我有这个基本代码,我想要它做的是选择一个随机数,然后它会要求用户输入一个从0到100的数字,它会根据数字给出结果,例如数字是太低或太高。我一直在切换,但总是会出错,这对于2.7:
import random
randomNumber = random.randrange(0,100)
guess = -1
guess = int(input('Enter a number between 0 and 100: ')
guess != randomNumber:
if guess < randomNumber
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
答案 0 :(得分:2)
首先,您定义guess
两次。只需定义一次。如果它不是原始值,则无需使guess
等于-1。其次,我相信您想使用while
循环来检查用户是否猜到了正确的数字。在这种情况下,将另一个guess
添加到while
循环中,以允许玩家继续猜测并保持正确的语法。
不要让玩家在另一个条件下获胜。在每个if/elif
语句后也使用冒号。在比较字符串(输入)和整数时,请将input()
更改为int(input())
。最终的代码应该是这样的:
import random
randomNumber = random.randrange(0, 100)
guess = None # Define guess
while guess != randomNumber: # Create loop
guess = int(input("Enter a number between 0 and 100")) # Change guess
if guess < randomNumber:
print "Your guess is too low."
elif guess > randomNumber:
print "Your guess is too high."
elif guess == randomNumber:
print "You win!" # Win message under correct condition
break # Exit the loop as game is finished
答案 1 :(得分:1)
你的if语句后缺少一个冒号。无论结果如何,您还打印You win!
。把它放在else
语句中。您不需要此行guess != randomNumber:
,并且您不需要guess=-1
,最后您会错过评论中提到的结束语。
import random
randomNumber = random.randrange(0,100)
guess = None
while guess != randomNumber:
guess = int(input('Enter a number between 0 and 100: '))
if guess == randomNumber:
break
elif guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
print('You win!')
答案 2 :(得分:0)
(编辑 - 删除了一些不必要的行)
缺少一些格式化,并且有几行(猜测!= randomNumber :)并没有真正做任何事情(在这种情况下,冒号会导致语法错误。)
import random
randomNumber = random.randrange(0,100)
guess = int(input('Enter a number between 0 and 100: '))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else: # assuming you only want to print this if they guessed right
print('You win!')
答案 3 :(得分:0)
像往常一样,评论您的代码会立即显示错误
import random
# Pick a number between 0 and 99
randomNumber = random.randrange(0,100)
# initialize guess (hint: why?)
guess = -1
# Ask the user to guess a number (hint: balanced parentheses help)
guess = int(input('Enter a number between 0 and 100: ')
# What is this line supposed to be? Looks like the beginning of a loop here, but what kind?
guess != randomNumber:
# If the guess is less than the number, then tell the user
if guess < randomNumber
print('Your guess is too low.')
# Otherwise if the guess is higher than the number, tell the user
elif guess > randomNumber:
print('Your guess is too high.')
# Regardless, win the game. Wait whuh..?
print('You win!')
答案 4 :(得分:0)
请尝试以下代码:
import random
randomNumber = random.randrange(0,100)
guess = int(input("Enter a number between 0 and 100:"))
if guess < randomNumber:
print('Your guess is too low.')
elif guess > randomNumber:
print('Your guess is too high.')
else:
print('You win!')