name = input('What is your name?')
print('Welcome to my quiz', name)
guess = 0
tries = 0
answer = 5
score = 0
while guess != answer and tries < 2:
guess = input('10/2 is...')
if guess == answer:
print("Correct")
score = score + 10
else:
print("Incorrect")
score = score - 3
tries = tries + 1
guess = 0
tries = 0
answer = 25
while guess != answer and tries < 2:
guess = input('5*5 is...')
if guess == answer:
print('Correct')
score = score + 10
else:
print('Incorrrect')
score = score - 3
tries = tries + 1
print ('Thank you for playing',name)
我遇到的问题是,当我测试代码时,每次回答问题时,即使答案是正确的,它也会打印错误。
答案 0 :(得分:1)
尝试:
guess = raw_input()
guess = int(guess)
OR
guess = int(input('10/2 is...'))
请相应缩进您的代码。
你试图将“&#39; 5&#39; (一个字符)到5(整数),这是假的,因为&#39; 5&#39;在ASCII中,它实际上并不等于整数5.所以你必须输入一个整数,而不是字符串/字符。
并且@johnrsharpe指出替换&#39; While
&#39;到&#39; while
&#39;。
答案 1 :(得分:0)
问题是:当您使用input()函数获得用户输入时,返回的值将始终为字符串。这样,'5'与5不同。参见:
尝试:
>>> a = input('type a number: ')
3
>>> type(a)
<class 'str'>
>>> b = 3
>>> type(b)
<class 'int'>
>>> a == b
False
但是如果将用户输入转换为int对象,则可以进行比较:
>>> converted_a = int(a)
>>> type(converted_a)
<class 'int'>
>>> converter_a == b
True
所以,这样做的捷径是:
>>> a = int(input('Type a number: '))
>>> type(a)
<class 'int'>
在您的示例中,您只需要在int()函数中嵌入用户输入:
guess = int(input('your question here: '))
但要小心这种方法。它只是在用户键入可转换值时才有效,这意味着如果用户键入一个字母,您的程序将无效。
>>> a = int(input('Type a number: '))
x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'x'
因此,在使用之前,您需要对用户输入进行某种验证。