I'm fairly new to python and just started yesterday. I gathered the most that I know and formed a little game or set of questions that the user would input his results and it'll come out. However, I reached a point where this one code would not work! Check it out, what have I done wrong.
number = input("type number")
if number is 5:
print("correct")
else:
print("wrong")
as soon as I input 5 in the system, it'll execute "wrong" even when the input is 5. Why?
First, you want to use == (double equals) for comparison, not is. Second, input returns a string, not a number. So it returns '5', which is not the same as 5. So you either want to convert the input to an integer (number = int(number)
), or you want to test against a string (if number == '5':
).
(Aug-30-2017, 04:24 PM)ichabod801 Wrote: [ -> ]First, you want to use == (double equals) for comparison, not is. Second, input returns a string, not a number. So it returns '5', which is not the same as 5. So you either want to convert the input to an integer (number = int(number)
), or you want to test against a string (if number == '5':
).
I feel incredibly stupid! However, I used this line of code:
number = float(input("type number here"))
#instead of
number = int(number)
#I also tried this
number = int(input("type number here"))
'''
and it also worked. However, whats the difference between float and int? when do you use float or int?
or it doesn't matter?
'''
myfloat = 1.23456
myint = int(float)
print('myfloat: {}, myint: {}'.format(myfloat, myint))
mynewfloat = float(myint)
print('mynewfloat: {}'.format(mynewfloat))
an integer is a whole number like 1, 2, 3 ,4 etc.
a float is a number like 1.0, 1.035, 76.4, etc. It contains a mantissa and an exponent.
you can convert a float to an integer, and you will lose any decimal portion
If you then convert back to a float, the decimal portion cannot be restored because it was lost.