相关疑难解决方法(0)

询问用户输入,直到他们给出有效的响应

我正在编写一个必须接受用户输入的程序.

#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")
Run Code Online (Sandbox Code Playgroud)

如果用户输入合理数据,这将按预期工作.

C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
Run Code Online (Sandbox Code Playgroud)

但如果他们犯了错误,那就崩溃了:

C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
  File "canyouvote.py", line 1, in …
Run Code Online (Sandbox Code Playgroud)

python validation loops user-input python-3.x

523
推荐指数
10
解决办法
42万
查看次数

Python变量范围错误

以下代码在Python 2.5和3.0中按预期工作:

a, b, c = (1, 2, 3)

print(a, b, c)

def test():
    print(a)
    print(b)
    print(c)    # (A)
    #c+=1       # (B)
test()
Run Code Online (Sandbox Code Playgroud)

但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值ab被正确地打印.这让我感到困惑,原因有两个:

  1. 为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?

  2. 为什么变量ab打印符合预期,同时c引发错误?

我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c

有人可以解释一下这种行为吗?

python variables scope

195
推荐指数
7
解决办法
6万
查看次数

标签 统计

python ×2

loops ×1

python-3.x ×1

scope ×1

user-input ×1

validation ×1

variables ×1