Python Course Design Note 2 of 52

Control Flow

Chapter02

Task Name - Control Flow

Task Overview

Study the documentation alongside the videos to learn arithmetic and logical operations in computing, as well as branching statements and loop statements

Community Topic

What are the respective use cases of Python’s while loop and for loop?

Details

  1. break exits the current loop level, while continue skips the current iteration and moves on to the next one.
  2. When you first start writing code, sort out the logical relationships first. You can write pseudocode first so you know what to write first and what to write next, and then write correct code using Python syntax

Check-in Requirements

Exercise 1

Write a user login authentication program. For example, the username is “Albert” and the password is “1”; ask the user to enter the username and password separately for authentication

Exercise 2

Write a program that prints user permissions; ask the user to enter a username for verification

Albert --> 超级管理员
tom  --> 普通管理员
jack,rain --> 业务主管
其他 --> 普通用户'

Exercise 3

Write a program that tells whether to go to work based on the current day; ask the user to enter the day to get the result

如果:今天是Monday,那么:上班
如果:今天是Tuesday,那么:上班
如果:今天是Wednesday,那么:上班
如果:今天是Thursday,那么:上班
如果:今天是Friday,那么:上班
如果:今天是Saturday,那么:出去浪
如果:今天是Sunday,那么:出去浪

Exercise 4

Write a program that verifies user login in a loop. After the user logs in successfully, entering “q” exits the program; if authentication fails, the user is asked to log in again repeatedly, and if the user still has not logged in successfully after more than 3 attempts, the program exits.

Exercise 5

Write an age-guessing game that allows the user up to 3 attempts. After every 3 attempts, if the user still hasn’t guessed correctly, ask whether they want to keep playing. If they answer Y or y, let them guess 3 more times, and so on; if they answer N or n, exit the program. If they guess correctly, exit immediately.

Exercise 6

Print the following results as required:

  1. Use a while loop to output 1 2 3 4 5 6 8 9 10
  2. Compute the sum of all numbers from 1 to 100
  3. Output all odd numbers from 1 to 100
  4. Output all even numbers from 1 to 100
  5. Compute the sum 1-2+3-4+5 … 99

Exercise 7

Print the following pyramid. The figure below is an isosceles triangle; each row always has two fewer stars than the row below it and sits directly above the row below (hint: use two nested for loops):

    *
   ***
  *****
 *******
*********