1、input方法
??函數(shù)input() 讓程序暫停運(yùn)行, 等待用戶輸入一些文本。 獲取用戶輸入后, Python將其存儲(chǔ)在一個(gè)變量中, 以方便使用。
name = input("Please enter your name: ")
print("Hello, " + name + "!")
??函數(shù)中的字符串是提示字符串,提示用戶應(yīng)該輸入什么樣的信息。當(dāng)提示字符串也可以先用變量保存,再在input()函數(shù)中使用該變量:
prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print("\nHello, " + name + "!")
2、int方法
??使用函數(shù)input() 時(shí), Python將用戶輸入解讀為字符串。
>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'
??從上面示例中可以看到讀入到age變量里面的是字符串'21',而不是數(shù)字21。如果這時(shí)候想要的是數(shù)字,就需要使用函數(shù)int()把輸入的字符串轉(zhuǎn)換為數(shù)值。
>>> age = input("How old are you? ")
How old are you? 21
>>> age = int(age)
>>> age
20
??從上面可以看到,age變量經(jīng)過(guò)int函數(shù)轉(zhuǎn)換后,已經(jīng)變成了數(shù)值。