简体   繁体   English

如何输入非数字来打印其他内容,而不是使用 while 循环出错?

[英]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.

相关问题 如何在 while 循环中打印其他内容? - How can I print something else in a while loop? 如何使输入与其他内容打印在同一打印件中? - How do I make an input to be printed in the same print as something else? 我如何在同时发生其他事情的同时等待输入? - How can I wait for an input while something else happens at the same time? 从字符串中删除非数字字符并在其上使用int()函数后,会发生错误 - After removing non-number characters from a string and using the int() function on it, error occurs Python正则表达式:如何将数字与非数字匹配? - Python regex: How to match a number with a non-number? 如何使用Regex分割非数字前的句号? - How to use Regex to split a period before non-number? 如果有多个循环,如果没有多个 if else 条件,如何立即停止线程? - How can I stop a thread immediately if have multiple loops, without having multiple if else conditions? 使用 python 和 yahoo 金融(还有其他东西)如何在 X 天的整个交易日内获取资产价格的数据 - Using python and yahoo finance (so something else) how can I get data for the price of an an asset throughout a trading day for X number of days 如何通过使用 while 循环和 if 语句再次输入我的输入? - How can I have my input be typed out again via using while loops and if statements? 在 MultiIndex 数据框中插入非数字行 - Inserting non-number rows in MultiIndex dataframe
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM