【问题标题】:How to properly use Variables in Python Functions? [closed]如何在 Python 函数中正确使用变量? [关闭]
【发布时间】:2014-05-26 14:58:16
【问题描述】:

构建随机生成器来确定宝石的质量。遇到导致脚本崩溃的语法错误......这是代码:

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

我希望该函数简单地生成一个介于 1 和 8 之间的随机数,并将其作为变量 gem_size 的值返回。我得到语法错误的地方是当我尝试将 gem_size 变量与随机数之一进行比较以便稍后设置一些额外的 gem 描述变量时。

这里有人可以提供一个工作示例(有效),说明如何使用 random 函数设置、分配和比较 python 变量?

【问题讨论】:

  • 请提供错误的堆栈跟踪
  • 我相信你的返回 gemsize 应该在你的 def 函数里面,而不是外面
  • 您的语法确实完全错误。它有几个明显的问题,在基本语法中,忘记使用= 进行赋值、缩进和使用\ 行继续,而你不能使用一个。
  • IfElif 真的不应该大写....
  • @MartijnPieters 抱歉发布的答案

标签: python function python-3.x random syntax


【解决方案1】:

生成和比较随机值的简单示例

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

【讨论】:

  • ...并解决了这个问题,谢谢!我最大的语法问题是句子大小写。我忘记了 Python 是区分大小写的,因为我已经好几年没有使用它了。一旦我解决了这个问题,其余的大部分都很好地结合在一起。但有一件事,编辑器/调试器使用 gemsize 变量显示错误,而不是精确定位 if 语句。有人知道为什么吗?
  • @GameDaddy idk 如果有一个很好的解释来说明没有将If 显示为第一个错误,但由于两者都是错误,我不会想太多。任何不区分大小写的编程语言的 Idk。有吗?
  • @GameDaddy 如果这解决了您的问题,请考虑accepting this answer
猜你喜欢
  • 2012-04-08
  • 1970-01-01
  • 2017-04-24
  • 2021-03-14
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多