我正在创建此函数,以测试用户输入(作为猜测)是否正确。
def check_guess():
letter = "d"
guess = input("What is your guess: ")
if guess.isalpha() == False:
print("This is invalid")
elif guess.lower() > letter:
print("This too high")
elif guess.lower() < letter:
print("this is too low")
else:
print("that is correct")
check_guess()
因此我创建了此代码,并且没有问题。但是,我现在的任务是必须给用户3次尝试。如果用户获得正确答案,则将打印“正确”,游戏结束。但是,如果他们在所有3次尝试中均失败,则类似于“游戏结束”。
如何创建/复制代码以使其能够执行此操作?
答案 0 :(得分:3)
使用 if ($this->form_validation->run() == FALSE)
循环及其for
子句。循环的else
子句仅在您未脱离循环的情况下运行。
首先让函数返回一个值,以指示用户是否正确猜测。否则,将很难与之交互:
else
现在您可以精确地调用该函数三次,或者直到用户正确猜出为止(以先到者为准):
def check_guess():
letter = "d"
guess = input("What is your guess: ")
if not guess.isalpha():
print("This is invalid")
return False
guess = guess.lower()
if guess == letter:
print("that is correct")
return True
if guess > letter:
print("This too high")
else:
print("this is too low")
return False
当for _ in range(3):
if check_guess():
break
else:
print('you failed')
返回check_guess
表示成功时,我们True
跳出循环,确保break
子句未 触发。如果这三个迭代完成并且用户从未做出正确的猜测,则将触发该子句。
答案 1 :(得分:2)
def check_guess():
letter = "d"
guess = input("What is your guess: ")
if guess.isalpha() == False:
print("This is invalid")
return False
elif guess.lower() > letter:
print("This too high")
return False
elif guess.lower() < letter:
print("this is too low")
return False
else:
print("that is correct")
return True
for i in range(0,3):
status = check_guess()
If status:
print(“success”)
break
else:
print(“fail”)
答案 2 :(得分:1)
如果用户正确,则需要返回,然后如果不增加计数器,则需要返回。这样的事情应该起作用:
count = 0
while count < 3:
if check_guess():
# he's right
break
else:
# he's wrong
count += 1
if count >= 3:
print("You lose !")
else:
print("You win !")
答案 3 :(得分:1)
您可以通过以下方式进行:
def check_guess():
status = False
letter = "d"
guess = input("What is your guess: ")
if guess.isalpha() == False:
print("This is invalid")
elif guess.lower() > letter:
print("This too high")
elif guess.lower() < letter:
print("this is too low")
else:
print("that is correct")
status = True
return status
for i in range(3):
status = check_guess()
if status:
break
else:
print "Gameover"
答案 4 :(得分:-2)
c=0
def check_guess():
letter = "d"
guess = input("What is your guess: ")
if guess.isalpha() == False:
print("This is invalid")
c++
elif guess.lower() > letter:
print("This too high")
c++
elif guess.lower() < letter:
print("this is too low")
c++
else:
print("that is correct")
c=4
if c<=3
check_guess()