构建随机生成器以确定宝石的质量。遇到语法错误导致脚本崩溃......这里是代码:
import random
# Set the basic parameters of the gemstone to determine a description
# and to determine the Gemstones base value.
def gem_size():
global gemsize
gemsize random.randint(1,8)
return gemsize
def gem_shape():
return random.randint(1,4)
def gem_lustre():
return random.randint(1,4)
If gemsize == "8":
GemSizeMult = 5 \
GemDesc = Mammoth
Elif gem_size == 7:
GemSizeMult, GemDesc = 4, Giant
我希望函数简单地生成一到八之间的随机数,并将其作为变量 gem_size 的值返回。我得到语法错误的地方是当我尝试将gem_size变量与其中一个随机数进行比较时,以便稍后设置一些额外的gem描述变量。
这里有人可以提供一个如何使用随机函数设置,分配和比较python变量的工作示例(可行)吗?
答案 0 :(得分:0)
生成和比较随机值的简单示例
num = random.randint(1,10)
if num > 3:
print("num is > 3")
elif num == 2:
print("num is exactly 2")
至于你的实际程序,下面是注释,这里有很多问题
import random
# Set the basic parameters of the gemstone to determine a description
# and to determine the Gemstones base value.
def gem_size():
return random.randint(1,8) # no need to explicitly modify a global
def gem_shape():
return random.randint(1,4)
def gem_lustre():
return random.randint(1,4)
gemsize = gem_size() # use '=' when assigning to a variable
if gemsize == 8: # lowercase 'if', 8 shouldn't be a string
GemSizeMult = 5 # no '\' character here
GemDesc = "Mammoth" # unless you have a Mammoth variable somewhere
elif gemsize == 7: # lowercase 'elif'
GemSizeMult, GemDesc = 4, "Giant" # unless you have a Giant variable