预期类型"大小",改为'int'



(我对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])

if l1 == int():

测试if l1 == 0:。如果要测试something是否为整数,请使用isinstance(something, int)。在您的代码中不起作用,因为如果将任何非整数作为输入,您的int(input())将抛出异常。


你应该避免全局变量。不要递归地调用函数以使其"循环"。当将字符串转换为整型时,需要捕获因输入非整数而产生的错误。

当检查输入的数字字符串表示的长度时,您需要转换然后再次进行字符串化以避免像

这样的输入
"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

要测试一个数字有多少位而不将其转换为字符串,您可以利用math.log10(.)的返回,如果转换为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.

首先,如果你做int(input()),如果它将是一个整数,它将被转换为整数,如果它不是,它将直接退出错误ValueError:无效的字面为int()与基数10,所以你想做什么如果l1=int()是不需要的,而不是你需要一个try except语句l1 =输入()

try:
l1=int(l1)
except ValueError:
print('input not an integer')

即使你做了一个if语句if l1==int(),它也不会工作,你需要做if type(l1) == int:,尽管你不需要它。同样值得一提的是,你不能做len(l1),因为l1是一个整数,len不能与整数一起工作,我建议你在同一个try except语句中创建另一个变量string_l1=int(l1),我刚刚写了

需要指出的几个错误:

  • 为了执行循环,使用while loop

    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)')

引用:

  1. https://www.w3schools.com/python/ref_func_isinstance.asp

最新更新