[英]python summing random integers
#Use main and a void function named randnums.
#randnums takes no arguments and return none.
#The randnums function generates 6 random integers between 1 and 9.
#The total should be printed on a new line.
#Main should call the randnums function.
import random
total=0
def main():
randnums()
def randnums():
for nums in range(6):
nums=random.randrange(1,10)
total=total+nums
print(nums,end=' ')
print("\nThe total is:",total)
main()
I keep getting: 我不断得到:
local variable 'total' referenced before assignment
赋值之前引用的局部变量“总计”
Or when total=nums
it only shows the last int
generated. 或者,当
total=nums
它仅显示生成的最后一个int
。
Can someone please explain to a beginner what I'm doing wrong? 有人可以告诉初学者我在做什么错吗?
When you assign to a variable inside a function, Python interprets it as local variable to that function. 当您分配给函数内部的变量时,Python会将其解释为该函数的局部变量。 So when you do -
因此,当您这样做时-
total=total+nums
You are actually trying to access the local variable total
before defining it. 实际上,您试图访问局部变量
total
定义它。
Based on your program, does not look like you need total
to be a global variable, you can simply define it as 0 at the start of randnums()
. 根据您的程序,看起来
total
不一定是全局变量,只需在randnums()
开头将其定义为0 randnums()
。 Example - 范例-
def randnums():
total = 0
for nums in range(6):
You are facing problem because of variable scope. 由于范围可变,您正面临问题。
total=total+nums
Notice that line, in your local scope, total doesn't exist but you are trying to get it's value and then add some num
with it, which is the cause of your error. 请注意,在您的本地范围内,该行不存在total,但是您试图获取它的值,然后在其中添加一些
num
,这是导致错误的原因。
If you really want to use it, use it like below: 如果您确实要使用它,请按照以下方式使用它:
global total
total=total+nums
So, that it recognises the global total
variable. 因此,它可以识别全局
total
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.