python猜数字
要求从1-10中随机选一个数字,然后每次猜一个,每次猜完会告诉你大了还是小了,只能猜五次,第五次输入数字之后如果没猜中,会告诉你猜错了。但是我的程序为什么第五次输入错误之后还会继续显示:你猜的数字大了或者小了,然后再告诉你猜错了。求大神帮助,感激不尽!!这是我的程序:
import random
counts = 1
turns = 5
answer = random.randint(1,10)
print("Pick a number between 1 and 10.\nYou will have 5 turns.")
while counts <= 5:
temp = input("Your guess is \n")
guess = int(temp)
turns = turns - 1
if guess == answer:
print("It took you",counts,"turns to guess my number, which was",answer,".")
break
else:
if guess < answer:
print("Turns ",counts+1)
print("Your guess,",guess,",is too low")
print("Pick a number between 1 and 10.")
print("You have ", turns, " turns left.")
else:
print("Turns ",counts+1)
print("Your guess,",guess,",is too high")
print("Pick a number between 1 and 10.")
print("You have ", turns, " turns left.")
counts = counts + 1
else:
print("Oops!!No turns left.My number was",answer,".")
請問想幫助什麼呢?{:5_94:} 这是你自己写的逻辑呀
你是想到第五次没匹配上就直接退出吗? 你想要的是这样的效果?
counts = 1
turns = 5
answer = random.randint(1, 10)
print("Pick a number between 1 and 10.\nYou will have 5 turns.")
while counts <= 5:
temp = input("Your guess is \n")
guess = int(temp)
turns = turns - 1
if guess == answer:
print("It took you", counts,
"turns to guess my number, which was", answer, ".")
break
else:
if counts == 5:
counts = counts + 1
continue
if guess < answer:
print("Turns ", counts+1)
print("Your guess,", guess, ",is too low")
print("Pick a number between 1 and 10.")
print("You have ", turns, " turns left.")
else:
print("Turns ", counts+1)
print("Your guess,", guess, ",is too high")
print("Pick a number between 1 and 10.")
print("You have ", turns, " turns left.")
counts = counts + 1
else:
print("Oops!!No turns left.My number was", answer, ".") 大马强 发表于 2021-9-11 16:37
你想要的是这样的效果?
谢谢大神,就是想要这种效果。可以麻烦给我解释以下什么原理吗? 傻眼貓咪 发表于 2021-9-11 16:14
請問想幫助什麼呢?
谢谢啊,已经解决了。可能是我没说的太清楚,不好意思
Ddaniel1177 发表于 2021-9-11 17:21
谢谢大神,就是想要这种效果。可以麻烦给我解释以下什么原理吗?
https://static01.imgkr.com/temp/b0b54aa01f33476c96ce52a70247ccff.jpg
下次发代码可以点击输入框的 <> 插入代码 大马强 发表于 2021-9-11 17:40
下次发代码可以点击输入框的插入代码
好的好的,谢谢大佬! 我怎么看着你这个是逻辑问题。。。。
稍微小小修改一下就好了
import random
counts = 1
turns = 0
answer = random.randint(1, 10)
print("Pick a number between 1 and 10.\nYou will have 5 turns.")
while counts <= 5:
temp = input("Your guess is \n")
guess = int(temp)
turns = turns + 1
if guess == answer:
print("It took you", counts, "turns to guess my number, which was", answer, ".")
break
else:
if guess < answer:
print("Turns ", counts + 1)
print("Your guess,", guess, ",is too low")
print("Pick a number between 1 and 10.")
print("You have ", turns, " turns left.")
else:
print("Turns ", counts + 1)
print("Your guess,", guess, ",is too high")
print("Pick a number between 1 and 10.")
print("You have ", turns, " turns left.")
counts = counts + 1
else:
print("Oops!!No turns left.My number was", answer, ".")
页:
[1]