Python Variables

Assign and access values:

my_num = 5.7 print(my_num)

- A variable is like a labeled box that can store a value. Later you can access the value by naming the box

Change values:

my_num = 5.7 my_num = 14 print(my_num)

- This will display 14, because the variable will keep the last value that was assigned

Simple data types:

num_siblings = 4 # An integer (int) can only have whole numbers age = 22.5 # A float can have a decimal name = "John Doe" # A string (str) can store text (letters, numbers, and symbols) is_student = True # A boolean (bool) can store True or False

- There are different types of data, but you don't have to specify which type it is

- Sometimes values are treated differently based on their type, for example 2 + 2 = 4, but "2" + "2" is "22"

Change data types (casting):

whole_age = int(age) has_siblings = bool(num_siblings) message = "I have " + str(num_siblings) + " siblings"

- Sometimes it is useful to change a data type of a variable so it can work with other data types properly

- The variable itself isn't modified by casting

- When you cast a float to an int, it rounds down because an integer can't store decimal values

- When you cast a number to a bool, it will be False if 0, or True for any other number

- When you add to a string with the '+' operator, you can only add other strings

Challenge

Create variables to store a customer's name, item name, item cost (as a float), purchase quantity (as an integer), and transaction number. Then display text for a payment receipt that includes all of that information. It should look something like this:

John Doe has purchased 7 apples for $0.76 each. Transaction number: 12356. Thank you.

Completed