python仅从输入语句输入int

时间:2017-05-21 03:26:21

标签: python

我是python的新手,我正在尝试检查startmilesendmiles是否仅作为整数输入,而gallons是否作为float输入。当我输入alpha时程序崩溃。谢谢

#!/usr/bin/env python

import os
import sys
import subprocess
import datetime 
clear = lambda: os.system('clear')

clear()

t = datetime.datetime.now()
from time import gmtime, strftime
strftime("%a, %d %b %Y %X +0000", gmtime())
today = strftime("%a, %d %b %Y ")
print(today,'\n')

def main():
    startmiles = input("Enter Your Start Miles = ")
    endmiles = input("Enter Your Ending Miles = ")
    gallons = input("Enter Your Gallons = ")
    mpg = (int(endmiles) - int(startmiles)) / float(gallons)
    print("Miles Per Gallon =", round(mpg, 2))
    answer = input("\n Go Again Y or n ").lower()
    if answer == 'y': print('\n'), main()
    if answer != 'y': print('\n Thank You Goodbye')



if __name__=="__main__":
    main() # must be called from last line in program to load all the code

2 个答案:

答案 0 :(得分:0)

在Python 2.x中,输入应该导致整数,除非你使用raw_input。看起来你的mpg变量无论如何都要采用endmiles的整数。

在Python 3.x

startmiles = int(input("Enter Your Start Miles = "))

听起来你说某些角色会使程序崩溃,这意味着你需要做一些异常处理。有关详细信息,请参阅this question response,但您需要找到一种方法来处理异常而不是崩溃。下面是一个强制正确输入变量的示例。

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.")

答案 1 :(得分:0)

输入后立即将输入转换为int / float,将其包装在循环中的try / except块中以捕获异常并立即再次提示输入:

while True:
    try:
        startmiles = int(input("Enter Your Start Miles = "))
        break
    except ValueError:
        print('that is not an integer, please try again')

或者只是在try / except中包装你的最终计算:

try:
    mpg = (int(endmiles) - int(startmiles)) / float(gallons)
except ValueError:
    print('some error message')

但是这样你就不能轻易要求更多输入,而且你不确切知道哪个值导致了错误。