用户输入和while循环
input()函数
当代码运行到input()函数时,程序会等待用户输入一些文本。当用户输入一些信息并按下它时enter之后,程序将继续执行。
name = str(input("input your name,please\n")) print(f"{
name},Hello. This is Python‘s world") input your name,please Wu Wu,Hello. This is Python‘s world
程序执行到input()函数时,输出一句话,请求用户输入。当我们输入信息时,程序继续执行,并输入上述信息Wu输出,输出一句话。
使用int()转换输入的数据类型
input()函数默认输入类型为str类型,但有时用户输入某个数字的数据,然后我们处理这个数字数据,如加减乘除,但是str类型不能做这些事情,所以我们需要强制转换类型。这将被使用int()函数将数据转换为int类型的。
age = int(input('How old are you?:')) if age >= 18: print("You are an adult!") else: print("You are too young!") How old are you?:23 You are an adult!
在这里,可以看到int()调用函数input()函数实际上是这样的input()函数获得的数据传输到int()函数中,再由int()数据转换函数。如果没有数据转换?
age = input("How old are you?:") if age >= 18: print("You are an adult!") else: print("You are too young!") How old are you?:23 Traceback (most recent call last): File "E:\PycharmProjects\...py", line 10, in <module> if age >= 18: TypeError: '>=' not supported between instances of 'str' and 'int'
可以看出,我们也输入23,但程序没有输出我们想要的结果,而是报告了一个错误,因为上面提到的原因input()函数输入的数据默认为str类型,而str类型无法与int型进行比较。
age = int(input('How old are you?:'))
if age >= 18:
print("You are an adult!")
else:
print("You are too young!")
How old are you?:l23
Traceback (most recent call last):
File "E:\PycharmProjects\learn\While.py", line 8, in <module>
age = int(input('How old are you?:'))
ValueError: invalid literal for int() with base 10: 'l23'
同样,通过int()转换我们也可以确保输入的数据是一个数字,而并非什么其他的非法输入。当然一段更好的程序应该是这样的,
try:
age = int(input('How old are you?:'))
except ValueError:
print("input valid data!")
else:
if age >= 18:
print("You are an adult!")
else:
print("You are too young!")
How old are you?:!!!
input valid data!
这里使用了try-except模块进行异常处理。
求模运算符
处理数值时,求模运算符(%)是个很有用的工具。求模运算是将两个数相除,然后返回相除后的余数。
#求模运算 闰年
try:
year = int(input("input year: "))
except ValueError:
print("input valid data!")
else:
if (year % 4 == 0 or year % 400 == 0) and year % 100 != 0:
print(f"{
year} is leap year!")
else:
print(f"{
year} is not leap year!")
input year: 1900
1900 is not leap year!
闰年的计算规则是,“**四年一闰,百年不闰,四百年再闰”,**这样的话,就要求对输入的数据进行处理,将输入的年份对4求模为0,或者对400求模为0,并且对100求模不为0才能表明这个年份是闰年。用代码来表述就是if语句。同时用try-except来进行确保输入的数据是合法的数据。
while循环
while也可以用来进行循环。whie语句的使用是while 条件:如果条件判断结果为True,则继续执行循环,如果条件判断结果为False,则结束循环。
# while循环
count = 1
sum = 0
try:
number = int(input("input number: "))
except ValueError:
print("input valid data!")
else:
while count <= number:
sum += count;
count += 1
print("sum = ", sum)
input number: 10
sum = 55
这里我使用while循环来计算累加和,而不是使用计算公式。可以看到我输入10后,程序开始循环运行,得到最终55的结果。
使用break退出循环
有时候我们希望提前结束while循环,不再运行循环中的其他代码,这里我们就可以使用break来提前结束循环。 break语句用于控制程序流程, 可用来控制哪些代码行将执行、 哪些代码行不执行, 从而让程序按你的要求执行你要执行的代码。
使用continue来跳过某些代码
在while循环中,有些时候我们并不像结束循环,但是我们希望能够结束当次循环,对于某些代码而不进行执行。这个时候,我们就可以使用continue语句,它不像break语句那样直接跳出所有的循环,但是会结束当前的循环。
无限循环
有时候,我们并没有注意到我们代码中while循环的条件设置的并不合理,这就导致了while循环条件结果一直为True,使得while循环一直进行而无法终结,所以在写好一个while循环后,一定要对while循环进行相应的测试,确保其功能的合理性。当然,在运行的时候,如果发生了while循环一直进行可以用Ctrl+C来强制程序结束。
使用while循环处理列表和字典
“for循环是一种遍历列表的有效方式, 但不应在for循环中修改列表,否则将导致Python难以跟踪其中的元素。 要在遍历列表的同时对其进行修改, 可使用while循环。 通过将while循环同列表和字典结合起来使用, 可收集、 存储并组织大量输入, 供以后查看和显示。”
citieslist = ['Nanjing', 'Hangzhou', 'Shanghai', 'Beijing']
Havebeen = []
city = str(input('What cities have you been to?: '))
while city != 'quit':
if city in citieslist:
Havebeen.append(city)
citieslist.remove(city)
else:
Havebeen.append(city)
city = str(input('What cities have you been to?: '))
print(citieslist)
print(Havebeen)
What cities have you been to?: Nanjing
What cities have you been to?: Qingdao
What cities have you been to?: quit
['Hangzhou', 'Shanghai', 'Beijing']
['Nanjing', 'Qingdao']
通过while,我们可以实现数据在列表之间的移动。
删除列表中的数据
我们也可以通过while循环来删除列表中,一些我们不需要的数据。
citieslist = ['Nanjing', 'Hangzhou', 'Shanghai', 'Beijing', 'Nanjing', 'Yangzhou', 'Nanjing']
while 'Nanjing' in citieslist:
citieslist.remove('Nanjing')
print(citieslist)
['Hangzhou', 'Shanghai', 'Beijing', 'Yangzhou']
这里,以 ‘Nanjing’ in citieslist作为一个条件语句,正如之前所提到过的,in 会返回True/False的结果,如果返回True就会执行while循环中的语句,来删除citieslist中的‘Nanjing’