(我對python很陌生)所以我試圖制作一個迷你專案來反轉字串中的所有數字。但首先我必須檢查用戶輸入的內容是否是數字。但即使用戶輸入的是整數,PyCharm 也會跳過該 if 陳述句。你們中的任何人都可以幫助我嗎?代碼:
print('type a random number consisting of 10 digits')
l1 = 0
def loop1():
global l1
l1 = int(input())
if l1 == int():
if len(l1) != 10:
print("The number you have entered does not consist of 10 digits. "
"Please enter a number consisting of 10 digits.")
loop1()
else:
print("You have not entered a proper number. Please enter a proper number")
loop1()
loop1()
l1 = list(l1)
print(l1[0: 10: 2])
uj5u.com熱心網友回復:
如果 l1 == int():
測驗if l1 == 0:。要測驗是否something為整數,請使用isinstance(something, int). 在您的代碼中不起作用,因為int(input())如果輸入任何非整數,您將拋出例外。
你應該避免使用全域變數。不要遞回呼叫您的函式以使其“回圈”。將字串轉換為 int 時,您需要捕獲因輸入非整數而產生的錯誤。
檢查輸入數字字串表示的長度時,您需要轉換然后再次字串化以避免像這樣的輸入
"0000000000" --> 0 --> "0" # length 1
這可以這樣做:
def ask_for_int_of_length(text, lenght):
"""Aks for an integer, loop until got one that has a string representation
that is 'length' long. Will accept negatives. Returns the numberstring"""
print(text) # could use input(text) as well to repeat message
while True:
t = input()
try:
n = int(t)
except ValueError:
print("Bad input - not an interger of length",lenght,". Try again.")
continue
if len(str(n)) != lenght:
# avoid inputs of 0000000001 for number of 10 digits
print("Bad input: ",n," is not an interger of length",
lenght, ". Try again.")
continue
return t # return the string of the number
number = ask_for_int_of_length("Gimme nummer of lenght 10", 10)
print(number[0: 10: 2])
輸出:
Gimme nummer of lenght 10
apple
Bad input - not an interger of length 10 . Try again.
0000100000
Bad input: 100000 is not an interger of length 10 . Try again.
1234567890
13579
如果您將它們設為負數,這仍然可以使用長度減少 1 的數字:
Gimme nummer of lenght 10
-123456789
-2468
要測驗一個數字有多少位數而不將其轉換為 string,您可以利用math.log10(.)'return 如果轉換為 int 并添加 1:
from math import log10
def numAbsDigits(integer):
"""Returns how many digits the absolute value has"""
return int(log10(abs(integer))) 1 if integer else 1
for i in range(11):
n = 10**i
for d in range(-1,2):
print (n d, "has", numAbsDigits(n d), "digits.")
輸出:
0 has 1 digits.
1 has 1 digits.
2 has 1 digits.
9 has 1 digits.
10 has 2 digits.
11 has 2 digits.
99 has 2 digits.
100 has 3 digits.
101 has 3 digits.
999 has 3 digits.
1000 has 4 digits.
1001 has 4 digits.
9999 has 4 digits.
10000 has 5 digits.
10001 has 5 digits.
99999 has 5 digits.
100000 has 6 digits.
100001 has 6 digits.
999999 has 6 digits.
1000000 has 7 digits.
1000001 has 7 digits.
9999999 has 7 digits.
10000000 has 8 digits.
10000001 has 8 digits.
99999999 has 8 digits.
100000000 has 9 digits.
100000001 has 9 digits.
999999999 has 9 digits.
1000000000 has 10 digits.
1000000001 has 10 digits.
9999999999 has 10 digits.
10000000000 has 11 digits.
10000000001 has 11 digits.
uj5u.com熱心網友回復:
首先,int(input())如果它是整數,它將被轉換為整數,如果不是,它將直接退出并出現錯誤 ValueError: invalid literal for int() with base 10, so what you want to do with if l1 =int() 不需要,而是你需要嘗試除了陳述句 l1=input()
try:
l1=int(l1)
except ValueError:
print('input not an integer')
即使你做了一個 if 陳述句if l1==int(),它也不起作用,if type(l1) == int:盡管你不需要它,但你需要做。還特別提到你不能做 len(l1) 因為 l1 是一個整數,而 len 不適用于整數我建議你在同一次嘗試中創建另一個變數 string_l1=int(l1) 除了我剛剛寫的陳述句
uj5u.com熱心網友回復:
需要指出的幾個錯誤:
為了做一個回圈使用while回圈
while True: EatSausages()為了檢查輸入/變數/物件是否為int型別,python有一個函式isinstance
isinstance(l1, int)您已經將輸入型別宣告為整數 int(input()) 然后您不必檢查其是否為 int 型別,因為如果用戶輸入字串,它將回傳錯誤/例外
你不能 len(type int)
可能的解決方案
為了解決您 反轉字串中所有數字的問題
cont = ''
while cont != 'n': #Using a while loop to iterate this code again untill user types in n in end of program
l1 = ''
while len(l1) != 10: #Again use a while loop to keep looping until user inputs correctly
try: #Use try to catch if the user did not enter ints
temp = int(input('type a random number consisting of 10 digits')) #asks for input of the digits and store it in digits
except ValueError:
print("You have not entered a proper number. Please enter a proper number")
l1 = str(temp) #change back into string so we can measure the length
if len(l1) < 10: #Check if l1 is 10 digits
print("The number you have entered does not consist of 10 digits. \n"
"Please enter a number consisting of 10 digits.")
print('Reversing...')
print(l1[::-1])
cont = input('Do you want to try again (y/n)')
參考:
- https://www.w3schools.com/python/ref_func_isinstance.asp
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469372.html
標籤:Python python-3.x
