from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
get_user_guess()
if get_user_guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)
这是代码。我在python 2中制作了一个正在运行的版本,但将其翻译为python 3一直让人头疼。我已经定义了get_user_guess,其中guess =一个int。但是,在roll_dice部分中,我调用上一个函数及其答案之后,我得到了错误消息。
答案 0 :(得分:0)
这不是访问函数返回值的方式。您应该将返回值分配给新名称,然后在以下比较中使用它。
guess = get_user_guess()
if guess > 13:
print("invalid guess")
else:
...
if guess == total_roll:
print("Congratulations")
else:
print("sorry")
答案 1 :(得分:0)
因此,这看起来像是一个小逻辑错误,也有语法错误。首先是语法错误。您并没有真正通过以下操作初始化或调用比较中的函数:
if get_user_guess > 12
而不是:
if get_user_guess() > 12
因此没有什么可与“>”运算符进行比较的。
第二,看到您正试图将变量重新用于下一个比较,您也需要存储它,否则它将再次提示用户输入新值。请注意,第13,14和28行的更改将解决此问题:
from random import randint
from time import sleep
def get_user_guess():
guess = int(input('What is your guess: '))
return guess
def roll_dice(number_of_sides):
first_roll = randint(1, number_of_sides)
second_roll = randint(1, number_of_sides)
max_val = number_of_sides * 2
print ("The maximum value you can roll is %d" % max_val)
guess = get_user_guess()
if guess > 13:
print ("invalid guess, please try again")
else:
print ("Rolling...")
sleep(2)
print ("%d" % first_roll)
sleep(1)
print ("%d" % second_roll)
sleep(1)
total_roll = first_roll + second_roll
print ("%d" % total_roll)
print ("Result...")
sleep(1)
if get_user_guess == total_roll:
print ("Congratulations, you've won!")
else:
print ("sorry sucker, you lose!")
roll_dice(6)