用户输入和while循环

1.函数input()的工作原理

函数input()让程序暂停,等待用户输入一些文本,获取到用户输入的文本赋给一个变量,用户输入后按下Enter键继续执行

1.1 编写清晰的程序

每当使用函数input()时,都应指定清晰易懂的提示,让用户来进行输入
在提示末尾添加包含一个空格,可将提示和用户输入的内容分隔开
提示超过一行,可将提示内容赋给一个变量,再将该变量传递给函数input()
例如:

promote = "If you tell us who you are, we can peisonalize the message for you see."
promote += "\n What is your first name?"

name = input(promote)
print(f"\n Hello,{name}! ")

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

  • 使用函数input()时,python将用户输入的内容解读为字符串
  • 可使用int()函数来将用户输入的内容转变成数值
    例如:
age = int(input("How old are you ?"))

1.3 求模运算符

  • 求模运算符%将两个数相除并返回余数
  • 如果一个数可以被另外一个数整除,求模运算返回的是0

2. while循环

2.1 使用while循环

  • while循环不断运行,直到指定的条件不满足为止
  • for循环用于针对集合中的每个元素都执行一个代码块

2.2 让用户选择何时退出

  • 可以使用while循环在用户愿意的时候不断运行,当用户不想while循环继续运行的时候,由用户输入指定的退出值来决定while循环不再循环

    例如:

    promote = "Tell me your name , i will repeat it back to you: "
    promote += "\n Enter 'quit' to end the program."
    message = ''
    while message != 'quit':
      message = input(promote)
      print(message)
    

2.3 使用标志

promote = "Tell me your name , i will repeat it back to you: "
promote += "\n Enter 'quit' to end the program."
message = ''
active = True
while active:
  message = input(promote)
  
  if message == 'quit':
    active = False
  else:
    print(message)

2.4 使用break退出循环

要立即退出循环不再执行余下的代码,也不管测试条件的结果如何,使用break语句

promote = "Tell me your name , i will repeat it back to you: "
promote += "\n Enter 'quit' to end the program."
message = ''
while True:
  message = input(promote)
  
  if message == 'quit':
    break
  else:
  	print(message)

2.5 在循环中使用continue

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

例如:

#打印1-10所有奇数
current_number = 0
while current_number < 10:
  current_number += 1
  if current_number % 2 == 0:
    continue
  print(current_number)

2.6 避免无限循环

确保while循环中有一个地方能够让测试条件变为False

3. 使用while处理字典和列表

3.1 在列表之间移动元素

例如:

unconfirmed_users = ['alice','brian','candace']
confirmed_users = []
while uncomfirmed_users:
  current_users = uncomfirmed_users.pop()
  confirmed_users.append(current_users)
  

3.2 删除为特定值的所有列表元素

例如:

pets = ['cat','dog','rabbit','cat']
while 'cat' in pets:
  pets.remove('cat')

3.3 使用用户输入来填充字典

例如:

responds = {}
polling_active = True
while polling_active:
  name = input("\n What is your name? ")
  respond = input("Which mountain would you like to climb someday? ")
  
  responds['name'] = respond
  
  repeat = input("Would you like to let another person respond? (yes/no) ")
  if repeat == 'no':
    polling_active = False
for name,respond in responds.items():
  print(f"{name} would like to climb {respond}")
posted @ 2021-11-30 11:42  写代码的小灰  阅读(106)  评论(0)    收藏  举报