0% found this document useful (0 votes)
7 views55 pages

Class 2

The document outlines various programming concepts and tasks, including variables, data structures (lists, dictionaries, sets), control flow (if-else statements, loops), and functions in Python. It provides examples and exercises for calculating time left until age 90, splitting bills, determining BMI, and assessing compatibility between names. Additionally, it emphasizes the importance of indentation and modular code through functions and classes.

Uploaded by

armaan.dinajpur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views55 pages

Class 2

The document outlines various programming concepts and tasks, including variables, data structures (lists, dictionaries, sets), control flow (if-else statements, loops), and functions in Python. It provides examples and exercises for calculating time left until age 90, splitting bills, determining BMI, and assessing compatibility between names. Additionally, it emphasizes the importance of indentation and modular code through functions and classes.

Uploaded by

armaan.dinajpur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

RECAP

Variables
Types
Arithmetic operators
Boolean logic
Strings
Printing
Exercises
AGENDA
Lists
Dictionaries
Sets
If Else
Loops
Functions
Classes
Exercises
BUT FIRST A FEW TASKS
Create a program that tells us how many days, weeks, months we have left if we live until
90 years old.
It will take your current age as the input and output a message with our time left in this
format:
You have x days, y weeks, or z months left.
Where x, y and z are replaced with the actual calculated numbers.
Warning your output should match the Example Output format exactly, even the positions
of the commas and full stops.

Example Input
56
Example Output
You have 12410 days, 1768 weeks, OR 408 months left.
Instructions
If the bill was $150.00, split between 5 people, with 12% tip.
Each person should pay (150.00 / 5) * 1.12 = 33.6
Format the result to 2 decimal places = 33.60
Thus, everyone's share of the total bill is $30.00 plus a $3.60 tip.

Tip: There are 2 ways to round a number.


format(number, '.2f’) >>> format(math.pi, '.12g') # give 12 significant digits
round(number, digits) '3.14159265359'

.
>>> format(math pi, '.2f') # give 2 digits after the point
Example Input '3.14'
Welcome to the tip calculator!
What was the total bill? $124.56
How much tip would you like to give? 10, 12, or 15? 12
How many people to split the bill? 7
Example Output
Each person should pay: $19.93
LISTS
One of the most useful concepts
Group multiple variables together (a kind of container!)
INDEXING A LIST
• Indexing – accessing items within a data structure

• Indexing a list is not very intuitive...


• The first element of a list has an index 0
QUICK QUIZ
What will fruits[3] return?
QUICK QUIZ
What will this return?
DATA STRUCTURE SIZES
Make sure you are always aware of the sizes of each variable!
This can easily be done using the len() function.
It returns the length/size of any data structure
IS A TOMATO REALLY A FRUIT?

Furthermore, we can modify lists in various ways


LISTS WITH INTEGERS
range() - a function that generates a sequence of numbers as a list
SLICING LISTS
• Slicing – obtain a particular set of sub-elements from a data structure.
• Very useful and flexible.
LISTS – HELPFUL FUNCTIONS
Makes them extremely useful and versatile
LISTS CAN BE OF DIFFERENT TYPES
Not very useful, but possible
MUTABILITY
Mutable object – can be changed after creation.

Immutable object - can NOT be changed after creation.


QUICK QUIZ
Are lists mutable?
TUPLES
Effectively lists that are immutable (i.e., can't be changed)
DICTIONARIES Tanmoy1
• Similar to actual dictionaries
• They are effectively 2 lists
combined – keys and values Nowrin
• We use the keys to access the
values instead of indexing them Kaniz
like a list
• Each value is mapped to a
Irtija
unique key

Tanmoy2
DICTIONARY DEFINITION
Defined as comma separated key : value pairs:

Comma separated

Curly brackets
DICTIONARY PROPERTIES
Values are mapped to a key
Values are accessed by their key
Key are unique and are immutable
Values cannot exist without a key
DICTIONARIES
Let us define the one from the previous image
ACCESSING A DICTIONARY
Values are accessed by their keys (just like a dictionary)

Note that they can't be indexed like a list


ALTERING A DICTIONARY
Can be done via the dictionary methods
KEYS AND VALUES
It is possible to obtain only the keys or values of a dictionary.

This is useful for iteration.


SETS
Effectively lists that cannot contain duplicate items
Similar functionality to lists
Can't be indexed or sliced
Can be created with {} or you can convert a list to a set
IF ELSE
Fundamental building block of software

Conditional statement
Executed if answer is True

Executed if answer is False


IF ELSE EXAMPLE
Try running the example below.
What do you get?
INDENTATION MATTERS!
Code is grouped by its indentation
Indentation is the number of whitespace or tab characters before the code.
If you put code in the wrong block then you will get unexpected behaviour
EXTENDING IF-ELSE BLOCKS
We can add infinitely more if statements using elif

elif = else + if which means that the previous statements must be false for the current one
to evaluate to true
Write a program that works out whether if a
given number is an odd or even number.
Multiple if if and elif Nested if
If condition If condition
code code If condition
If condition elif condition If condition
code code If condition
If condition elif condition code
code code
If condition elif condition else:
code code code

else: else:
code code
BITCOIN BROKER EXAMPLE
QUICK QUIZ
What would happen if both conditions are True?
FOR LOOP
Allows us to iterate over a set amount of variables within a data structure. During
that we can manipulate each item however we want

Again, indentation is important here!


EXAMPLE
Say we want to go over a list and print each item along with its index

What if we have much more than 4 items in the list, say, 1000?
FOR EXAMPLE
• Now with a for loop

• Saves us writing more lines


• Doesn't limit us in term of size
NUMERICAL FOR LOOP
WHILE LOOP
Another useful loop. Similar to the for loop.
A while loop doesn't run for a predefined number of iterations, like a for loop. Instead, it stops
as soon as a given condition becomes true/false.
BREAK STATEMENT
Allows us to go(break) out of a loop preliminary.
Adds a bit of controllability to a while loop.
Usually used with an if.
Can also be used in a for loop.
QUICK QUIZ
How many times are we going to execute the while loop?
FUNCTIONS
Allow us to package functionality in a nice and readable way
reuse it without writing it again
Make code modular and readable
Rule of thumb - if you are planning on using very similar code more than once,
it may be worthwhile writing it as a reusable function.
FUNCTION DECLARATION
keyword Any number of arguments

[Optional] Exits the function and returns some value

• Functions accept arguments and execute a piece of code


• Often they also return values (the result of their code)
FUNCTION EXAMPLE
FUNCTION EXAMPLE 2
We want to make a program that rounds numbers up or down.
Try to pack the following into a function.
FUNCTION EXAMPLE 2
FUNCTION EXAMPLE 3
PYTHON BUILT-IN FUNCTIONS

To find out how they work: https://docs.python.org/3.3/library/functions.html


CLASSES
Important for programming
Useful, but more advanced
Will be taught later with some time limitations .. but there are explanations
and examples in the references
FURTHER READING
LinkedIn Learning:
Python Essentials Training – more detailed; good if you want to use your own
environment – https://www.linkedin.com/learning/python-essential-training-
2/welcome?u=50251009&auth=true
Python for Data Science – continues this course; taught with Jupyter Notebooks as
well – https://www.linkedin.com/learning/python-for-data-science-essential-
training-part-1/data-science-life-hacks?u=50251009&auth=true
Python Crash Course book – more detailed; more exercises
Python Data Analysis – O'Reilly press
PEP 8 style: https://www.python.org/dev/peps/pep-0008/
Write a program that interprets the Body Mass Index (BMI) based on a user's weight and height. It should tell them the
interpretation of their BMI based on the BMI value. The BMI is calculated by dividing a person's weight (in kg) by the square of
their height (in m)
Conditions:
Under 18.5 they are underweight
Over 18.5 but below 25 they have a normal weight
Over 25 but below 30 they are slightly overweight
Over 30 but below 35 they are obese
Above 35 they are clinically obese.

Warning you should round the result to the nearest whole number. The interpretation message needs to include the words from
the interpretations above. e.g. underweight, normal weight, overweight, obese, clinically obese.

Example Input
weight = 85
height = 1.75
Example Output
85 ÷ (1.75 x 1.75) = 27.755102040816325

Your BMI is 28, you are slightly overweight.


Instructions
Write a program that works out whether if a given year is a leap year.
A normal year has 365 days, leap years have 366, with an extra day
in February.

This is how you work out whether if a particular year is a leap year.

Every year that is evenly divisible by 4 **except** every year that is


evenly divisible by 100 **unless** the year is also evenly divisible by
400

e.g. The year 2000


Instructions
Congratulations, you've got a job at Python Pizza. Your first job is to build an automatic pizza
order program.
Based on a user's order, work out their final bill.

Small Pizza: $15


Medium Pizza: $20
Large Pizza: $25
Pepperoni for Small Pizza: +$2
Pepperoni for Medium or Large Pizza: +$3
Extra cheese for any size pizza: + $1

Example Input
size = "L"
add_pepperoni = "Y"
extra_cheese = "N"
Example Output
Your final bill is: $28.
Instructions
You are going to write a program that tests the compatibility between two
people. To work out the love score between two people:

Take both people's names and check for the number of times the letters in the
word TRUE occurs. Then check for the number of times the letters in the word LOVE
occurs. Then combine these numbers to make a 2-digit number.
HINT: use count() to count the number of a particular letter in a string

For Love Scores less than 10 or greater than 90, the message should be:
"Your score is **x**, you go together like coke and mentos."
For Love Scores between 40 and 50, the message should be:
"Your score is **y**, you are alright together."
Otherwise, the message will just be their score. e.g.:
"Your score is **z**."
Example
name1 = "Angela Yu"
name2 = "Jack Bauer"

Love Score = 53
Print: "Your score is 53.“

T occurs 0 times
R occurs 1 time
U occurs 2 times
E occurs 2 times
Total = 5

L occurs 1 time
O occurs 0 times
V occurs 0 times
E occurs 2 times
Total = 3

You might also like