相关疑难解决方法(0)

Python中的switch语句的替换?

我想在Python中编写一个函数,它根据输入索引的值返回不同的固定值.

在其他语言中,我会使用switchcase声明,但Python似乎没有switch声明.在这种情况下,推荐的Python解决方案是什么?

python switch-statement

1719
推荐指数
32
解决办法
149万
查看次数

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

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

#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万
查看次数