[英]Python Guess number game - While loop not responding
我是一个相对较新的人,正在尝试创建一个游戏,用户和游戏者轮流猜测彼此的游戏。 我知道我在while / if运算符中在用户输入字符串时做错了事。 是的
在两个地方:
1.用户决定谁应该去哪里( if a in ["Y", "y"]
2.在compguess
函数中的while循环( while ans = False:
compguess
它只是跳过了。
a = input("Shall I guess first? (Y/N):")
userscore = 1
compscore = 1
def compguess():
global compscore
low = 0
high = 100
c = 50
ans = False
while ans = False:
print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
def userguess():
global userscore
g = r.randint(1,100)
h = input("Enter your guess number:")
i = int(h)
while g != i:
if g > i:
h = input("You guessed lower. Guess again:")
i = int(h)
userscore = userscore + 1
else:
h = input("You guessed higher. Guess again:")
i = int(h)
userscore = userscore + 1
if a in ["Y", "y"]:
compguess()
userguess()
else:
userguess()
compguess()
if userscore == compscore:
print("Its a tie !!")
elif userscore < compscore:
print ("Congrats ! You won !")
else:
print ("I won !! Better luck next time")
我将您的while循环条件更改为:
while not ans:
另外,在r.randint(1,100)
, r
是未定义的。 如果要随机使用一个函数,则需要导入它:
你可以做任何import random
或from random import randint
。 如果要保留r
,则可以import random as r
。
您还应该指出猜谜游戏的结束时间。 尽管这暗示着它们彼此直接流动,但我一开始很困惑。
措词对于计算机猜测是不正确的:
Is the number 50 ?
Enter Y if correct / L if your number is lower or H if higher:H
Is the number 25 ?
Enter Y if correct / L if your number is lower or H if higher:L
Is the number 37 ?
Enter Y if correct / L if your number is lower or H if higher:Y
I won !! Better luck next time
最初的猜测是50。然后,我说我的数字更高。 那么随后的猜测就更低了。 您颠倒了数学或短语。
while ans = False:
应该
while ans == False:
print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
在这里,您检查d是否为H(较高),并计算为较低((50 + 0) /2) = 25
因此,您需要切换
另外,您还忘了一个=
while ans = False:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.