Python: raw_input and unsupported operand type(s)

前端 未结 3 570
抹茶落季
抹茶落季 2020-12-12 05:45

I am a newbie to Python and have been recently attempting to create a BMI calculator, but I am having errors with the following code:

def calculator():

             


        
相关标签:
3条回答
  • 2020-12-12 05:58

    raw_input always returns a str object. You need to explicitly convert the input to an int. You can either do

    val = int(raw_input(...))
    

    or

    val = raw_input(...)
    val = int(val) 
    

    As others have mentioned, there are many errors in your code. Here is one:

    if height == exit:
    

    Same problem with weight condition. I am just going to point out as you didn't ask about this in question so I will let you find out what the problem is :).

    0 讨论(0)
  • 2020-12-12 06:04

    Please use it this way

    def calculator():
    
        weight = int(raw_input('Please enter your weight (kg):'))
    
        if weight >0 and weight > 0:
            height = int(raw_input('Please enter your height (m):')) 
    
            if height >0 and height > 0:
                bmi = (weight) / (height ** 2) 
    
                print "Your BMI is", bmi
    
                if bmi < 18.5:
                    print 'You are underweight.'
                if bmi >= 18.5 and bmi < 25:
                    print 'Your BMI is normal.'
                if bmi >= 25 and bmi < 30:
                    print 'You are overweight.'
                if bmi >= 30:
                    print 'You are obese.'      
    
            else:   
                height = int(raw_input('Please state a valid number (m):'))
            if height == exit:
                exit()
    
        else:
            weight = int(raw_input('Please state a valid number (kg):'))
    
        if weight == exit:
            exit()
    

    You need to cast input entries to int because they are strings.

    And you no longer have to check if it is a digit,

    Still, I suggest you add another condition like:

    if weight and height:
        #Do stuff
    

    In case no entry was provided.

    EDIT:

    /!\ In case you need decimals cast them to float

    0 讨论(0)
  • 2020-12-12 06:13

    the numbers entered should be converted to float. just change the bmi = float(weight)/(float(height)** 2) You are good to go

    0 讨论(0)
提交回复
热议问题