[英]How can I input a non-number to print something else instead of having an error using while loops?
I have to calculate factorials of given numbers, which have inputs of 4, 9, and abc123.我必须计算给定数字的阶乘,其输入为 4、9 和 abc123。 This is my coding so far but for abc123 is where the error is.
到目前为止,这是我的编码,但对于 abc123 来说是错误所在。 How can I edit this so that it does not show an error but printing something else?
如何编辑它以使其不显示错误但打印其他内容?
for i in range(0,2):
num = int(input('Enter a number: '))
factorial = 1
if num < 0:
print('Sorry! Factorials cannot be negative numbers.')
else:
for i in range(1, num + 1):
factorial = factorial*i
print(num, '!=', factorial)
You could use try except
to handle non-integers as:您可以使用
try except
来处理非整数:
for i in range(0,3):
try:
num = int(input('Enter a number: '))
factorial = 1
if num < 0:
print('Sorry! Factorials cannot be negative numbers.')
else:
for i in range(1, num + 1):
factorial = factorial*i
print(num, '!=', factorial)
except Exception as ex:
print("Invalid input. Try again")
Wrap your call to int
in a try/except
block将您对
int
的调用包装在try/except
块中
try:
foo = int(input())
except Exception:
print("exception occurred")
this can be made much more advanced with some extra feedback about the error and also arguably better by capturing only the minimum Exception expected这可以通过一些关于错误的额外反馈来变得更加先进,并且通过仅捕获预期的最小异常可以说更好
while True:
_value = input("Enter a number: ")
try:
value = int(_value)
except ValueError:
print("invalid input!: {}".format(_value)
continue # jump to top of loop
The idiomatic way to handle errors in Python is with try: ... except: ...
blocks:在 Python 中处理错误的惯用方法是使用
try: ... except: ...
块:
for i in range(0,2):
inp = input('Enter a number: '))
try:
num = int(inp)
except ValueError:
print('>{}< is not a valid number'.format(num))
continue
factorial = 1
if num < 0:
print('Sorry! Factorials cannot be negative numbers.')
else:
for i in range(1, num + 1):
factorial = factorial*i
print(num, '!=', factorial)
Please note that the exception clause should only catch the exception you want to handle.请注意,异常子句应该只捕获您要处理的异常。 Avoid catch all exception blocks, because they can silently swallow various errors and make some problems harder to diagnose...
避免捕获所有异常块,因为它们可以默默地吞下各种错误并使一些问题更难诊断......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.