5.1. Python Basics#
5.1.1. First Line of Code#
In order to test pieces of code we can run Python from the command line. In this Jupyter Notebook we are going to simulate this. You can type the commands in the fields and execute them. In the field type:
print(‘Hello, World’) Then press [shift] + [return] to execute the command.
print('Hello, World')
Hello, World
Congratulations! You just created a program, that prints the words ‘Hello, World’. The Python environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work.
5.1.2. Math#
Remember that thing called order of operation that they taught in math class? Well, it applies in Python, too. Here it is, if you need reminding:
Parenthesis () Exponents ** Multiplication *, division / and remainder % Addition + and subtraction - Here are some examples that you might want to try, if you’re rusty on this:
1 + 2 * 3
(1 + 2) * 3
5.1.4. Variables#
Now let’s start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let’s make a program that uses variables:
#variables demonstrated
print("This program is a demo of variables")
v = 1
print("The value of v is now", v) # v represents 1
v = v + 1 #v now equals 2
print("v now equals itself plus one, making it worth", v)
v = 51
print("v can store any numerical value, to be used elsewhere.")
print("for example, in a sentence. v is now worth", v)
print("v times 5 equals", v * 5)
print("but v still only remains", v)
print("to make v five times bigger, you would have to type v = v * 5")
v = v * 5
print("there you go, now v equals", v, "and not", v / 5)
This program is a demo of variables
The value of v is now 1
v now equals itself plus one, making it worth 2
v can store any numerical value, to be used elsewhere.
for example, in a sentence. v is now worth 51
v times 5 equals 255
but v still only remains 51
to make v five times bigger, you would have to type v = v * 5
there you go, now v equals 255 and not 51.0
Run the script and try to understand the results.
Note that we can also write v = v + 1 as v += 1. This can be used for all operators (e.g. -=, *=,/=). Try it in the code above.
It is good practice to use lowercase for variables. Don’t use special characters and don’t start with a number!
As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:
#giving variables text, and adding text.
word1 = "Intro"
word2 = "to"
word3 = "Data Science"
print(word1, word2)
sentence = word1 + " " + word2 + " " + word3
print(sentence)
Intro to
Intro to Data Science
Here are some other things you can do with strings!
w = "What's up"
print(len(w))#len shows the amount of letters in a string
9
Let’s say we want to print the character at position 5. Note that the first character “W” is at position 0! So position 5 gives us back “s”.
print(w[5])
s
5.1.5. Functions#
Python has lots of pre-made functions, that you can use right now, simply by ‘calling’ them. ‘Calling’ a function involves you giving a function input, and it will return a value (like a variable would) as output. Don’t understand? Here is the general form that calling a function takes: function_name(parameters)
Examples of functions you have already used:
print('hi') #returns hi
len('hi') #returns 2
Function_name identifies which function it is you want to use. For example, the function raw_input, which will be the first function that we will use. Parameters are the values you pass to the function to tell it what is should do, and how to do it… for example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70 x 5.
len('hi')#reminder that this is a built in function
2
User Made Function
Well, it is all well and good that you can use other people’s functions, but what if you want to write your own functions, to save time, and maybe use them in other programs? This is where the def operator comes in. (An operator is just something that tells Python what to do, e.g. the + operator tells Python to add things, the if operator tells Python to do something if conditions are met.)
This is how the def operator works:
def function_name(parameter_1,parameter_2):
{this is the code in the function}
{more code}
{more code}
return {value to return to the main program}
{this code isn't in the function}
{because it isn't indented}
#remember to put a colon ":" at the end
#of the line that starts with 'def'
#Example 1: double
def double(input):
output = input * 2
return output
double(5)
10
double(10)
20
output #will error! output is defined within the function, so cannot be accessed
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[10], line 1
----> 1 output #will error! output is defined within the function, so cannot be accessed
NameError: name 'output' is not defined
Well, in effect, when a computer runs a function, it doesn’t actually see the function name, but the result of what the function did. Variables do the exact same thing - the computer doesn’t see the variable name, it sees the value that the variable holds. Let’s call this program that multiplied any number by five, multiply(). You put the number you want multiplied in the brackets. So if you typed this:
a = double(70)
The computer would actually see this:
a = 140
The function ran itself, then returned a number to the main program, based on what parameters it was given.
#Example 2
def funnyfunction(first_word,second_word,third_word):
print("The word created is: " + first_word + second_word + third_word) #adding strings together uts them together
return first_word + second_word + third_word
funnyfunction('12', '34', '56') #think about why this function is returning two lines of code!!!
The word created is: 123456
'123456'
5.1.6. Conditionals#
Before we go over if statements, lets go over booleans. Booleans are either True or False.
boolean = True
boolean
True
Certain codes evaluate to booleans:
#True evaluates to True, what about 1 == 1
1 == 1 #basically stating: is one equal to one?
True
2 != 1 + 1 #means not equal (the statement that 2 is not equal to 1 + 1 is False)
False
Now we’ll go through the three keywords for Python conditionals: if, else, and elif.
In Python, the if statement allows you to control the flow of your code based on a logical condition. The constituents of an if statement are
if (optional) else (optional) elif ####If… The most basic if statement has a conditional clause and an indented (nested) block of code that only gets executed when that conditional clause is true.
if <Conditional Clause>:
<Line 1 of code that possibly gets executed...Line 1>
<Line 2 of code that possibly gets executed...Line 2>
elif <Conditional Clause>: #if the first if statement returns False
<Line 1 of code that possibly gets executed...Line 1>
<Line 2 of code that possibly gets executed...Line 2>
else: #if both previous statements return False
<Line 1 of code that possibly gets executed...Line 1>
<Line 2 of code that possibly gets executed...Line 2>
if 1==2: #evaulates to False
print('This line will never get printed out')
if 1==1: #evaluates to True
print('Hello World')
Hello World
temp = 72
if temp > 68 and temp < 82: #'and' means that both need to be True in order to print
print('It is a nice day outside')
It is a nice day outside
#Can you figure out what is going on here?
day_of_week = 'Wednesday'
if day_of_week=='Monday':
special = 'Meat Loaf'
elif day_of_week=='Tuesday':
special = 'Tacos'
elif day_of_week=='Wednesday' or day_of_week=='Thursday':
special = 'Chili'
else:
special = 'Fish Sticks'
print("The special of the day is {}.".format(special))
The special of the day is Chili.
5.1.7. Lists/Arrays#
Earlier when discussing strings we introduced the concept of a sequence in Python. Lists can be thought of the most general version of a sequence in Python, subscripting using the brackets. Unlike strings, they are mutable, meaning the elements inside a list can be changed!
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats’ names.
#Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this:
cats = ['Tom', 'Snappy', 'Oreo', 'Jessie', 'Chester']
cats
['Tom', 'Snappy', 'Oreo', 'Jessie', 'Chester']
You recall values from lists exactly the same as you do with strings. For example, to print the name of your 3rd cat you would do this:
print(cats[2])
Oreo
You can also recall a range of examples, like above, for example - cats[0:2] would recall your 1st and 2nd cats. Try it in the field above.
Where lists come into their own is how they can be modified. To add a value to a list, you use the append() function. Let’s say you got a new cat called Catherine. To add her to the list you’d do this:
cats.append('Catherine')
cats #printing the cats list out after adding to the list
['Tom', 'Snappy', 'Oreo', 'Jessie', 'Chester', 'Catherine']
Clears things up? Good! Now to a sad situation - Snappy was shot by a neighbour, and eaten for their dinner (good on ‘em!). You need to remove him (or her) from the list. Removing that sorry cat is an easy task, thankfully, so you have to wallow in sadness for as short a time as possible:
del cats[1]
cats #notice Snappy disappears
['Tom', 'Oreo', 'Jessie', 'Chester', 'Catherine']
Arrays
Data manipulation in Python is nearly synonymous with NumPy array manipulation: even newer tools like Pandas which we will learn about are built around the NumPy array. The main aspect of NumPy arrays is thta it is easy to do array math on them! Get to know them well!
import numpy as np #we'll understand this later!
x = np.array([1, 2, 3, 4])
x
array([1, 2, 3, 4])
print(x * 2)
print(x / 2)
print(x % 2)
[2 4 6 8]
[0.5 1. 1.5 2. ]
[1 0 1 0]
#this is a 2d array, which is an array inside another array
np.array([np.array([1, 2, 3, 4]), np.array([1, 2, 3, 4]), np.array([1, 2, 3, 4]), np.array([1, 2, 3, 4])])
array([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
5.1.8. For Loops and Iteration#
Basically, the for loop does something for every value in a list. The way it is set out is a little confusing, but otherwise is very basic. Here is an example of it in code:
# Example 'for' loop
# First, create a list to loop through:
newList = [45, 'hmm', 90210, "The day has come, the walrus said, \
to speak of many things", -67]
# create the loop:
# Goes through newList, and sequentially puts each bit of information
# into the variable value, and runs the loop
for value in newList:
print(value)
45
hmm
90210
The day has come, the walrus said, to speak of many things
-67
As you see, when the loop executes, it runs through all of the values in the list mentioned after in. It then puts them into value, and executes through the loop, each time with value being worth something different. Let’s see it again, in a classic Berkeley football call that we all know:
word = 'CAL'
for letter in word:
call = "Gimme a " + letter + "!"
print(call)
print(letter + "!")
qs = ["What does that spell", "Who are we", "And who is gonna win"]
for question in qs:
print(question + '?')
print(word + "!")
Gimme a C!
C!
Gimme a A!
A!
Gimme a L!
L!
What does that spell?
CAL!
Who are we?
CAL!
And who is gonna win?
CAL!
A couple of things you’ve just learnt:
As you see, strings (remember - strings are lines of text) are just lists with lots of characters. The program went through each of the letters (or values) in word, and it printed them onscreen. With normal lists, we iterate through each entry in the sequence.
#Sometimes, you will see the code in ranges
#range(start, stop, step)
list(range(1, 15, 1)) #from 1 inclusive to 15 exclusive going up by 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
5.1.9. Classes#
In this course, although you will not be making classes, you will have to use classes that have been made by others, such as predicting value and doing Machine Learning. So what is a class? Think of a class as a blueprint. It isn’t something in itself, it simply describes how to make something. You can create lots of objects from that blueprint - known technically as an instance.
So how do you make these so-called ‘classes’? very easily, with the class operator:
# Defining a class
class class_name:
[statement 1]
[statement 2]
[statement 3]
[etc]
Makes little sense? That's okay, here is an example, that creates the definition of a Shape:
#An example of a class
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
What you have created is a description of a shape (that is, the variables) and what operations you can do with the shape (that is, the fuctions). This is very important - you have not made an actual shape, simply the description of what a shape is. The shape has a width (x), a height (y), and an area and perimeter (area(self) and perimeter(self)). No code is run when you define a class - you are simply making functions and variables.
The function called init is run when we create an instance of Shape - that is, when we create an actual shape, as opposed to the ‘blueprint’ we have here, init is run. You will understand how this works later.
self is how we refer to things in the class from within itself. self is the first parameter in any function defined inside a class. Any function or variable created on the first level of indentation (that is, lines of code that start one TAB to the right of where we put class Shape is automatically put into self. To access these functions and variables elsewhere inside the class, their name must be preceeded with self and a full-stop (e.g. self.variable_name). Without self you can only use the variables inside the function where they are defined, not in other functions in the same class.
#Think of a class as a cookbook! You probably won't need to make this for this class
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
It’s all well and good that we can make a class, but how do we use one? Here is an example of what we call creating an instance of a class. Assume that the code above has already been run:
rectangle = Shape(100,45)
What has been done? It takes a little explaining…
The init function really comes into play at this time. We create an instance of a class by first giving its name (in this case, Shape) and then, in brackets, the values to pass to the init function. The init function runs (using the parameters you gave it in brackets) and then spits out an instance of that class, which in this case is assigned to the name rectangle.
Think of our class instance, rectangle, as a self-contained collection of variables and functions. In the same way that we used self to access functions and variables of the class instance from within itself, we use the name that we assigned to it now (rectangle) to access functions and variables of the class instance from outside of itself. Adding all code above, we would do this:
#using your cookbook
rectangle = Shape(5, 7) #creating a shape
print(rectangle.area())
print(rectangle.perimeter())
rectangle.scaleSize(2)
rectangle.area() #should be 35 * 4 = 140
35
24
140
We aren’t limited to a single instance of a class - we could have as many instances as we like. We could do this:
longrectangle = Shape(120,10)
fatrectangle = Shape(130,120)
and both longrectangle and fatrectangle have their own functions and variables contained inside them - they are totally independent of each other. There is no limit to the number of instances I could create.
####Congratulations! You are now an expert on Python basics!
5.1.3. Comments#
A comment is a piece of code that is not run. In Python, you make something a comment by putting a hash in front of it. A hash comments everything after it in the line, and nothing before it. Comments are important for adding necessary information for another programmer to read, but not the computer.
Try typing this entire line:
print(“Welcome to Data 198”) #welcomes the student to the Data Science Decal