Implement Python code, input a number, and output three times that number.
>>> n = input("Enter a number: ") Enter a number: 6 >>> print(f"{n} * 3 = {n*3}") 6 * 3 = 666
The input function always returns a string. You can convert strings to integers by int:
>>> n = int(n) >>> print(f"{n} * 3 = {n*3}") 6 * 3 = 18
However, if the input is not a value, an error will be reported:
Enter a number: abcd ValueError: invalid literal for int() with base 10: 'abcd'
A common approach is to run the transformation in a "try" block and catch any exceptions we might get. But the isdigit method of strings can solve this problem more elegantly.
>>> '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 returns True for the regular expression '^ \ d + $'.
>>> n = input("Enter a number: ") >>> if n.isdigit(): n = int(n) print(f"{n} * 3 = {n*3}")
- Reference material
- Discussion on qq group 144081101 591302926 567351477
- Address of the latest version of this article
- python test development library involved in this article Thanks a lot!
- This article related massive books Download
- 2018 best artificial intelligence machine learning tool book and download (continuous update)
Python also includes another method, str.isnumeric. What's the difference between them?
>>> n = input("Enter a number: ") >>> if n.numeric(): n = int(n) print(f"{n} * 3 = {n*3}")
str.isdigit returns True when the string contains only numbers 0-9. str.isnumeric can also recognize the value of English unexpected language.
>>> 'One two three four five'.isdigit() False >>> 'One two three four five'.isnumeric() True >>> int('Two') ValueError: invalid literal for int() with base 10: 'Two'
str.isdecimal
>>> s = '2²' # or if you prefer, s = '2' + '\u00B2' >>> s.isdigit() True >>> s.isnumeric() True >>> s.isdecimal() False