test.js
如果我想每次玩家输入无效输入并且"猜测"游戏还在继续,我该怎么办?
答案 0 :(得分:0)
在某种while循环中包装您的输入。
def checkIsValid(value):
#some validity checking function here.
for taken in range(1,7):
print("Take a guess.")
guess = input()
isValid = checkIsValid(guess)
while (not isValid):
print("Invalid input")
guess = input()
isValid = checkIsValid(guess)
guess = int(guess)
#continue with the valid value.
答案 1 :(得分:0)
'''
Created on 2016-3-24
@author: GuangFa
'''
import random
def get_name():
"""
Get name from the input.
:Usage:
get_name()
"""
print("hello,what is your name?")
name=raw_input()
return name
def get_number():
"""
Get number from the input.Return the number until the input is a valid number
:Usage:
get_number()
"""
is_number=False
while not is_number:
try:
number=input('please enter a valid number:')
except Exception ,e:
is_number=False
else:
is_number=True
return number
def guess():
"""
Guess the number.The system generates a random number,
Only 7 chances to guess the number.
:Usage:
guess()
"""
name=get_name()
print("well,%s, I am thinking of a number between 0 and 20"%name)
number = random.randint(0,20)
for taken in range(1,7):
print("Take a guess.")
guess=get_number()
if number==guess:
print ("good job, %s you guessed my number in %s guesses"%(name,str(taken)) )
break
if guess < number:
print("your guess is too low.")
elif guess > number:
print("your guess is too high.")
if taken==6:
print "nope,the number i was thinking of was " + str(number)
guess()
答案 2 :(得分:0)
我认为你应该尽可能地分离循环响应和获得验证响应的两个问题,你可以通过编写一个处理验证用户输入问题的函数来实现这一点。
这样的函数需要知道如何提示用户以及告诉用户输入是否无效的内容,因此我们必须为函数提供两个参数,但我们也为参数提供合理的默认值...
要查看输入的正确性,我们使用try: ... except: ...
子句,如果try
的主体引发错误,except
会查看错误,如果它是特定的一个(对我们来说,ValueError
)执行除外的主体。
except
的主体以调用我们正在定义的函数结束,因为这是另一种循环方式,如果你考虑发生了什么......在这种情况下它是一个更简单的循环方式。
那就是说,通过理解我们在函数中需要的东西,我们写下它:
def get_integer(prompt='Enter an integer: ',
err_prompt='Not an integer, please try again.'):
answer = input(prompt)
try:
number = int(answer)
return number
except ValueError:
print(err_prompt)
return get_integer(prompt, err_prompt)
现在进行一些测试,
In [19]: get_integer()
Enter an integer: 1
Out[19]: 1
In [20]: get_integer()
Enter an integer: a
Not an integer, please try again.
Enter an integer: 1
Out[20]: 1
In [21]: get_integer(prompt='Un numero intero, per favore: ')
Un numero intero, per favore: 23.2
Not an integer, please try again.
Un numero intero, per favore: 22
Out[21]: 22
In [22]: get_integer(err_prompt='Naaaah!')
Enter an integer: q
Naaaah!
Enter an integer: 11
Out[22]: 11
In [23]:
我已经使用了您的实现,因为肯定它已经足够好了,但我已经改变了一点字符串的大写,不再是try ... except
,因为它隐藏在{{1引入在正常终止时执行的else
clause to the for
loop,以便告知用户程序停止的原因。
get_integer()