Python中文
首页
教程
问答
标签
搜索
登录
注册
Python-在For循环中更新变量
回答此问题可获得
20
贡献值,回答如果被采纳可获得
50
分。
<p>所以我决定用Python编写monopy,但是我在更新播放器位置时遇到了一些问题。我写了一个for循环,循环遍历玩家,为每个人掷骰子,然后更新他们的位置。问题是location变量没有保留最新的位置,它在for循环开始时一直重置回0。这是我的代码:</p> <pre><code>player1location = 0 def turn(numberPlayers, player, player1location, Board): for player in range(numberPlayers): player = 'Player'+str(player+1) print 'It\'s', player, 'turn!' print player1location rollDice = raw_input('Press Enter to roll the dice!') diceRoll = random.randint(1,6) print player, 'rolled a', diceRoll player1location = player1location + diceRoll print 'You landed on', player1location print '\n' while True: turn(numberPlayers, player, player1location, Board) </code></pre> <p>如果需要的话,我可以提供更多的代码,但我认为这是控制玩家位置的一切。谢谢!</p> <p>编辑:很明显我是在改变局部变量而不是全局变量。如何更改全局变量?</p>
0 条评论
分类:
Python问答
请先
登录
后评论
默认排序
时间排序
1 个回答
匿名
1天前
擅长:python、mysql、java
<p>您的函数参数与要更新的目标变量同名。 因此,对函数参数而不是全局变量所做的任何更改。这是因为<code>function</code>为传递给函数的参数创建了一个本地作用域。因此,它在全局上覆盖了用相同名称定义的变量。</p> <p>因此,要么更改函数参数<code>player1location</code>的名称,要么更改全局变量的名称。</p>
请先
登录
后评论
针对此问题:
更多的回答
关注
89
关注
收藏
1
收藏,
216
浏览
网友 提问于 2天前
相关Python问题
无法使用Django restfram生成PDF
7 回答
无法使用Django Rest框架发送压缩的gzip数据
5 回答
无法使用Django rest框架进行身份验证(请求用户=匿名用户)
5 回答
无法使用Django、Python和JavaScrip触发onclick函数
10 回答
无法使用Django.views.generic.View保存表单
5 回答
无法使用Django(python 2.7,OS X 10.11.1)
8 回答
无法使用Django/mongoengine连接到MongoDB(身份验证失败)
9 回答
无法使用Django\u mssql\u后端迁移到外部hos
6 回答
无法使用Django&Python3.4连接到MySql
2 回答
无法使用Django+nginx上载媒体文件
3 回答
无法使用Django1.6导入名称模式
10 回答
无法使用Django1.7和mongodb登录管理站点
2 回答
无法使用Djangoadmin创建项目,进程使用了错误的路径,因为我事先安装了错误的Python
3 回答
无法使用Djangockedi验证CBV中的字段
4 回答
无法使用Djangocketditor上载图像(错误400)
9 回答
无法使用Djangocron进行函数调用
8 回答
无法使用Djangofiler djang上载文件
4 回答
无法使用Djangokronos
7 回答
无法使用Djangomssql provid
3 回答
无法使用Djangomssql连接到带有Django 1.11的MS SQL Server 2016
8 回答