python input函數


python input函數

覺得有用的話,歡迎一起討論相互學習~


我的微博我的github我的B站

  • 對於python的input函數需要從python2和python3兩方面講。
  • 對於python3,通過input函數輸入的所有內容都會作為str類型的字符串變量傳入,只需要使用int和float進行強制類型轉換就可以。
# python3
d=float(input('Please enter what is your initial balance: \n'))
p=float(input('Please input what is the interest rate (as a number): \n'))
Please enter what is your initial balance:
50000
Please input what is the interest rate (as a number):
2.3
  • 對於python2,input函數可以識別輸入的是int還是float,但是String類型的一定要""引號引起來,否則會出現錯誤。
# python2
>>>a = input("input:")
input:123                  # 輸入整數
>>> type(a)
<type 'int'>               # 整型
>>> a = input("input:")    
input:"runoob"           # 正確,字符串表達式
>>> type(a)
<type 'str'>             # 字符串
>>> a = input("input:")
input:runoob               # 報錯,不是表達式,輸入的runoob必須用括號括起來
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'runoob' is not defined
<type 'str'>
  • python2中的raw_input() 函數和python3中的input函數是一樣的使用方法,將命令行的輸入都會視為string類型。
# python2
>>>a = raw_input("input:")
input:123
>>> type(a)
<type 'str'>              # 字符串
>>> a = raw_input("input:")
input:runoob
>>> type(a)
<type 'str'>              # 字符串
>>>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM