我应该如何指定我的if-else-elif语句,以免它们在第一个if-子句之后完成条件检查?
import random
x = random.randint(1, 100)
correct_answer = False
guess_count = 0
answer = input("Try to guess a number in range of 1 to 100... ")
while guess_count < 6 and correct_answer == False:
if answer != x:
answer = input("Try again...")
guess_count = guess_count + 1
elif answer > x:
print("Try lower number")
guess_count = guess_count + 1
elif answer < x:
print("Try higher number")
guess_count = guess_count + 1
elif answer == x:
print("You won!")
correct_answer = True
elif guess_count > 6:
print("You ran out of chances, sorry")
break
答案 0 :(得分:1)
您可以通过更改条件的顺序来简化此操作,以便仅在处理完所有退出条件(即赢或输)后才要求另一个数字:
import random
x = random.randint(1, 100)
correct_answer = False
guess_count = 0
answer = input("Try to guess a number in range of 1 to 100... ")
while True:
guess_count = guess_count + 1
answer = int(answer)
if answer == x:
print("You won!")
correct_answer == True
break
if guess_count > 6:
print("You ran out of chances, sorry")
break
if answer > x:
answer = input("Try a lower number:")
else:
answer = input("Try a higher number:")
答案 1 :(得分:0)
您应将elif
语句替换为if
语句,如下所示:
import random
x = random.randint(1, 100)
correct_answer = False
guess_count = 0
answer = int(input("Try to guess a number in range of 1 to 100... "))
while guess_count < 6 and correct_answer == False:
if answer != x:
answer = int(input("Try again..."))
guess_count = guess_count + 1
if answer > x:
print("Try lower number")
guess_count = guess_count + 1
if answer < x:
print("Try higher number")
guess_count = guess_count + 1
if answer == x:
print("You won!")
correct_answer = True
if guess_count > 6:
print("You ran out of chances, sorry")
break
答案 2 :(得分:0)
我相信这是您真正想要的。我删除了重复的代码,并修改了@fozoro代码,以修复过程中的错误
import random
x = random.randint(1, 100)
correct_answer = False
answer = int(input("Try to guess a number in range of 1 to 100...: "))
guess_count = 1
while guess_count < 6 and correct_answer == False:
guess_count = guess_count + 1
if answer != x:
answer = int(input("Try again...: "))
if answer > x:
print("Try lower number")
if answer < x:
print("Try higher number")
if answer == x:
print("You won!")
correct_answer = True
if guess_count >= 6:
print("You ran out of chances, sorry")
答案 3 :(得分:0)
完整的工作代码:
import random
x = random.randint(1, 100)
correct_answer = False
guess_count = 0
answer = int(input("Try to guess a number in range of 1 to 100... "))
while guess_count < 6 and correct_answer == False:
if answer != x and answer > x:
answer = int(input("Try again... The number should be lower "))
guess_count = guess_count + 1
if answer != x and answer < x:
answer = int(input("Try again... The number should be higher "))
guess_count = guess_count + 1
if answer == x:
print("You won!")
correct_answer = True
if guess_count > 5:
print("You ran out of chances, sorry")
break