For this workshop we're going to dive deeper into python
Python has two kinds of loops, for loops and while loops
Let's first take a look at the for loop:
# we use the range function for "for" loops
for x in range(5): #Here x is the iterater in the range 0-4
print(x)
#We can provide a more specific range in the range function
for num in range(3 , 8): #here we iterate from 3 - 7
print(num) #also notice we used num instead of x; we
Below are some examples
list_of_nums = [1 , 5 , 10 , 20] #initialize list
for i in list_of_nums: #the variable i iterates through every item in the list
print(i)
name = "SDSU AI" #declaring string
for x in name: #iterate through each character in string
print(x)
Now that we went over the basics of for loops, let's look at while loops
#like if statements, while loops use conditional statements
a = 0
while a != 5: #this will execute until it's not true
print(a)
a = a + 1 #we are manually increasing the iterator
When importing modules we usually keep that at the top of our script
Let's take a look
#To use math functions we must import the math module
import math
x = math.pi #Here we are calling the math module to use its pi function
print(x)
#We can also give aliases to packages
# Some packages usually have a typical alias convention
import math as m #You can change this alias to what you want
x = m.pi #We're doing the same as the code above except we call math with an alias 'm'
print(x)
def my_function(): #Here we defined a simple function
print("Python is easy to learn")
Notice above how our function didn't print anything
In order for it to execute we must call it:
def my_function():
print("Python is easy to learn")
my_function() #Calling function
def a_function(student_name): #Here in the paranthesis we define number of parameters
print(student_name + " attends SDSU") #We use arguement in print statement
a_function("Bob") #Call function and provide arguement
a_function("John")
def another_function(name, redid): #Here we have two parameters
print(name + "'s redid is: ", redid)
another_function("Hector" , 1082954) #arguements fill parameters in order so first arguement gets first paramter
def mult_by_five(x):
return x * 5 #returning x value times 5
print(mult_by_five(3))
print(mult_by_five(10))
A lambda function is a one line function with only one expression
#Here's an example of a single function
x = lambda a : a + 10 #a is the parameter and x holds the result
print(x(5)) #5 is the argument being passed to the function
#the function above is equivalent to:
def x(a):
a = a + 10
return a
print(x(5))
#This lambda function takes two arguments
multiply_numbers = lambda a,b : a * b #a and b are parameters
print(multiply_numbers(3,10))#3 and 10 are arguments
#you can also include if else chains in lambda functions
x = lambda x : True if (x > 10) else False
print(x(10))