您好,登錄后才能下訂單哦!
小編給大家分享一下python中獲取用戶輸入的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
整數輸入
#!/usr/bin/python3 usr_ip = input("Enter an integer number: ")
# 需要將輸入的字符串顯式地指定為需要的類型
usr_num = int(usr_ip) sqr_num = usr_num * usr_num print("Square of entered number is: {}".format(sqr_num))
讓我們給定一個整數和字符串來測定這個程序
Python docs - 整數文本
$ ./user_input_int.py Enter an integer number: 23 Square of entered number is: 529 $ ./user_input_int.py Enter an integer number: abc Traceback (most recent call last): File "./user_input_int.py", line 6, in <module> usr_num = int(usr_ip) ValueError: invalid literal for int() with base 10: 'abc'
浮點數輸入
#!/usr/bin/python3 usr_ip = input("Enter a floating point number: ") # 需要將輸入的字符串顯式地指定為我們需要的類型 usr_num = float(usr_ip) sqr_num = usr_num * usr_num # 限制小數點位數 print("Square of entered number is: {0:.2f}".format(sqr_num))
E 科學計數法在需要時可以使用
Python文檔 - 浮點數文本
Python文檔 - 浮點數
$ ./user_input_float.py Enter a floating point number: 3.232 Square of entered number is: 10.45 $ ./user_input_float.py Enter a floating point number: 42.7e5 Square of entered number is: 18232900000000.00 $ ./user_input_float.py Enter a floating point number: abc Traceback (most recent call last): File "./user_input_float.py", line 6, in <module> usr_num = float(usr_ip) ValueError: could not convert string to float: 'abc'
字符串輸入
#!/usr/bin/python3 usr_name = input("Hi there! What's your name? ") usr_color = input("And your favorite color is? ") print("{}, I like the {} color too".format(usr_name, usr_color))
不像Perl,字符串輸入不需要進行類型轉換和注意換行符
$ ./user_input_str.py Hi there! What's your name? learnbyexample And your favorite color is? blue learnbyexample, I like the blue color too
看完了這篇文章,相信你對python中獲取用戶輸入的方法有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。