0% found this document useful (0 votes)
5 views

Lab 1

Lab 1 introduces Python and Jupyter Notebook, covering basic concepts such as variable types, Python commands, lists, functions, and loops. It includes practical examples and exercises for creating variables, manipulating lists, and defining functions. The lab aims to equip learners with foundational skills in Python programming for data science applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lab 1

Lab 1 introduces Python and Jupyter Notebook, covering basic concepts such as variable types, Python commands, lists, functions, and loops. It includes practical examples and exercises for creating variables, manipulating lists, and defining functions. The lab aims to equip learners with foundational skills in Python programming for data science applications.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Lab 1 2023-05-15, 8:04 AM

Lab 1
Jupyter Notebook is an open source web application that you can use to create and
share documents that contain live code, equations, visualizations, and text. In this lab we
provide an introduction to Python.

Turn to this link for more details (or simply "Help" tab):
https://nbviewer.org/github/ipython/ipython/blob/3.x/examples/Notebook/Index.ipynb

What are we covering in this lab?

1. Introduction to Python and Jupyter notebook


2. Types of variables
3. Basic Python commands
4. Lists and functions
5. Boolean operators and loops

Basic Python Instances


Python Operators: https://www.w3schools.com/python/python_operators.asp

print() function prints the specified message to the screen. The message can be a
string, or any other object, the object will be converted into a string before written to the
screen.

In [ ]: print("Hello World")

You can add comments to your Python scripts. Comments are important to make sure
that you and others can understand what your code is about. To add comments to your
Python script, you can use the # tag. It will not be shown in the output.

In [ ]: # I'm computing a division


print(1/2)

You can use python as a calculator

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 1 of 13
Lab 1 2023-05-15, 8:04 AM

In [ ]: # Multiplication, division, and exponentiation


print(5 * 4)
print(15 / 3)
print(5 ** 3)

Variables and types


Variables
If you want to do more complex calculations, you will want to "save" values while you're
coding along.

You can do this by defining a variable, with a specific, case-sensitive name. Variable
names can start with a letter or _, but not a number or any other operator. Once you
create such variable, you can later call up its value by typing the variable name. Every
time you type the variable's name, you are asking Python to change it with the actual
value of the variable.

To create a variable use = like in the following example

In [ ]: # Creating a variable called hello


hello = "Hello World"

# print variable hello by calling its name


print(hello)

Create two variables called x and y, x corresponds to 10 and y to 5. Notice that we are
not printing anything so we don't get any output when we run this line of code.

In [ ]: x = 3
y = 6

Print the result of x2 + y2

In [ ]: # reproducible
print(x**2 + y**2)

In Python, variables are used all the time. They help to make your code reproducible.

In [ ]: # not reproducible
print(3**2 + 6**2)

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 2 of 13
Lab 1 2023-05-15, 8:04 AM

Python Types
You can check out the type of a variable with the type function. To see the type of x,
simply run type(x) . Number have usually two types in Python. A value has a float
type if it's a real number, and a value has a int type if it has only an integer part.

In [ ]: type(x)

Practice: Create a variable called height with value 75.2 and check its type.

In [ ]: # Complete this code with the information provided.


height = ____
type(___)

Other python types are strings and booleans.

A string or str for short is how python represents text. You can use both double and
single quotes to build a string. The Boolean or bool for short is a type that can either
be True or False. You can think of it as 'Yes' and 'No' in practice.

Python Strings: https://www.w3schools.com/python/python_strings.asp

In [ ]: word = "data science"


text = 'this works too'

In [ ]: type(word)

In [ ]: w = True
type(w)

The + operator behaves differently for different data types. For string it pastes them
into one, for integer or float values it adds them.

In [ ]: print("Data" + "Science" + "1000")

In [ ]: print(5 + 10)

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 3 of 13
Lab 1 2023-05-15, 8:04 AM

Type conversion
Using the + operator to paste together two strings can be very useful in creating
custom messages.

Let's say we want to print the following message:

The sum of x and y is x + y, but instead of x + y we want to display the result of the
sum.

To do this, you'll need to explicitly convert the types of your variables so that they are all
strings. More specifically, you'll need str(), to convert a value into a string. str(x) , for
example, will convert the integer x to a string.

Similar functions such as int() , float() and bool() will help you convert Python
values into any type.

In [ ]: x = 20
y = 7
print("The sum of x and y is " + str(x + y))

Data Structures
There are many data structures in Python. We will mainly cover the structures that are
related to this data science course.

Dictionaries: https://www.w3schools.com/python/python_dictionaries.asp

Python lists: https://www.w3schools.com/python/python_lists.asp

Usually, instead of working with only one value, like we have for x and y in the previous
example. We will work with many values at a time. So, we will need to stored these
values somewhere.

Data Structures are here for this purpose. The data structure that we use depend on the
type of value we want to save. Let's start with lists.

Lists

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 4 of 13
Lab 1 2023-05-15, 8:04 AM

A list is a way to give a single name to a collection of values. These values, can have any
type; they can be floats, integer, booleans, strings. A list can contain different types. To
create a list we use [] .

In [ ]: # Create and print a list called list_1 that contains only integers
list_1 = [1, 2, 3]
print(list_1)

In [ ]: # Create and print a list that contains strings and integers values
list_2 = ["a", 1, "b", 5, "c", 7, 'z']
print(list_2)

Practice: Create and print a list called newlist with the following elements
'DataScience' , 'Python' , 100 , True , 3.14 .

In [ ]: #Your code here

Subsetting lists
Now that we know how to create lists in Python, we need to know how you can access
information in the list. Python uses the index to do this. The first element in the list has
index 0, the second element has index 1, and so on. To select a element in a list we write
the name of the list then inside [] we define the index we want, e.g.,
name_list[index] .

In [ ]: # Create a list called heights with 7 numbers


heights = [75, 64.5, 67, 89, 70.4, 63, 50.9]

In [ ]: # Print the height for the second element in the heights list which has the index
print(heights[1])

Slicing lists
Instead of selecting only one element of a list to print, we can select multiple elements
by specifying the range of indeces we want to print. By using [start_index :
end_index] which is inclusive for start_index and exclusive for end_index .

In [ ]: # Print the fourth until the sixth element in the heights list
print(heights[2:4])

If you leave out the index where the slice should begin, you're telling Python to start the
slice from index 0. If you leave out the index where the slice should end, you include all
elements up to and including the last element in the list.

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 5 of 13
Lab 1 2023-05-15, 8:04 AM

In [ ]: # Print the first 2 elements in the heights list


print(heights[:2])

#Print the last 3 elements in the heights list


print(heights[4:])

Manipulating lists
We may also be interested in changing elements in our list, or we may want to add
elements to the list or even remove elements from our list.

Changing list elements is pretty straightforward. You use the same square brackets that
we've used to subset lists, and then assign new elements to it using = .

In [ ]: heights[2] = 97
print(heights)

Practice: Change the last element of the heights list to be now equal to 100. Then
print the list so we can see the change.

In [ ]: # Your code here

Now, if you want to add elements to a list you can use + or the method append
(which we are going to see later in this lab, when we introduce methos). See below some
examples:

Note: The elements you want to add to our list need to be in a list when we use + . Also,
when we use + we need to create a variable with the same name as the previous list so
that the change will show in our original list.

In [ ]: heights = heights + [2]

Now, if you want to delete elements in a list, we use the same ideas as when we want to
select elements in a list with the del function. As soon as you remove an element from
a list, the indexes of the elements that come after the deleted element all change.

In [ ]: # Delete first element in heights list. Don't forget to print the list so we can s
del(heights[0])
print(heights)

Functions

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 6 of 13
Lab 1 2023-05-15, 8:04 AM

Functions aren't entirely new for you, we already used them. type , for example, is a
function that returns the type of a value. You can call functions instead of having to write
code yourself. Example of functions in Python min , mean , max , print , round ,
len . Functions are usually colored in green.

Instead of writing your own code that goes through the list and finds the highest value,
we can use Python's max function. We simply pass the name of our list to max inside
() .

In [ ]: # Let's use the function max to get the maximum value in the heights list
print(max(heights))

Another function we will use quite a lot is round . It takes two inputs: first, a number
you want to round, and second, the precision with which to round, which is how many
digits after the decimal point you want to keep

In [ ]: print(round(2.78, 1))
print(round(2.78))

If you want to know how many elements we have in a list or string we can use the
function len short for lenght.

In [ ]: # Print the number of elements in the heights list


print(len(heights))

# Print the number of elements in the string 'Data'


print(len("Data"))

To get more information about what a function does, what are its inputs and outputs you
can always use the help function

In [ ]: help(round)

Methods
Depending on the type of a object in Python. Objects are variables in Python, that is, a
string is an object, a list is an object, and so on. So depending on the type of object we
can apply functions, called methods, that are specific to each python type.

Fo example, append is a method for lists only and to use it, we need to write the name
of our list and use .append to use the function.

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 7 of 13
Lab 1 2023-05-15, 8:04 AM

In [ ]: heights.append(1)
print(heights)

Another method we can use in lists or strings is index , which returns the index of the
element we want we just need to write the name of our list or variable that you used to
stored the string and then use .index with the element we want inside ()

In [ ]: # What is the index of the height 64.5 in our list called heights?
print(heights.index(70.4))

In [ ]: # Using the method count for strings to count how many a's there are in DataScienc

# First we create a variable to stored the string DataScience


string = 'DataScience'

# Now we print how many a's we have in this string using the count method
print(string.count('a'))

In [ ]: #help(str) # shows all methods we can apply into a string including count

Practice Create a list called score with values 100, 50, 56.5, 70.2, 85, 99. Then use
the append() method to add the value 50 to our list. Then print our list to see the
change.

In [ ]: # Your code here

Creating your own functions

Python Functions: https://www.w3schools.com/python/python_functions.asp

A recipe to create functions in Python is: First we define our function by writing def
then we write the name_of_our_function and inside the () we define the inputs
(arguments) our function takes. The output of our function is defined using return at
the end of the function.

To call our function we write its name and inside () we give the values for our inputs.

In [ ]: # Create a function called double that has one input (called x), our function retu
def double(x):
return 2 * x

# Call our function with input = 17


double(17)

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 8 of 13
Lab 1 2023-05-15, 8:04 AM

Let's create a function that takes more than one argument (input). Create a function
called percent that returns the percentage up to 2 decimal places of a number called x
with respect to a total. Our arguments are x and total .

In [ ]: def percent(x, total):


return round((x / total) * 100, 2)

# Call function with x = 33 and total = 200


percent(33, 200)

Practice: Add another argument to the previous function called decimal_places , so


that now the number of decimal places is also an argument of our function. Complete
the code below, and call our function now with x = 37 , total = 120 and
decimal_places = 4 .

In [ ]: # Complete the code below:

def percent(x, total, _____):


return round((x/total)*100, _____)

# Call function with x = 37, total = 200 and decimal_places = 4

In [ ]: # Dictionaries have a Key and a value.


dict_1 = {"Stats" : "Happy"}
print("The dictionay holds", dict_1, "and the 'Stats' value is:", dict_1["Stats"

Booleans operators
Comparison operators are used to compare values. When we use an comparison
operator, we our dealing with boolean variables (Remember the begging of this lab when
we discussed boolean variables True and False )

Logical Operators :
https://www.w3schools.com/python/gloss_python_logical_operators.asp

Conditional Statements : https://www.w3schools.com/python/python_conditions.asp

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 9 of 13
Lab 1 2023-05-15, 8:04 AM

Operator What it means Example

== Equal to 4 == 5 is False

!= Not equal to 4 != 5 is True

< Less than 4 > 5 is False

> Greater than 4 < 5 is True

<= Less than or equal to 4 >= 5 is False

>= Greater than or equal to 4 <= 5 is True

In [ ]: x = 5
y = 8

In [ ]: print("x == y:", x == y)
print("x != y:", x != y)
print("x < y: ", x < y)
print("x > y: ", x > y)
print("x <= y:", x <= y)
print("x >= y:", x >= y)

Logical Operators
There are three logical operators that are used to compare values. They evaluate
expressions down to Boolean values, returning either True or False . These
operators are and , or , and not . Let's check some examples on how to use them.

Operator What it means Example

and True if both are True x and y

or True if at least one is True x or y

not True only if it is False not x

Logical operators are typically used to evaluate whether two or more expressions are
true or not true. For example, we can use logical operators to check if someone is female
and is older than 30 years old.

Note: You can use & and | instead of and and or .

In [ ]: print((9 > 7) and (2 < 4)) # Both expressions are True


print((8 == 8) | (6 != 6)) # One expression is True
print(not(3 <= 1)) # The expression inside not is False

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 10 of 13
Lab 1 2023-05-15, 8:04 AM

Boolean Operators Testing


The most popular use for a Python Boolean is in an if statement. This statement will
execute if the value is True .

In [ ]: grade = 70

In [ ]: if grade >= 65: # Condition


print("Passing grade") # Clause

else:
print("Failing grade")

In [ ]: if grade > 90 and attendence == 100:


print("Star")
else:
print("no Star")

In [ ]: # Create a if statement with more than one else


if grade > 90 and attendence == 100:
print("Star")
elif grade > 60:
print("Passing grade")
else:
print("Failing grade")

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 11 of 13
Lab 1 2023-05-15, 8:04 AM

Loops
Loops are important in Python or in any other programming language as they help you to
execute a block of code repeatedly. You will often come face to face with situations
where you would need to use a piece of code over and over but you don't want to write
the same line of code multiple times.

The word "loop" refers to a piece of code that you execute repeatedly.

While lop
While Looping: https://www.w3schools.com/python/python_conditions.asp

A while loop, when it's implemented, executes a piece of code over and over again
while a given condition still holds true.

To run a while loop in Python we need to write

while condition :

code

The condition needs to return True or False

In [ ]: x = 1
while x != 10:
print(x)
# Increment the value of the variable "x by 1"
x = x + 1

The above example is a bit basic, you can also include conditionals, or, in other words,
an if condition, to make it even more customized. Check the next example

In [ ]: # Take user input


number = 2

# Condition of the while loop


while number < 5 :
# Find the mod of 2
if number%2 == 0:
print("The number "+str(number)+" is even")
else:
print("The number "+str(number)+" is odd")

# Increment `number` by 1
number = number + 1

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 12 of 13
Lab 1 2023-05-15, 8:04 AM

For loops
For Looping: https://www.w3schools.com/python/python_for_loops.asp

As you probably would have expected, the "for" component in "for loop" refers to
something that you do for a certain number of times. In contrast to the while loop, there
isn't any condition actively involved - you just execute a piece of code repeatedly for a
number of times. For loop executes the code contained within it only for a specific
number of times. This "number of times" is determined by a sequence or an ordered list
of things.

To create for loops we use the recipe:

for a variable in range() :

code

The range(start, stop, step) function creates a sequence of numbers in a


specific range. The range function returns an object that produces a sequence of
integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i + 1,
i + 2, ..., j − 1. start defaults to 0, and stop is omitted!
range(4) produces 0, 1, 2, 3.

In [ ]: # Create a list of number using range function


numbers = list(range(1,11,3))
print(numbers)

In [ ]: for i in range(1, 11, 3):


print(i)

Let's consider another example of a for loop, where you make use of two variables to
define our flow.

In [ ]: words = ["stats", "math", "exams", "python"]


for i in range(len(words)):
print(words[i])

In the loop above, we have that for every index in the range len(words) , you want to
print the each word in the list.

http://localhost:8890/nbconvert/html/Documents/Phd%20STATISTICS%20-%20Western/Spring%202023/Labs/Lab%201.ipynb?download=false Page 13 of 13

You might also like