實作Python代碼,輸入數字,然後輸出這個數字的三倍。
>>> n = input("Enter a number: ")
Enter a number: 6
>>> print(f"{n} * 3 = {n*3}")
6 * 3 = 666
input函數總是傳回字元串。可以通過int轉換字元串為整數:
>>> n = int(n)
>>> print(f"{n} * 3 = {n*3}")
6 * 3 = 18
但是,如果輸入不是數值,則會報錯:
Enter a number: abcd
ValueError: invalid literal for int() with base 10: 'abcd'
比較常用的方法是在“try”塊中運作轉換,并捕獲我們可能獲得的任何異常。但字元串的isdigit方法可以更優雅地解決這個問題。
>>> '1234'.isdigit()
True
>>> '1234 '.isdigit() # space at the end
False
>>> '1234a'.isdigit() # letter at the end
False
>>> 'a1234'.isdigit() # letter at the start
False
>>> '12.34'.isdigit() # decimal point
False
>>> ''.isdigit() # empty string
False
str.isdigit對正規表達式'^ d + $'傳回True。
>>> n = input("Enter a number: ")
>>> if n.isdigit():
n = int(n)
print(f"{n} * 3 = {n*3}")
- 參考資料
- 原文: https://www.jianshu.com/p/ba90e1f58f51
- 釘釘支援群: 21745728
- 本文涉及的python測試開發庫 謝謝點贊!
- 本文相關海量書籍下載下傳
- 2018最佳人工智能機器學習工具書及下載下傳(持續更新)
Python還包括另一方法str.isnumeric,他們有什麼差別?
>>> n = input("Enter a number: ")
>>> if n.numeric():
n = int(n)
print(f"{n} * 3 = {n*3}")
字元串隻包含數字0-9時str.isdigit傳回True。str.isnumeric則還能識别英語意外語言的數值。
>>> '一二三四五'.isdigit()
False
>>> '一二三四五'.isnumeric()
True
>>> int('二')
ValueError: invalid literal for int() with base 10: '二'
str.isdecimal
>>> s = '2²' # or if you prefer, s = '2' + '\u00B2'
>>> s.isdigit()
True
>>> s.isnumeric()
True
>>> s.isdecimal()
False