- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在编写一个接受用户输入的程序。
#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.")
C:\Python\Projects> canyouvote.py
Please enter your age: 23
You are able to vote in the United States!
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Traceback (most recent call last):
File "canyouvote.py", line 1, in <module>
age = int(input("Please enter your age: "))
ValueError: invalid literal for int() with base 10: 'dickety six'
C:\Python\Projects> canyouvote.py
Please enter your age: dickety six
Sorry, I didn't understand that.
Please enter your age: 26
You are able to vote in the United States!
-1
这样的值,这是一个有效的
int
,但在这种情况下是荒谬的?
最佳答案
完成此操作的最简单方法是放置 input
while 循环中的方法。使用 continue
当您输入错误时,以及 break
当您满意时退出循环。
当您的输入可能引发异常时
使用 try
and except
检测用户何时输入无法解析的数据。
while True:
try:
# Note: Python 2.x users should use raw_input, the equivalent of 3.x's input
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
#better try again... Return to the start of the loop
continue
else:
#age was successfully parsed!
#we're ready to exit the loop.
break
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.")
while True:
data = input("Please enter a loud message (must be all caps): ")
if not data.isupper():
print("Sorry, your response was not loud enough.")
continue
else:
#we're happy with the value given.
#we're ready to exit the loop.
break
while True:
data = input("Pick an answer from A to D:")
if data.lower() not in ('a', 'b', 'c', 'd'):
print("Not an appropriate choice.")
else:
break
while True:
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if age < 0:
print("Sorry, your response must not be negative.")
continue
else:
#age was successfully parsed, and we're happy with its value.
#we're ready to exit the loop.
break
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.")
def get_non_negative_int(prompt):
while True:
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
continue
if value < 0:
print("Sorry, your response must not be negative.")
continue
else:
break
return value
age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")
def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
if min_ is not None and max_ is not None and max_ < min_:
raise ValueError("min_ must be less than or equal to max_.")
while True:
ui = input(prompt)
if type_ is not None:
try:
ui = type_(ui)
except ValueError:
print("Input type must be {0}.".format(type_.__name__))
continue
if max_ is not None and ui > max_:
print("Input must be less than or equal to {0}.".format(max_))
elif min_ is not None and ui < min_:
print("Input must be greater than or equal to {0}.".format(min_))
elif range_ is not None and ui not in range_:
if isinstance(range_, range):
template = "Input must be between {0.start} and {0.stop}."
print(template.format(range_))
else:
template = "Input must be {0}."
if len(range_) == 1:
print(template.format(*range_))
else:
expected = " or ".join((
", ".join(str(x) for x in range_[:-1]),
str(range_[-1])
))
print(template.format(expected))
else:
return ui
age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=('a', 'b', 'c', 'd'))
input
声明
data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
print("Sorry, your response was not loud enough.")
data = input("Please enter a loud message (must be all caps): ")
while True
短方法,但它违反了
Don't Repeat Yourself软件开发原理。这会增加系统中出现错误的可能性。如果您想通过更改
input
向后移植到 2.7 怎么办?至
raw_input
,但不小心只改了第一个
input
以上?这是一个
SyntaxError
只是等待发生。
get_non_negative_int
中使用它所以你可以处理while循环。
def get_non_negative_int(prompt):
try:
value = int(input(prompt))
except ValueError:
print("Sorry, I didn't understand that.")
return get_non_negative_int(prompt)
if value < 0:
print("Sorry, your response must not be negative.")
return get_non_negative_int(prompt)
else:
return value
RuntimeError: maximum recursion depth exceeded
终止。 .你可能认为“没有傻瓜会连续犯1000次错误”,但你低估了傻瓜的聪明才智!
关于python - 要求用户输入直到他们给出有效的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60721001/
我需要在 JavaScript 中的笛卡尔坐标和球坐标之间进行转换。我在论坛上浏览了一下,没有找到我要找的东西。 现在我有这个: this.rho = sqrt((x*x) + (y*y) + (z*
有没有matrix3d可以像这样把矩形变成梯形的?我知道常规的 2d 矩阵变换只能以平行四边形结束,因为您只能有效地倾斜和旋转。 div { width: 300px; height:
关于这个例子(d3.j radial tree node links different sizes),我想知道是否可以在 d3.js 中混合径向树和直线树。 对于我的 jsFiddle 示例:htt
我尽量把标题写得最好,但我不确定如何准确描述这里发生的事情,所以请随时更正。 我想使用 › 直 Angular 引号 (›) 而不是 > 直 Angular 引号 (>),虽然 › 字符比 > 短,但
我正在尝试使用 CSS 创建一个具有圆边的矩形棱柱,如下图所示。 到目前为止,我已经指定了顶部和底部的边界半径。问题是我不知道如何让另一边的左右边缘向内 curl 。因此,拐 Angular 处不应有
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 去年关闭。 社区去年审查了是否重
首先,我刚刚开始学习 HTML 和 CSS。 我想如何使用这段代码: https://codepen.io/martinjkelly/pen/vEOBvL .container { width:
我是一名优秀的程序员,十分优秀!