您的位置:首页 > 编程语言 > Python开发

自学Python:第7篇——用户输入与while循环

2018-03-04 16:20 781 查看
input()
函数input()接受一个参数:即要向用户显示的提示或者说明,让用户知道该如何做
注意:使用input,python将用户输入解读为字符串

在文本编辑器里面先码好:
name=input("Tell me your name:")
print("Hello, "+name)
运行:
Tell me your name:Torres
>>> name
'Torres'

使用int()来获取数值输入
age=input("Tell me your age:")
age=int(age)
if age >= 18:
    print("Your are a adult")

可见,int()把age变成了整数

求模运算符%
可以利用%来判断一个数是奇数还是偶数
num=input("Give me a number:")
num=int(num)
if (num%2)==0:
    print("even")
else:
    print("odd")

while循环

示例(求平方和)
k=1
s=0
while k<=5:
    s+=k*k
    k=k+1
print(s)

>>>55

如果要立即退出while循环,可以使用break语句
message=input("tell me something:")
while 1:
    print("good")
    message=input("tell me something:")
    if message=='quit':
        break

continue语句
跳出本次循环,进入下一次循环
while 1:
    message=input("tell me something:")
    if message=='quit':
        continue
    print("good")
        
次程序的不足之处在于,是一个死循环,永远无法跳出来
所以写循环模块时要注意循环出口

使用while循环来处理列表和字典
for循环适于遍历列表,while适于遍历列表的同时对其进行修改

在列表之间移动元素
new_p=['messi','kaka','toni']
famous_p=[]
while new_p:
    x=new_p.pop()
    famous_p.append(x)
print(new_p)    
print(famous_p)

[]
['toni', 'kaka', 'messi']

删除包含特定值的所有列表元素
使用remove()
num=[1,1,1,2,3,4,5]
while 1 in num:
    num.remove(1)
print(num)

[2, 3, 4, 5]
注:每次循环只删除一个元素

使用用户输入来填充字典
result={}
mood=True
while mood:
    name=input("Tell me your name: ")
    age=input("Tell me your age: ")
    result[name]=age
    repeat=input("Continue? Y/N: ")
    if repeat=='N':
        mood=False
print("Here are the results")
print(result)

Tell me your name: YY
Tell me your age: 90
Continue? Y/N: Y
Tell me your name: ll
Tell me your age: 89
Continue? Y/N: N
Here are the results
{'YY': '90', 'll': '89'}

        

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: