我有一个非常基本的问题.
假设我调用一个函数,例如,
def foo():
x = 'hello world'
Run Code Online (Sandbox Code Playgroud)
如何让函数以这样的方式返回x,我可以将它用作另一个函数的输入或者在程序体内使用变量?
当我使用return并在另一个函数中调用该变量时,我得到一个NameError.
我还是python的新手.我正在为更大的项目工作框架.这个程序让你想到一个圆圈或正方形,然后它会问四个问题,然后决定一个答案.
我正处于框架的最后一步,但遇到了问题.我得到"全局名称'qas1'未定义"
getQuestion中的第50行问题='qas'未定义全局名称'qas'
当我试图腌制我的元组时,就会发生这种情况.
这是我的加载程序,用于创建包含我的元组的pickle文件:
import cPickle
import os
qas1 = [
('Are you more like Waffle or a Pancake'),
('1. Waffle', 1, 0),
('2. Pancake', 0, 1)
]
qas2 = [
('Do you have a straight edge?'),
('1. Yes', 1, 0),
('2. No', 0, 1)
]
qas3 = [
('Are you simliar in shape to a lolipop?'),
('1. Yes', 0, 1),
('2. No', 1, 0)
]
qas4 = [
('Is the world rounded like a planet, or flat like …Run Code Online (Sandbox Code Playgroud) 我想我在这里疯了.
url_request = 0
def somefunction():
url_request+=1
if __name__ =='__main__':
somefunction()
Run Code Online (Sandbox Code Playgroud)
给我UnboundLocalError.我在这里错过了什么重要概念?
转到使用C/Java背景的python,我最近不得不实现相互递归,但python中的某些东西困扰着我:
因为python程序是逐行解释的,如果我在同一个python文件中一个接一个地有两个函数:
def A(n):
B(n-1)
# if I add A(1) here, it gives me an error
def B(n):
if n <= 0:
return
else:
A(n-1)
Run Code Online (Sandbox Code Playgroud)
当解释器正在读取时A,B尚未定义,但是此代码不会给我一个错误
TL; DR
我的理解是,当def被解释,蟒蛇增加了一些本地的名称空间中的条目locals()有{"function name": function address},但作为函数体,它只能做语法检查:
def A():
blabla # this will give an error
def B():
print x # even though x is not defined, this does not give an error
A() # same as above, NameError is only detected during runtime
Run Code Online (Sandbox Code Playgroud) 我试图弄清楚为什么我的pygame应用程序Table Wars中出现UnboundLocalError.以下是发生的情况摘要:
变量,REDGOLD,REDCOMMAND,BLUEGOLD和BLUECOMMAND,被初始化为全局变量:
#Red Stat Section
REDGOLD = 50
REDCOMMAND = 100
#Blue Stat Section
BLUEGOLD = 50
BLUECOMMAND = 100
def main():
[...]
global REDGOLD
global REDCOMMAND
global BLUEGOLD
global BLUECOMMAND
Run Code Online (Sandbox Code Playgroud)
这在主循环中产生单位时减少了产生单位的资金.
现在,我正在尝试建立一个系统,以便当一个单位死亡时,杀手会根据他杀死的内容退还受害者COMMAND并获得收入GOLD:
class Red_Infantry(pygame.sprite.Sprite):
def __init__(self, screen):
[...]
self.reward = 15
self.cmdback = 5
[...]
def attack(self):
if self.target is None: return
if self.target.health <= 0:
REDGOLD += self.target.reward #These are the problem lines
BLUECOMMAND += …Run Code Online (Sandbox Code Playgroud) 我有下面的代码片段,可以创建一个笔记并添加到笔记本中.
我的问题与全局变量有关last_id.当我将它声明为类变量时,即在Class Note中,我得到以下错误但是当我在类外声明时,我的代码工作正常.
以下是我的澄清:
last_id当我在函数中将其声明为全局变量时,为什么需要定义?Error:
C:\Python27\Basics\OOP\formytesting>python notebook.py
Traceback (most recent call last):
File "notebook.py", line 38, in <module>
firstnote = Note('This is my first memo','example')
File "notebook.py", line 10, in __init__
last_id += 1
NameError: global name 'last_id' is not defined
Run Code Online (Sandbox Code Playgroud)
code.py
import datetime
last_id = 0
class Note:
def __init__(self, memo, tags):
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id
#global last_id
#last_id += 1 …Run Code Online (Sandbox Code Playgroud) 我是Python的新手,我从未学过任何其他编程语言.我似乎得到了这个错误,我已经阅读了其他帖子,但他们说在[dollar = 0]之前放置全局,这会产生语法错误,因为它不允许[= 0].我正在使用[美元]作为计数器,所以我可以跟踪我添加到它的内容并在需要时将其显示回来.有人能帮助我吗?谢谢.
<>代码<>
dollars = 0
def sol():
print('Search or Leave?')
sol = input()
if sol == 'Search':
search()
if sol == 'Leave':
leave()
def search():
print('You gain 5 bucks')
dollars = dollars + 5
shop()
def leave():
shop()
def shop():
shop = input()
if shop == 'Shortsword':
if money < 4:
print('I\'m sorry, but you don\'t have enough dollars to buy that item.')
shop1()
if money > 4:
print('Item purchased!')
print('You now have ' + dollars + …Run Code Online (Sandbox Code Playgroud) 我对使用和修改全局变量的函数进行了测试。我想确保我的全局变量在我的测试之间重置。有什么技巧可以做到这一点吗?
主要.py:
y = 0
def inc(x):
# side effect
global y
y = y + 1
return x + y + 1
Run Code Online (Sandbox Code Playgroud)
测试_main.py:
from main import inc
def test_answer():
assert inc(3) == 5
def test_answer_again():
assert inc(3) == 5
Run Code Online (Sandbox Code Playgroud)
_________________________________________________________________________________________ test_answer_again __________________________________________________________________________________________
def test_answer_again():
> assert inc(3) == 5
E assert 6 == 5
E + where 6 = inc(3)
test_main.py:8: AssertionError
====================================================================================== short test summary info =======================================================================================
FAILED test_main.py::test_answer_again - assert 6 == 5
==================================================================================== 1 failed, 1 …Run Code Online (Sandbox Code Playgroud) 当我尝试编译下面的代码时,我得到了这个错误
UnboundLocalError: local variable 'L' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
有人可以解释原因吗?是不是之前分配的全局变量?
我的Python版本是2.7.3
#!/usr/bin/env python
import pygame
from pygame.locals import *
from sys import exit
import random
import math
R = int(8) # promien planety
N = 5 # liczba planet
G = 2 # stala "grawitacyjna"
L = 1
def compute_dv(p1,p2):
dx = p2[0]-p1[0]
dy = p2[1]-p1[1]
r = math.hypot(dx,dy)
dx /= r*r
dy /= r*r
if(L>1000):
print "r= ", r, "dx= ", dx, "dy= ", dy, "dx/ r*r = ", dx, …Run Code Online (Sandbox Code Playgroud) 所以基本上我不知道这小块代码有什么问题,而且似乎找不到让它工作的方法.
points = 0
def test():
addpoint = raw_input ("type ""add"" to add a point")
if addpoint == "add":
points = points + 1
else:
print "asd"
return;
test()
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
UnboundLocalError: local variable 'points' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
注意:我不能在函数中放置"points = 0",因为我会重复多次,所以它总是先将点设置回0.我完全陷入困境,任何帮助将不胜感激!