Casting in If statement and using int & float
# equal
5 == 5
# not equal
3 ! = 5
# greater than
5 > 3
# greater than or equal to
5 >= 3
# less than
3 < 5
# less than or equal to
3 <= 5
Casting is where we explicitly tell the computer that what we are typing is a number and not a letter.
The code below is saying any score greater than 100,000 is a winner. Anything less, try again.
myScore = input("Your score: ")
if myScore > 100000:
print("Winner!")
else:
print("Try again ")
- int whole number (ex: 42)
- float any number with a decimal (ex: 1.81)
myScore = int(input("Your score: "))
if myScore > 100000:
print("Winner!")
else:
print("Try again ")
You would do the exact same thing, except using float for a decimal number. In the code below, I want to find pi to 3 decimal places.
We are casting that input as a float which means we are expecting a decimal number. The code will not crash if we put a . and then numbers after it to signify a decimal number.
myPi = float(input("What is Pi to 3dp? "))
if myPi == 3.142 :
print("Exactly!")
else:
print("Try again ")
code for Generation Generator :-
print("Generation Identifier")
userBorn = int(input("Which year were you born:"))
if userBorn >= 1883 and userBorn <=1900 :
print("Lost Generation")
elif userBorn >= 1901 and userBorn <=1927 :
print("Greatest Generation")
elif userBorn >= 1928 and userBorn <= 1945 :
print("silent Generation")
elif userBorn >= 1946 and userBorn <= 1964 :
print("Baby Boomers")
elif userBorn >= 1965 and userBorn <= 1980 :
print("Generation X")
elif userBorn >= 1981 and userBorn <= 1996 :
print("Millenials")
elif userBorn >= 1997 and userBorn <= 2012 :
print("Generation Z")
else:
print("Generation alpha")
No comments:
Post a Comment