04 - Objects, Type Casting
Objects
have states and behaviors.
State- data, information about the object itself
Behavior- functions, procedures, things it can do
Everything in Python is an object
ex.
x = 5
An int object.
Has some information about itself- the value 5
Some behaviors that this object of type int can do are add, subtract, multiply, etc.
Objects are defined in classes
Classes have fields for data and function definitions.
Type Casting
The input function is used to get some information from a user of our program.
It always returns a string.
Even if the user were to type the number 5, it would return it to you as a string, like β5β
If we want to do anything with that number (add, subtract), we need to change it into an int!
Type Casting- returns to you a new object of the type you call.
str(), int(), float() are all functions that return a new object of the type you called.
The original object will remain unchanged. (can reassign variable, ex. x = 5 , x = float(5) )
ex. Ask the user their name, calculate how many years they have until they turn 100, print a message letting them know how many years they have until they turn 100.
First, weβll have to ask our user their age, using the input function.
Then, we will need to cast their age to an int so we can calculate the number of years until they turn 100.
There will be three cases to consider,
if the userβs age is less than 100 β> print βyou have __ years until you turn 100β and the __ will be the difference between their age and 100 (100 - age)
if the userβs age is exactly 100 β> print βyou have 0 years until you turn 100β zero is the difference between their age and 100 (100 - age == 0) so actually the same as the first case
if the userβs age is greater than 100 β> print βyou already passed 100β
So, actually I can modify this so that we only have two cases:
if the userβs age is less than or equal to 100 β> print βyou have __ years until you turn 100β the __ will still be the difference between their age and 100
Calculate difference between age and 100
Cast to string and concatenate and print our message
if the userβs age is greater than or equal to 100 β> print βyou already passed 100β
just print message