Python基础学习-用户输入和while循环

时间:2022-05-07
本文章向大家介绍Python基础学习-用户输入和while循环,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一:函数input()的工作原理:

函数input()让程序暂停运行,等待用户输入一些文本。

获取用户输入后,Python将其存储在一个变量中,以方便使用。

1:编写清晰的程序:

# 函数input()让程序暂停运行, 等待用户输入一些文本, 并在用户按回车键后继续运行
message = input("Tell me something, and I will repeat it back to you: ")
print(message)

# 通过在提示末尾(这里是冒号后面)包含一个空格, 可将提示和用户输入分开
name = input("Please enter your name: ")
print("Hello, " + name + " !")

# 提示可能超过一行, 在这种情况下,可将提示存储在一个变量中
prompt = "If you tell us who you are, we can personalize the message you see "
prompt += "nWhat is you first name? "
name = input(prompt)
print("nHello, " + name + " .")
输出:

 2:使用int()来获得数值输入
     使用函数input()时,Python将用户输入解读为字符串
 函数int()可将数字的字符串表示转换为数值表示
# 使用int()来获取数值输入
age = input("How old are you? ")
age = int(age)
print(age >= 18)
输出:


3:求模运算符:
求模运算符(%)是一个很好用的工具,它将两个数相处并返回余数。
# 求模运算符(%), 它将两个数相除并返回余数
print(4%3)
print(5%3)
print(6%3)
print(7%3)
输出:

4:在Python2.7中获取输入:
如果你使用的是Python2.7,请使用raw_input(),而不是input()来获取输入

二:while循环简介:
     for循环用于针对集合中的每个元素的一个代码块,
     而while循环不断地运行,直到指定的条件不满足为止。

1:使用while循环:# 使用while循环
current_number = 1
while current_number <= 5:
    print(current_number)
    current_number += 1
输出:12345

2:让用户选择何时退出:# 让用户选择何时退出
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 everyoneHello everyone
Tell me something, and I will repeat it back to you: Enter 'quit' to end the program.quit
3:使用标志:在其中的任何一个事件导致活动标志变成False时,
主游戏循环将退出。# 使用标志
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)

4:使用break退出循环:在任何Python循环中都可以使用break语句。# 使用break来退出循环
prompt = "nPlease enter the name of a city you have visited"
prompt += "n(Enter 'quit' to end the program.)"

while True:
    city = input(prompt)

    if city == "quit":
        break
    else:
        print("I'd love to go to " + city.title() + " .")
输出:Please enter the name of a city you have visited(Enter 'quit' to end the program.)chongqingI'd love to go to Chongqing .
Please enter the name of a city you have visited(Enter 'quit' to end the program.)quit
5:在循环中使用continue:跳过当前循环,执行下一循环。# 在循环中使用continue
current_number = 0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue

    print(current_number)
输出:13579
6:避免无限循环:如果程序陷入无限循环,可按Ctri+C,
   也可关闭显示程序输出的终端窗口。
   
三:使用while循环来处理列表和字典:
    要在遍历列表的同时对其进行修改,可使用while循环。
通过将while循环同列表和字典结合起来使用,可收集、
存储并组织大量输入,供以后查看和显示。

1:在列表之间移动元素:# 在列表之间移动元素
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:CandaceVerifying user:BrianVerifying user:Alice
The following users have been confirmed:CandaceBrianAlice
2:删除包含特定值的所有列表元素:# 删除包含特定值的所有列表元素
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']
     
3:使用用户输入来填充字典:# 使用用户输入来填充字典
responses = {}

# 设置一个标志,指出调查是否继续
polling_active = True

while polling_active:
    # 提示输入被调查者的名字和回答
    name = input("nWhat's your name? ")
    response = input("Which mountain would you like to climb someday? ")

    # 将答案存储在字典中
    responses[name] = response

    # 看看是否还有人要参加调查
    repeat = input("Would 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 + " would like to climb " + response + " .")
输出:What's your name? youWhich mountain would you like to climb someday? DenaliWould you like to let another person respond? (yes/ no) no
----Poll Results---you would like to climb Denali .
最后,我很抱歉,没能够解决代码块在推文中如何完美显示这个重大问题。
我会努力找到解决办法的。


每天学习一点点,每天进步一点点。
-看完了请点个赞鼓励一下辛勤的小编嘛-