Chapter 7 user input and while loop

7.1 working principle of function input()

The function input() has a parameter, which can be displayed to the user for prompt; The function input() pauses the program and waits for the user to enter some text

message = input("Tell me something, and I will repeat it back to you:")
print(message)
'''
If you enter: Hello, everyone!
The screen also displays: Hello, everyone!
'''

7.1.1 write clear procedures

Tips and suggestions on function input()

  1. A space is included at the end of the prompt, so that the prompt information is separated from user input
  2. If the prompt information is too complex, it can be passed with a variable
prompt = "If you tell us who are you,we can personalize the message you see."
prompt += "\nWhat's your first name? "

name = input(prompt)
print(f"\nHello, {name}!")
'''
The code is executed as follows:
If you tell us who are you,we can personalize the message you see.
What's your first name? zhang xy

Hello, zhang xy!

'''

7.1.2 use input() to get numeric input

When using the function input(), the user input is parsed into a string. If you want to use an integer, you can use the function int()

age = input("How old are you? ")
print(type(age))

age = int(age)
print(type(age))
'''
Output:
How old are you? 18
<class 'str'>
<class 'int'>

'''

7.1.3 modulo operator

%Modulo two numbers and return the remainder, such as:
4% 3 returns 1

7.2 while loop

Both for and while statements are loops. For is generally used for traversal and while is generally used for continuous execution until the conditions are not met

7.2.1 using the while loop

current_number = 1

while current_number <= 5:
    print(current_number)
    current_number += 1
'''
Output:
1
2
3
4
5

'''

7.2.2 let the user choose when to exit

Define an exit value in the while loop to launch the loop program

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the programe. "

message = ""
while message != 'quit':
    message = input(prompt)
    if message != 'quit':
        print(message)
'''
Output:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. hello world
hello world

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. 123
123

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. quit

'''

7.2.3 use signs

If there are more than one exit condition, if the exit condition is set as in the previous program, the inspection condition will be complex and difficult. At this time, the flag bit can be used (the inspection and change of the flag bit can be placed elsewhere)

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the programe. "

active = True
while active:
    message = input(prompt)
    if message == 'quit':
        active = False
    else:
        print(message)
'''
Output:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. hello
hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. 123
123

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. quit

'''

7.2.4 using break to exit the loop

Use the break statement to exit the loop immediately without executing all the remaining code in the loop

prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the programe. "

while True:
    message = input(prompt)
    if message == 'quit':
        break
    else:
        print(message)
'''
Output:

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. hello
hello

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. 123
123

Tell me something, and I will repeat it back to you:
Enter 'quit' to end the programe. quit

'''

7.2.5 using the continue statement in a loop

The continue statement will exit this cycle and will not execute the rest of the code in this cycle. Note the difference between the continue statement and the break statement

# Use continue to exit this cycle
current_number = 0

while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue
    print(current_number)
'''
Output:
1
3
5
7
9

'''
# Use break to exit the loop
current_number = 0

while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        break
    print(current_number)
'''
Output:
1

'''

7.2.6 avoid infinite cycles

The while loop must have explicit exit conditions, or the program will execute endlessly

7.3 using the while loop to process lists and dictionaries

For loop is an effective way to traverse the list, but the list should not be modified in the for loop, otherwise it will be difficult to track the elements in it; To modify the list while traversing it, you can use the while loop

7.3.1 moving elements between lists

There are newly registered but unauthenticated users in a list. After user authentication, move the user to the authenticated user list

unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []

while unconfirmed_users:
    confirmed_user = unconfirmed_users.pop()

    print(f"Verifying user:{confirmed_user.title()}")
    confirmed_users.append(confirmed_user)

print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())
'''
Output:
Verifying user:Candace
Verifying user:Brian
Verifying user:Alice

The following users have been confirmed:
Candace
Brian
Alice

'''

7.3.2 delete all list elements with specific values

pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)

while 'cat' in pets:
    pets.remove('cat')

print(pets)
'''
Output:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

'''

7.3.3 use user input to populate the dictionary

You can use the while loop to store what someone says in a dictionary

responses = {}
polling_active = True

while polling_active:
    name = input("\nWhat's your name? ")
    response = input("What would you want to say? ")
    responses[name] = response # Store sb's words in a dictionary

    repeat = input("Any one else?('yes' or 'no') ")
    if repeat == 'no':
        polling_active = False

print(responses)
print(f"\n{'Poll Result':=^40}")
for name,response in responses.items():
    print(f"{name} says: {response}.")
'''
Output:

What's your name? zhang xy
What would you want to say? python would change world
Any one else?('yes' or 'no') yes

What's your name? mao
What would you want to say? good good study, day day up
Any one else?('yes' or 'no') no
{'zhang xy': 'python would change world', 'mao': 'good good study, day day up'}

==============Poll Result===============
zhang xy says: python would change world.
mao says: good good study, day day up.

'''

7.4 summary

slightly

Tags: Python

Posted on Thu, 14 Oct 2021 20:26:42 -0400 by HokieTracks