用户输入
函数input()让程序暂停运行,等待用户输入。其接受一个参数,是向用户显示的提示或说明。
message = input("Hello!Input something:")
print(message)
Hello!Input something:hello
hello
使用函数input()时,Python将输入解读为字符串。如果要获得数字需要通过int()函数进行转换。
number = input("input a number please:")
number = int(number)
print(number + 5)
input a number please:3
8
while循环
while循环使用break跳出循环,使用continue跳出当前循环继续下一次循环。
for循环是一种遍历列表的有效方式,但在for循环中不应修改列表,否则将导致Python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可以使用while循环。其中最常见的应用是删除列表中所有的指定值。
animals = ['cat','dog','cat','cat','rabbit']
while 'cat' in animals:
animals.remove('cat')
print(animals)
['dog', 'rabbit']
使用for循环处理的话就会出错:
animals = ['cat','dog','cat','cat','rabbit']
for animal in animals:
if(animal == 'cat'):
animals.remove('cat')
print(animals)
['dog', 'cat', 'rabbit']