Variables and Assignment Python
The lesson plan for our lesson on variables
Python
Defining Variables
To define a variable in python, just type in the variable name - one word - and use the =
sign to set it equal to it's value. A variable can be defined using numbers, string, list, or boolean. Strings must have quotations around it and lists must be surrounded by square brackets. Once you have defined a variable, you can do many functions and conditions with it, including the print()
statement.
#defining all the variables using the equal sign
numbervariable = 25
stringvariable = "word"
numberlist = [1, 2, 3, 4, 5]
stringlist = ["a", "b", "c", "d", "e"]
israining = False
#printing all the defined variables
print(numbervariable)
print(stringvariable)
print(numberlist)
print(stringlist)
print(israining)
number = 5 #defining the variable number
x = number * 2 #defining a variable by using another variable
print(number*2) # multiplying a variable by 2
print(x)
list = []
list.append("cookies") # appending a value to a defined list
print(list)
mydict = {"ice cream":"dairy"} # defining dictionary using curly brackets
mydict["banana"] = "fruit" #add keys and values to a dict by setting a value equal to a key, like shown
mydict["ice cream"] = "dessert" #editing a value inside the dictionary
print(mydict)
var1 = "word" # defining first variable
var2 = "number" # defining second variable
temp = var1 # defining temporary variable using the first variable
var1 = var2 # changing the first variable value as the second variable value
var2 = temp # changing the second variable value to the first variable value
number = 20.3 #defining a variable usinbg float
x = number/10 #defining second variable
y = number*2 # defining third variable
print(number) # printing first variable
print(x) #printing second variable
print(y) # printing third variable
print(x*y) #printing the second and third variables multiplied
Even Function
The function below takes in a parameter, x, and determines if x is even or odd. Variables can be used within functions to perform a certain task, which in this case, is to determine even or odd. To define a function, use the variable def
and use a colon. Make sure there are parenthesis next to the function name, even if the function doesn't tkae in any parameters.
def IsEven(x): # define the function
if x % 2 == 0: # % variable returns the remainder of division
# use double equal signs when determining if a value is equal to another value
return True
if x % 2 != 0: # the != means not equal to
return False
#printing the values outputted by the function multiple times
print(IsEven(24))
print(IsEven(7))
print(IsEven(19))
print(IsEven(30))