2014-09-05 82 views
-5

我正在嘗試使用用戶輸入來結束程序。我希望他們只需點擊當他們需要退出時輸入。我究竟做錯了什麼?結束用戶輸入的Python程序

# 1)Pace.py 
# Converts miles per hour to minutes per mile. 

print ("Hello! This program will convert the miles per hour you got on your treadmill to >minutes per mile.") # Greeting 

def main() : # Defines the function main 

    while True : # The loop can repeat infinitely for multiple calculations. 
     mph = eval (input ("Please enter your speed in miles per hour. ")) # Asks for >user input and assigns it to mph. 
     mpm = 1/(mph/60) # The user input is divided by 60, and that is divided by 1. >This is assigned to mpm. 
     print ("Your speed was", mpm, "minutes per mile!") # Prints out the miles per >minute. 
     if mph == input ("") : # If the user entered nothing... 
      break # ...The program stops 
main() # Runs main. 
+1

請修正你的代碼 - 這不能是你的原程序。無論如何,你可能希望'如果mph ==「」'沒有輸入。我強烈建議不要以這種方式使用「eval」,這是非常危險的。 – mdurant 2014-09-05 19:14:54

+1

你爲什麼使用eval? – 2014-09-05 19:14:55

+1

你不應該在輸入中使用'eval'。強制轉換爲int [ – 2014-09-05 19:15:15

回答

1

if not mph將捕獲一個空字符串作爲輸入並結束您的循環。

在檢查空字符串作爲輸入之後,請勿使用eval強制轉換爲int

def main() : # Defines the function main 
    while True : # The loop can repeat infinitely for multiple calculations. 
     mph = (input ("Please enter your speed in miles per hour or hit enter to exit. ")) # Asks for >user input and assigns it to mph. 
     if not mph: # If the user entered nothing... 
      break # ...The program stops 
     mpm = 1/(int(mph)/60) # The user input is divided by 60, and that is divided by 1. >This is assigned to mpm. 
     print ("Your speed was", mpm, "minutes per mile!") # Prints out the miles per >minute. 
main() # Runs main. 

您應該使用try/except趕不正確的輸入,以避免ValueError並檢查英里是> 0,以避免ZeroDivisionError

def main() : # Defines the function main 
    while True : # The loop can repeat infinitely for multiple calculations. 
     mph = (raw_input ("Please enter your speed in miles per hour. ")) # Asks for >user input and assigns it to mph. 
     if not mph: # If the user entered nothing... 
      break # ...The program stops 
     try: 
      mpm = 1/(int(mph)/60.) # The user input is divided by 60, and that is divided by 1. >This is assigned to mpm. 
     except (ZeroDivisionError,ValueError): 
      print("Input must be an integer and > 0") 
      continue 
     print ("Your speed was", mpm, 
     "minutes per mile!") # Prints out the miles per >minute. 
main() # Runs main. 
+0

感謝第一個,但第二個是做什麼的?爲什麼它必須是int? – 2014-09-08 01:39:29