簡體   English   中英

python 處理來自用戶的無效輸入

[英]python handling invalid inputs from a user

我被這個作業困住了:

重寫以下程序,以便它可以處理來自用戶的任何無效輸入。

def example():
   for i in range(3)
       x=eval(input('Enter a number: '))
       y=eval(input('enter another one: '))
       print(x/y)

我試了試try...除了ValueError,但程序仍然無法運行。

def example():

   for i in range(3)
      try:
         x=eval(input('Enter a number: '))
      except ValueError:
         print("Sorry, value error")
      try:
         y=eval(input('enter another one: '))
      except ValueError:
         print("Sorry, value error")`enter code here`
      try:
         print(x/y)
      except ValueError:
         print("Sorry, cant divide zero")

那是因為您可能沒有考慮 y = 0 時得到的ZeroDivisionError 關於什么

def example():
   for i in range(3):
      correct_inputs = False
      while not correct_inputs:
         try:
            x=eval(input('Enter a number: '))
            y=eval(input('enter another one: '))
            print(x/y)
            correct_inputs = True
         except:
            print("bad input received")
            continue

這個 function 精確計算了 3 個正確的除法 x/y! 如果您需要有關continue運算符的良好參考,請查看此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM