Python learning path 6 - user input and while loop

This series is a compilation of notes for the introductory book "Python Programming: From Getting Started to Practice", which belongs to the primary content. The title sequence follows the title of the book.
This chapter mainly introduces how to perform user input, loops, and the , statement whileused in conjunction with loops .breakcontinue

input() function

In Python, use input()functions to get user input, please note here: input()the return value is a string . If the input is a number and it is to be used in subsequent calculations, type conversion is required.
input()The function can pass a string parameter as an input prompt, as follows:

# 代码:
number = input()
# 判断数据类型的两种方法
print(type(number))
print(isinstance(number, str))

print(int(number) ** 2)    # int()函数将字符串转换成整数

# 如果提示超过一行,可以将提示放在变量中,再将变量传入input();
# 并且最好在提示后面留一个空格以区分提示和用户输入
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

# 结果:
123
<class 'str'>
True
15129
Tell me something, and I will repeat it back to you: Hello, everyone!
Hello, everyone!

Judging parity (as a supplement to the common operations above): take the modulo operation %and return the remainder

# 代码:
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)

if number % 2:
    print("\nThe number " + str(number) + " is even.")
else:
    print("\nThe number " + str(number) + " is odd.")

# 结果:
Enter a number, and I'll tell you if it's even or odd: 123

The number 123 is even.

Introduction to while loops

forA loop is used for one block of code for each element in the collection, and the whileloop runs continuously until the specified condition is not met. For example, let the user choose when to log out:

# 代码:
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != "quit":
    message = input(prompt)
    if message != "quit":
        print(message)

# 结果:
Tell me something, and I will repeat it back to you:
Enter 'quit' to end the program. Hello everyone!
Hello everyone!

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

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

use logo

In the above code, we directly judge the input data, which is feasible in a simple program, but in a complex program, if there are multiple states at the same time to decide whether whileto continue the loop or not, if the above method is still used, the whileloop will Conditional judgment will be very long and complex. In this case, a variable can be defined as a flag to replace multiple conditions. Rewrite the above code using flags:

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

active = True
while active:
    message = input(prompt)
    if message != "quit":
        active = False
    else:
        print(message)

Flags are useful in complex programs, such as games where many events cause the program to stop running: when any of these events cause the active flag to change False, the main game loop will exit.

Use break to exit the loop

To exit whileor forloop immediately, without executing the rest of the code in the loop, regardless of the result of the conditional test, use the breakstatement. Then rewrite the above code using the flag to break:

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

while True:
    message = input(prompt)
    if message != "quit":
        break
    print(message)

Use continue in a loop

continueUse a statement if you want to return to the beginning of the loop instead of breaking out of the loop when a condition is met . Here is the code to print all odd numbers from 1 to 10:

# 代码:
count = 0
while count < 10:
    count += 1
    if count % 2 == 0:
        continue
    print(count)

# 结果:
1
3
5
7
9

The difference between break and continue : breakskip all the remaining code in the loop body and jump out of the loop; continueskip all the remaining code in the loop body and go back to the beginning of the loop body to continue execution instead of jumping out of the loop body.
It is worth reminding that when writing loops, you should avoid infinite loops , or infinite loops . For example, whilethe loop forgets to increment the variable.

Use while loops to process lists and dictionaries

Move elements between lists

To make an unauthenticated user authenticated into an authenticated user:

# 代码:
unconfirmed_users = ["alice", "brian", "candace"]
confirmed_users = []

while unconfirmed_users:
    current_user = unconfirmed_users.pop()

    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)

print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
    print(confirmed_user.title())

# 结果:
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

Remove all list elements that contain a specific value

Functions were used in previous chapters remove()to remove values ​​from a list, but only the first specified value in the list was removed. The following code loops to remove the specified values ​​from the list:

# 代码:
pets = ["dog", "cat", "dog", "goldfish", "cat", "rabbit", "cat"]
print(pets)

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

print(pets)

# 结果:
['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
['dog', 'dog', 'goldfish', 'rabbit']

Populate a dictionary with user input

# 代码:
responses = {}

# 设置一个标志,指出调查是否继续
polling_active = True
while polling_active:
    # 提示输入被调查者的名字和回答
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    # 将回答存入字典
    responses[name] = response

    # 是否还有人要参与调查
    repeat = input("World you like to let another person respond?(yes/ no) ")
    if repeat == "no":
        polling_active = False

# 调查结束,输出结果
print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name + " world like to climb " + response + ".")

# 结果:
What is your name? Eric
Which mountain would you like to climb someday? Denali
World you like to let another person respond?(yes/ no) yes

What is your name? Lynn
Which mountain would you like to climb someday? Devil's Thumb
World you like to let another person respond?(yes/ no) no

--- Poll Results ---
Eric world like to climb Denali.
Lynn world like to climb Devil's Thumb.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325657976&siteId=291194637