How do you take a users input as a float?

后端 未结 2 661
悲哀的现实
悲哀的现实 2020-12-22 14:20

I\'m running Python 2.7.10. I have the following code block from a program I\'m working on.

with open(\'inventory.txt\', \'r+\') as f:
  inventory = {}
  whi         


        
相关标签:
2条回答
  • 2020-12-22 14:36

    Try using my code. I just made it and started browsing the web for people that. Disclaimer:I made it in Python 3.7 so I am not sure it will work with your problem.

    #Get Input
    User_Input_Number_Here = input ("Enter a number: ")
    try:
    #Try to convert input to Integer
       User_Input_Converted_Here = int(User_Input_Number_Here)
    #It worked, now do whatever you want with it
       print("The number is: ", User_Input_Converted_Here)
    except ValueError:
    #Can't convert into Integer
        try:
    #Try converting into float
           User_Input_Converted_Here = float(User_Input_Number_Here)
    #It worked, now do whatever you want with it
           print("The number is: ", User_Input_Converted_Here)
        except ValueError:
    #Can't convert into float either. Conclusion: User is dumb
    #Give custom error message
           print("Are you by any chance...\nRetarded?")
    
    0 讨论(0)
  • 2020-12-22 14:39

    The short answer is to use float(raw_input('Price: ')), but it might be better to write a method to handle the inputing of floats (and retry until you get what you need).

    def input_float(prompt):
        while True:
            try:
                return float(raw_input(prompt))
            except ValueError:
                print('That is not a valid number.')
    

    then use the method

    inventory[item] = input_float('Price: ')
    
    0 讨论(0)
提交回复
热议问题