有人可以帮我解决我遇到的问题吗?
def marbles():
marbles = 0
while True:
try:
x = eval(input("How many marbles? "))
except ValueError:
print("You can't enter", x , "marbles! How many marbles do you have?")
continue
else:
break
for i in range(x):
x = eval(input("Please enter how many marbles between 0 and 100: "))
if 0 <= x and x <= 100:
marble = marble + x
else:
print("Your number is out of range!")
y = int(input("Please enter how many marbles between 0 and 100: "))
main()
我似乎无法弄清楚为什么当我编码5.4弹珠时它不会发出你不在射程范围内的警告。在0到100之间,我应该被允许给出小数,但对于“多少弹珠”,我希望收到警告再试一次。
答案 0 :(得分:0)
使用is_integer()
方法。如果参数是整数,则返回boolean。
例如
>>> (5.4).is_integer()
False
>>> (1).is_integer()
True
答案 1 :(得分:0)
您需要字符串isdigit方法。 像这样的东西?
def marbles():
marbles = 0
count_flag = False
while count_flag is False:
try:
x = raw_input("How many marbles? ")
if not x.isdigit():
raise ValueError
except ValueError:
print "You can't enter %s marbles! How many marbles do you have?" % (x)
else:
x = int(x)
count_flag = True
for i in range(x):
x = int(input("Please enter how many marbles between 0 and 100: "))
if 0 <= x and x <= 100:
marbles = marbles + x
else:
print("Your number is out of range!")
y = int(input("Please enter how many marbles between 0 and 100: "))
return marbles
print marbles()
此外,在python的情况下,您可以执行0&lt; = x&lt; = 100(我的首选项)或范围内的x(0,101),而不是0&lt; = x和x&lt; = 100。不推荐第二个: - )
同样是您的for语句逻辑的缺陷。如果用户提供两个不良输入,则不予考虑。你还需要一段时间。
while x > 0:
y = int(input("Please enter how many marbles between 0 and 100: "))
if 0 <= y and y <= 100:
marbles = marbles + y
x -= 1
else:
print("Your number is out of range!")
老实说,更清洁的做法是将输入验证放在另一个函数中并在大理石函数中调用它。
def get_number(screen_input):
flag = False
while flag is False:
try:
x = raw_input(screen_input)
if not x.isdigit():
raise ValueEror
except ValueError:
print("You can't enter %s marbles! How many marbles do you have?" % (x))
else:
return int(x)
def marbles():
marbles = 0
x = get_number("How many marbles?")
while x > 0:
y = get_number("Please enter how many marbles between 0 and 100:")
if 0 <= y <= 100:
marbles += y
x -= 1
else:
print("Your number is out of range!")
return marbles
print marbles()