0
i was being confused about type convertion can u explain ..??
3 Réponses
+ 1
Integer, Float, Double, String, etc.. These are data types. When you assign a variable it gets a Type. if you have a variable of one type and want to convert it to a different type, this is type conversion.
number=5
number is an integer. That is it's type.
number=str(number)
now number is a string.
number=int(number)
now it is an integer again.
fN=4.9
fN=int(fN)
Here fN is a float. Then it is Type converted into an integer. This does not round the float, it simply drops off the decimal. fN is converted to the integer 4
+ 1
thank u so much
+ 1
one area where people struggle (myself included) was using input to compare an if statement. for example..
number = input("Enter a number")
if number == 5:
print("5 was entered")
else:
print("Nothing")
This will always print Nothing. The reason being is input() by default returns a string. if you enter 5 for the number, what you actually entered is "5" ... A few ways to remedy this. if you convert the type after you get it is one way.
number = input("Enter a number")
number=int(number)
now you have gotten your number. which is a string and converted it to an integer. now you would be checking 5 == 5 instead of "5"==5..
a more efficient way to handle this is just get your input as an integer in the first place. think of it as input type conversion.
number = int(input("Enter a number"))
notice how the input is wrapped in int() .. This makes the input an integer instead of the default of being a string.