第七章 用户输入和while循环
①input()和int()
input()将用户输入解读为字符串。int()则将这个字符串转化成了数值。只有数值之间可以比较大小。否则会报“类型错误”的提示。
name=input("Please input you name : ")
age=input("Please input you age : ")
message = 'Hello !'+age+"'s "+name+'.'
message += '\nWlecome to Python!'
print(message)
#
Please input you name : Sanmu
Please input you age : 19
Hello !19's Sanmu.
Wlecome to Python!
②while循环简介
message = "Guess who I am ?"
name = ""
while name != 'sanmu':
name = input(message)
if name == 'sanmu':
print("Yes,I'm sanmu.")
elif name != 'sanmu':
print("WRONG!")
使用标志:
在很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为 标志。
message = "Guess who I am ?"
logo=True
name = ""
while logo:
name = input(message)
if name == 'sanmu':
print("Yes,i am sanmu.")
logo = False
elif name != 'sanmu':
print("WRONG!")
这样做的好处非常明显。我们将active设成true,让程序最初处于活动状态,这样简化了while的语句。
同时在多个条件的循环中,可以分别在不同条件情况下设置真假值,来达到通过控制程序活动的目的。
message = "Guess who I am ?"
name = ""
while True:
name = input(message)
if name == 'sanmu':
print("Yes,i am sanmu.")
break
elif name != 'sanmu':
print("WRONG!")
在任何Python循环中都可以使用break语句,例如,可以使用break语句来退出遍历链表或字典的for循环
要返回到循环开头,并根据条件测试结果决定是否继续循环使用continue语句。
它不像break语句那样不再执行余下的代码并退出整个循环。
num = 0
while num <= 10:
num += 1
if num %3 == 0:
print(num)
continue
3
6#如果是break
9#则只执行一次,即输出3
③使用while循环来处理列表和字典
competitors = ["Jacklove",'Theshy',"Rookie",'Feaker']
print(competitors)
competitors_01 = ()
while competitors:
competitors_01=competitors.pop()
print(competitors_01)
print(competitors)
['Jacklove', 'Theshy', 'Rookie', 'Feaker']
Feaker
Rookie
Theshy
Jacklove
[]
competitors = ['Theshy',"Jacklove",'Theshy','Theshy',"Rookie",'Feaker','Theshy']
print(competitors)
competitors_01 = ()
while 'Theshy' in competitors:
#错误示范:while competitors:
competitors.remove('Theshy')
print(competitors)
#正确输出:
['Theshy', 'Jacklove', 'Theshy', 'Theshy', 'Rookie', 'Feaker', 'Theshy']
['Jacklove', 'Rookie', 'Feaker']
#错误输出:
competitors.remove('Theshy')
ValueError: list.remove(x): x not in list
['Theshy', 'Jacklove', 'Theshy', 'Theshy', 'Rookie', 'Feaker', 'Theshy']
#录入选手的赛区
competitors = {
}
logo = True
while logo:
name = input("competitors's name is :")
zone = input("He plays in :")
competitors[name] = zone
repeat = input("Do you want to input again?(YES/NO)")
if repeat == 'NO':
logo = False
print(competitors)
for key, value in competitors.items():
print(key + ' plays in ' + value + '.')
competitors's name is :The shy
He plays in :lpl
Do you want to input again?(YES/NO)yes
competitors's name is :Feaker
He plays in :lkl
Do you want to input again?(YES/NO)NO
{
'The shy': 'lpl', 'Feaker': 'lkl'}
The shy plays in lpl.
Feaker plays in lkl.