一、input()输入
input()函数很简单,接受一个参数,中间可以加提示语句
#等待用户输入文本信息
name = input("please input your name:")
print('name:'+name)
结果:
please input your name:Alice
name:Alice
唯一需要注意的时input()返回的参数类型是一个字符串,因此如果想要得到时数值时,需要用到int()函数,将输入的字符串转换为数值,否则就会报错如:
age = input("please input your age:")
if age>18:
print("你是一个大人了")
TypeError: ‘>’ not supported between instances of ‘str’ and ‘int’
修改一下:
age = input("please input your age:")
age=int(age)#将age由字符串型转换为数值型
if age>18:
print("你是一个大人了")
please input your age:19
你是一个大人了
二、while循环
为什么不直接用for循环,而要用while循环?
这个要看具体情节来看,但是在python中for循环常用于遍历或者说条件有限的情况,而while循环用于给定一个条件,同时修改列表中元素的时候用。
用法:
while 条件:
在列表间移动元素
unconfirmed_users =['alice','brain','candace']#没有验证的列表
confirmed_users=[]#经过验证的列表
while unconfirmed_users:
user = unconfirmed_users.pop()
#从没有验证的列表中弹出最后一元素并赋值给user
print('verifying:'+user) #验证操作(模拟简单的)
confirmed_users.append(user)#加入验证过的列表中
print('\n验证过的用户:')
#输出验证过的列表,title()将首字母大写
for user in confirmed_users:
print('\t'+user.title())
verifying:candace
verifying:brain
verifying:alice
验证过的用户:
Candace
Brain
Alice
删除包含特定值的所有列表元素:
pets = ['dog','cat','fish','sheep','dog']
print('开始的pets:'+str(pets))
while 'dog' in pets: #删除列表中所有的cat
pets.remove('dog')
print('删除dog后的列表:'+str(pets))
开始的pets:[‘dog’, ‘cat’, ‘fish’, ‘sheep’, ‘dog’]
删除dog后的列表:[‘cat’, ‘fish’, ‘sheep’]
使用用户填入来填充字典
surveys ={} #建立空的调查字典
flag = True #用于判断是否继续调查
while flag:
name = input('\nyour name:')
city = input('which city do you like:')
surveys[name] = name
repeat = input('continu;(yes/no)')
if repeat == 'no':
flag = False
#打印调查结果
print('\n')
for name,answer in surveys.items():
print(name+" likes "+answer)