我已经看过很多if语句和while循环问题,但是没有发现任何与我的问题有关的问题。 在学校,我们被挑战做一个猜谜游戏,但计算机不得不猜测我们的号码。老师给了我们答案,但我并不高兴,决定按照我的方式去做。在尝试这样做时,发生了错误。
我的错误是:
Guess2 = str(random.randint(Guess2, Number+1))
File "C:\Users\Diogo Melim\AppData\Local\Programs\Python\Python36\lib\random.py",
line 220, in randint
return self.randrange(a, b+1)
File "C:\Users\Diogo Melim\AppData\Local\Programs\Python\Python36\lib\random.py", line 198, in randrange
raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (188315,32, -188283)
import random
def guessing_game():
Number = int(input())
Number2 = str(Number)
Guess = int(random.randint(1, 1000000))
Guess2 = str(Guess)
while Guess2 != Number2 :
Number2
print( "My guess is " + Guess2)
if Guess2 > Number2:
print ("Wrong, " + Guess2)
Guess2 = int(Guess2)
Guess2 = str(random.randint(Number-1, Guess2))
print("I'll try again, it's less")
elif Guess2 < Number2:
print ("Errei, " + Guess2)
Guess2 = int(Guess2)
Guess2 = str(random.randint(Guess2, Number+1))
print("I'll try again, it's bigger")
elif Guess2 == Number2 :
print( "Got it, the value was: " + Guess2)
break
else :
print( "Got it! The value was: " + Number2)
exit
guessing_game()
答案 0 :(得分:0)
您的基本逻辑问题是比较字符串值而不是数值。你不能在一对字符串上合理地调用 randint 。
字符串逐个字符排序。例如,“2”大于“10”,因为它看起来没有超过第一个差异:“2”对比“1”。这会使您的猜测值超出范围,最终会使您的上下猜测边界反转。
代码中唯一需要 字符串的地方就是获取输入。之后,只需使用整数值:
import random
def guessing_game():
Number = int(input())
Guess = int(random.randint(1, 1000000))
while Guess != Number :
print( "My guess is " + Guess)
if Guess > Number:
print ("Wrong, " + Guess)
Guess = int(Guess)
Guess = random.randint(Number-1, Guess)
print("I'll try again, it's less")
elif Guess < Number:
print ("Errei, " + Guess)
Guess = int(Guess)
Guess = random.randint(Guess, Number+1)
print("I'll try again, it's bigger")
elif Guess == Number :
print( "Got it, the value was: " + Guess)
break
else :
print( "Got it! The value was: " + Number)
exit
guessing_game()