Wednesday, February 28, 2024

 

Casting in If statement and using int & float

If statements support more than ==. They support inequality symbols as well. Remember those <, >, and = signs you used in math way back . 

# 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

This is because the way input works behind the scenes is it always assumes what you are typing is text (or a string) and gets stored as a variable in " ".

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 ")



Let's add int

There are two types of numbers the computer will recognize:
  • int whole number (ex: 42)
  • float any number with a decimal (ex: 1.81)
int

To change "your score" to a number, we need to add int in front of the input and place the entire input in ()

Update your code to look like this:

myScore = int(input("Your score: "))
if myScore > 100000:
  print("Winner!")
else:
  print("Try again ")

The way the computer will read this code is by starting with what is in brackets first ("your score"). The computer thinks this is text because of the "". When we add int, we are telling the computer, "This is not text. Please convert this to a whole number." Now the variable, myScore will store the answer as a number.

Let's add float

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.

myPi = float(input("What is Pi to 3dp? "))
if myPi == 3.142 :
  print("Exactly!")
else:
  print("Try again ")

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.




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

  2D Dictionaries Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it...