gpt4 book ai didi

How to have a set number of attempts for user input? [duplicate](如何设置用户输入的尝试次数?[复制])

转载 作者:bug小助手 更新时间:2023-10-24 21:50:09 26 4
gpt4 key购买 nike




I want to user to have 3 incorrect guesses before the program closes but I cant get the "Incorrect try again" messages to go one by one after each wrong response.

我想让用户有3个错误的猜测之前,程序关闭,但我不能得到“不正确的重试”的消息去一个接一个后,每个错误的反应。


while True:
password = input("Enter the password (3 guesses left):")
x = 1


if password == "Cookie":
print("You guessed the password right")
quit()

if password != "Cookie" and x == 1:
x = x + 1
print("Incorrect try again (2 guesses left)")

if password != "Cookie" and x == 2:
x = x + 1
print("Incorrect try again (1 guess left)")

if password != "Cookie" and x == 3:
x = x + 1
print("You ran out of guesses")
quit()

更多回答

x=3; while x>0; guess = input(f'Enter password ({x} guesses remaining)'); if guess == "Cookie": print("correct."); quit(); x -= 1; print('Incorrect.");

X=3;当x>0时;猜测=输入(f‘输入密码({x}个猜测剩余)’);如果猜测==“Cookie”:打印(“正确。”);退出();x-=1;打印(‘不正确。“);

优秀答案推荐

Because you used if instead of elif
In general, the structure of using conditions is such that when your conditions are related, you should use if, elif, else. It is not related, again, it is done because x is increased, and that is why you are having problems. Your correct code is as below

因为你使用了if而不是elif一般来说,使用条件的结构是这样的,当你的条件相关时,你应该使用if,elif,else。这是不相关的,因为x增加了,这就是为什么你会有问题。您的正确代码如下


x = 1
while True:
password = input("Enter the password (3 guesses left):")
if password == "Cookie":
print("You guessed the password right")
quit()

if password != "Cookie" and x == 1:
x = x + 1
print("Incorrect try again (2 guesses left)")

elif password != "Cookie" and x == 2:
x = x + 1
print("Incorrect try again (1 guess left)")

elif password != "Cookie" and x == 3:
x = x + 1
print("You ran out of guesses")
quit()

And of course x must be outside of while

当然,x必须在While之外


更多回答

No need to check the password every time. It's wrong... because the first IF didn't trigger.

无需每次都检查密码。这是不对的..。因为第一个如果没有触发。

Yes, you are right, but I just wanted to show the problem of the code and tell the solution for this code, but logically what you say is more correct and better.

是的,你是对的,但我只是想展示代码的问题,并告诉这个代码的解决方案,但从逻辑上讲,你说的更正确、更好。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com