python6-while循环

一、用户输入和while循环

1、函数input()的工作原理:让程序暂停运行,等待用户输入一些文本(字符串),获取用户输入后,python将其存在变量中,方便使用。

  input()接受一个参数,即要想用户显示的提示或说明,让用户知道该怎么做。

    * 有时提示超过一行,可以使用拼接方式进行输出;

1 prompt="If you tell us who you are,we can personalize the message you see."
2 prompt+="
What is your first name?"
3 name=input(prompt)
4 print("
Hello!"+name)

    * 使用int()获取数值输入;

height=int(input("Input you height(cm):"))
if height>=200:
    print("You are so tall!")
elif(height>=150&&height<200):
    print("Normal height")
else:
    print("short ")

    * 求模运算符%:返回两数相除后的余数。

      - 若可被整除,余数为0,反则输出余数;

      - 可用于判断一个数是奇数还是偶数;

1 number=int(input("Enter a number ,I'll tell you if it's even or odd:"))
2 if number%2==0:
3     print("It's even")
4 else:
5     print("odd")

二、while循环

  for循环用于针对集合中每个元素都一个代码块。而while则是不断运行,直到条件不满足。

  1、while循环

    1)使用while循环;

    2)让用户选择何时退出;

    3)使用标志:要求条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否都处于活动状态,该变量被称为标志。这样在while循环中只需检查一个条件,标志当前值是否为True。

1 prompt="Tell me something,and I will repeat it back ti you."
2 prompt+="
Enter 'quit' to end the program."
3 active=True
4 while active:
5     message=input(prompt)
6     if message=='quit':
7         active=False
8     else:
9         print(message)

   4)使用break退出循环——直接退出整个循环(可用于退出遍历列表/字典的for循环) 

1 prompt="输入你想去的城市."
2 prompt+="
输入'quit'退出程序."
3 while True:
4     city=input(prompt)
5     if city=='quit':
6         break
7     else:
8         print(city)        

    5)使用continue在循环中:返回到循环开头,并依据条件测试结果决定是否继续执行循环。

1 # 打印0-10中的偶数
2 number=0
3 
4 while number<10:
5     number+=1
6     if number%2==0:
7         continue

    6)避免无限循环

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

  for循环是种遍历列表的有效方式,但for循环中不应该修改列表,否则将导致Python难跟踪其中的元素,故可用while循环将列表和字典组合起来使用,可收集存储并组织大量输入,供以后查看和显示。

 1、列表之间移动元素

   情况:一个列表包含新注册的用户但还未验证的网站用户:验证这些用户后,将其从未验证的用户列表中提取出来,再将其加入到另一个已验证的用户列表中。

 1 # 创建待验证用户列表
 2 unconfirmed_users=['alice','brian','candace']
 3 confirmed_users=[]
 4 # 验证每个用户,直到没有未验证的用户为止
 5 # 将每个经过验证的列表都一道已验证的用户列表中
 6 while unconfirmed_users:
 7     current_user=unconfirmed_users.pop()
 8     print("Verfying user:"+current_user.title())
 9     confirmed_users.append(current_user)
10 print("The following users have been confirmed:")
11 for confirmed_user in confirmed_users:
12     print(confirmed_user.title())

  2、删除包含特定值的所有列表元素

    * remove()  删除值在列表中只出现过一次;

    * 循环语句配合remove()使用;

1 pets=['dog','cat','duck']
2 print(pets)
3 while 'cat' in pets:
4     pets.remove('cat')
5 print(pets)

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

  创建一个调查程序,其中的循环每次执行都提示输入被调查者的名字和回答,我们将收集的数据存在一个字典中,以便将回答和调查者关联起来。

  

原文地址:https://www.cnblogs.com/Free-Ink/p/12604523.html