我正在尝试制作一个程序,其中该程序向用户询问数字,并一直询问直到输入空白行。然后,它应该打印出有多少个偶数。现在唯一的问题是,每输入一个空行都会给我这个错误:ValueError: invalid literal for int() with base 10: ''
。你能给出解决方案吗?
number = int(input('Enter your number: '))
count = 0
even = []
while number:
even.append(number)
if number %2 == 0:
number = int(input('Enter your number: '))
else:
number = int(input('Enter your number: '))
number = int(input('Enter your number: '))
for nums in evens:
count+=1
print(f'Your even numbers are: {nums} ')
答案 0 :(得分:0)
检查用户提供的号码。将任何字符串强制转换为int可能导致ValueError
number = input('Enter your number')
if number.isdigit():
number = int(number)
else:
print('Please provide a correct number value')
答案 1 :(得分:0)
尝试以下代码:
number = input("Enter Number:\t")
my_list = []
while True:
if number.isdigit():
my_list.append(int(number))
number = input("Enter Number:\t")
continue
elif number.isspace():
print()
print("The Even Numbers are:\t")
print(*[var for var in my_list if var%2==0])
break
else:
print("Wrong input Enter number or press space. Start from beginning")
break
答案 2 :(得分:0)
isExit=False
str_number=input('Enter your number: ')
if str_number.isnumeric():
number = int(str_number)
else:
isExit=True
count = 0
even = []
while not isExit:
if number %2 == 0:
even.append(number)
str_number=input('Enter your number: ')
if str_number.isnumeric():
number = int(str_number)
else:
isExit=True
if even:
for nums in even:
count+=1
print(f'Your even numbers are: {nums} ')
else:
print('No even numbers')
希望这会根据您的需要