Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...