1. 程式人生 > >自學Python:第7篇——使用者輸入與while迴圈

自學Python:第7篇——使用者輸入與while迴圈

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'}