我想扩展我的程序,以便在用户猜对数字、猜得太高或太低时显示。我的代码有什么问题?
I want to extend my program so that it displays if the user guessed the correct number, guessed too high or too low. What's wrong with my code?
def dice_game():
print ("Welcome to my dice game")
import random
your_name = input ("Please enter your name:")
your_lucky_number = int(input ("Please select a lucky number between 1 and 6:"))
print (your_name,"'s lucky number was:", your_lucky_number)
#initialize computer number
computer_die_roll = random.randint(1,6)
print ("The computer rolled: ", computer_die_roll)
if your_lucky_number == computer_die_roll:
print("You guessed correct, well done!")
break
elif your_lucky_number < computer_die_roll:
print("You guessed too low!")
else:
print("You guessed too high!")
您的代码存在几个问题,大致按严重程度排序:
else
块的缩进错误。缩进它,使其与 if
和 elif
语句处于同一级别。
- 您不能在
if
块中使用 break
。这将创建一个 SyntaxError
,因此将其删除。
- 您没有验证您的数字输入并盲目地将其转换为
int
,当您通过抛出 ValueError
. 输入任何非整数时会中断
- 你的代码看起来很乱。请关注standard formatting conventions。有一个工具可以自动修复这个问题,叫做
autopep8
.
def dice_game():
print ("Welcome to my dice game")
import random
your_name = input ("Please enter your name:")
your_lucky_number = int(input ("Please select a lucky number between 1 and 6:"))
print (your_name,"'s lucky number was:", your_lucky_number)
#initialize computer number
computer_die_roll = random.randint(1,6)
print ("The computer rolled: ", computer_die_roll)
if your_lucky_number == computer_die_roll:
print("You guessed correct, well done!")
break
elif your_lucky_number < computer_die_roll:
print("You guessed too low!")
else:
print("You guessed too high!")
您的代码存在几个问题,大致按严重程度排序:
else
块的缩进错误。缩进它,使其与if
和elif
语句处于同一级别。- 您不能在
if
块中使用break
。这将创建一个SyntaxError
,因此将其删除。 - 您没有验证您的数字输入并盲目地将其转换为
int
,当您通过抛出ValueError
. 输入任何非整数时会中断
- 你的代码看起来很乱。请关注standard formatting conventions。有一个工具可以自动修复这个问题,叫做
autopep8
.