python基础5-用户输入与while循环

    获得用户输入是,使用`input()`函数。此外,还要使用while循环让程序不断运行,直到指定的条件不满足为止。

5.1、函数input()工作原理

input()让程序暂停运行,等待用户输入一些文本,获得用户输入后,将其存储在一个变量中,以方便程序使用。

message = input("Tell me something, and I will repeat it back to you: ")
print(message)

5.1.1、使用int()来获取数值输入

使用input()输入时,python将用户输入保存为字符串。

可以使用int()函数将input()获得的值转化为int类型

age = input("How old are you: ")
age = int(age)

5.1.2、求模运算符

求模运算符%将两个数相除并返回余数

4%3 = 1
5%3 = 2
number = input("Enter a number, and I`ll tell you if it`s even or odd: ")
number = int(number)

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

5.2、while循环

for循环针对集合中的每个元素,而while循环不断地运行,知道指定的条件不满足为止

5.2.1、使用while循环

你可以使用while循环来数数

current_number = 1
while current_number <= 5:
  print(current_number)
  current_number += 1

5.2.2、让用户选择何时退出

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

message = ""
while message != 'quit':
  message = input(prompt)
  print(message)

5.2.3、使用标志

定义一个变量,用于判断整个程序是否处于活动状态,这个变量被称为标志。

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)

5.2.4、使用break退出循环

要立即退出while循环,不在运行循环中余下的代码,可以使用break语句。

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

while True:
    message = input(prompt)

    if message == 'quit':
        break
    else:
        print(message)

5.2.5、在循环中使用continue

要返回到循环开头,并根据条件测试结果决定是否继续执行循环,可使用continue语句。

current_number = 0
while current_number < 10:
  current_number += 1
  if current_number % 2 == 0:
    continue
  
  print(current_number)

5.3、使用while循环来处理列表和字典

5.3.1、在列表之间移动元素

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

while unconfirmed_users:
  current_user = unconfirmed_users.pop()
  print("Verifying user: " + current_user.title())
  
  cofirmed_users.append(current_user)

5.3.2、删除列表中重复元素

删除列表中特定元素使用remove()函数,但是函数只能删除一个特定值,可以配合while遍历整个列表,将所有特定值全部删除

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

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

5.3.3、使用用户输入来填充字典

可使用while提示用户输入任意数量的信息。

response = {}

poll_active = True

while poll_active:
  name = input("\nWhat is your name?")
  response = input("which mountain sould you like to climb someday?")
  
  response[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 + ".")
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容