Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

python 3.x - TypeError: '<=' not supported between instances of 'str' and 'int' although I converted str to int

I am a python newpie...can anyone tell me what is wrong with the following code? it gives me the above error

inp = input('Enter Hours: ')
inp2 = input ('Enter Rate: ')
if inp <= 0 :
    print ('Please inter a valid number')
if  inp <= 40 :
    Hours = int (inp)
    Rate = int (inp2)
    Pay = inp * inp2
    print ('Pay= ', pay)
elif inp > 40 :
        Hours = int (inp)
        Rate = int (inp2)
        Pay = (inp * 10) + (inp2 - 10) * (1.5)
question from:https://stackoverflow.com/questions/65857770/typeerror-not-supported-between-instances-of-str-and-int-although-i-co

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your first if cases are still of type str. You should also convert your input to an int, before comparing them.

Just took the code that you wrote and moved your str -> int castings up, just before all the if cases. Now your input is converted to an int before it's used in the if cases.

This code will work fine if all inputs are garuanteed to be numeric. Otherwise, you should add some error catching.

inp = input('Enter Hours: ')
inp2 = input ('Enter Rate: ')
Hours = int (inp)
Rate = int (inp2)
if Hours <= 0 :
    print ('Please inter a valid number')
if Hours <= 40 :
    Pay = Hours * Rate 
    print ('Pay= ', pay)
elif Hours > 40 :
        Hours = int (Hours)
        Rate = int (Rate)
        Pay = (Hours * 10) + (Rate - 10) * (1.5)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...