0% found this document useful (0 votes)
43 views100 pages

Python Fundamentals

Here is one way to write the program: 1. Display the menu items and prices in a formatted string 2. Use input() to ask the user to enter the number of the item they want 3. Use if/elif/else conditional statements to check the user's input and print the appropriate message: - If input is valid number 1-5, print "You chose item #" - Else print "Invalid selection" 4. Ask for any other inputs and end the program The key aspects are displaying the menu clearly, validating the user input, and using conditionals to handle the different possible inputs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
43 views100 pages

Python Fundamentals

Here is one way to write the program: 1. Display the menu items and prices in a formatted string 2. Use input() to ask the user to enter the number of the item they want 3. Use if/elif/else conditional statements to check the user's input and print the appropriate message: - If input is valid number 1-5, print "You chose item #" - Else print "Invalid selection" 4. Ask for any other inputs and end the program The key aspects are displaying the menu clearly, validating the user input, and using conditionals to handle the different possible inputs.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 100

Python

Fundamentals
Programming Terminology
Syntax: the structure of statements in a computer language.
Semantics: deal with the meaning assigned to the symbols, characters
and words.
Command: an instruction given by a user telling a computer to do
something.

Keyword/ Reserved Words: words used by the programming language


and cannot be used for other purposes while programming
Running and Saving Programs in Python
Open “IDLE” in Python

IDLE stands for Integrated Development Environment, it allows you to


create/read/edit and execute your programs under the same roof without touching
the command line.

Click on “File” and open a new file. Save the file with an appropriate name and
with the extension “.py”

Type your program in the text editor provided by idle. Make sure you save any
changes you make in your program before you try to run it.

To run the program, click on run and select “Run Module”.


print()
A command to display something on the screen.

print(“Hello World”)

Displays “Hello World” on the screen.

What does the statement below do?

print(‘Hello World’)

‘Hello World’ and “Hello World” are called String Literals


Introduction to Variables
Variables are containers for storing data values.

Unlike other programming languages, Python has no command for declaring a


variable.

A variable is created the moment you first assign a value to it.

Variables can change values.

“abc”
x = “abc”;
x
y = 300.5;

print (X);
Variable Names
A variable can have a short name (like x and y) or a more descriptive
name (age, carname, total_volume). Rules for Python variables:

● A variable name must start with a letter or the underscore


character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three
different variables)
● Variable names cannot be reserved words
Are these valid variable names? age=”16” +”1”
str1= “123”
_City 4th_subject
str2= “45”
x = 45
1country Population_1948
print (str1 + str2)
home_town Country(1)

Score_ Str1

Math-Score Student_name?

Is it good to name variable with short names?


Data types

Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:

Text Type: str Numeric


Types: int, float, complex

Sequence Types: list, tuple, range Mapping Type: dict

Set Types: set, frozenset


Frequently used Data Types
Str is a string of characters

name=”Angelique”

Int or integer, is a whole number, positive or negative, without decimals, of


unlimited length.

X = 267890

X1 = “124.57”

Y1= 12.5
Practice program 1:
Float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the
power of 10.

y= -12.5

z1=10e2 = 10 x 10 raised 2

z2=10E2 = 10 x 10 raised 2

What is the value of z1 and z2, try it and tell me? Write a python program to print
the values of all the variables above.

y = -12.5
Practice program 2:
Write a program called "Test" that does the following:

-Displays "Testing different variables:"

- creates a variable and assigns a string to it, then displays the string

- creates another variable and assigns a string to it, then displays the second string

-displays the sum of the strings

- creates a variable and assigns an integer to it, then displays the integer

- creates another variable and assigns an integer to it, then displays the second integer

-displays the sum of the integers.


“+” Operator with strings and Integers
“+” Operator

What does it do with integers/ numbers? = addition

What does it do with strings? = Concatenation

What is the operation called when used with strings? Concatenation


Input
input() command
The above command allows us to accept input from a user

Practice program 3:
Try this:
print(“Enter your name:”)
name=input()
print(“Enter your age:”)
age=int(input()) # int(“16”) = 16
print(“Next year at this time ”,name, “ will be ”, age + 1, “ years old”)

Test the above program and tell me what output you see.
What happened?
The input you get from the user when you use input() is always a string, even if
they enter a number.

If you are expecting a number you need to convert it using the following command

int() // type casting

For the previous example int(age) will give you the integer value of what the user
entered.

Modify the program to make it work properly. (3 contd.)


age= input()
Age= int(input())

“17” 17

age print(Age+1)
print(Age * 2)
print(int(age) + 1)

print(int(“17”)+1)

print(17+1)

18 7th Sept 2022

print(int(age)+2) Oct 02nd 2005 Age 16years

2005 + 100 = 2105


Practice program 4:
Write a program that asks the user to enter their name and asks their
age. Print out a message addressed to them that tells them the year
that they will turn 100 years old.

What could be a problem with the program? How can you change it?
Rewrite the program to overcome the problem.
Simple Mathematical Operators
+ Addition

- Subtraction

* Multiplication

/ Division

% Modulus 10%3

** Exponential 2**3

// Floor Division 7.5//2 =3


Practice program 5:
Write a program that takes two integers from a user, saves them in
variables and performs each of the simple operations on the two
variables, it then displays the results for each of the operations giving a
complete statement.

Eg: If the two numbers entered are 5 and 2, the program should give
statements like this on a new line.

The sum of 5 and 2 is 7

The difference of 5 and 2 is 3

Etc etc.
Practice program 6:
Pretend you are a bank. That offers saving accounts at 3% interest, compounded
every 3 months. Ask the user to enter the amount that he/she would like to deposit
and the number of years for which the amount will be deposited. Calculate what
the final amount with interest will be at the end of the time and display this with an
appropriate message.

Tip: Use the link below for more information on how to calculate this.

https://www.thecalculatorsite.com/articles/finance/compound-interest-formula.php
Comparison Operators
== equal to vs = assignment z =10

!= not equal to a=5 b =7 if(a != b) 10

z
> greater than

< less than

>= greater than or equal to

<= less than or equal to


Conditionals
if statement
The section of code following an if statement will execute if the condition of the “if”
statement evaluates to be true.

E.g: if (condition)
{
if score > 100:

print (“You win!”) }

-
print (“Great job”) -
-
Indentation is critical
Conditionals continued...
if and else

If the condition is true the statement after the if executes otherwise the statement
after the else executes. It only checks for one condition.

if score > 100:

print (“You win!”)

else:

print (“Oops you loose!”)

-
Practice program 7a:
Since most banks have a minimum amount that one needs to deposit to be able to
earn compound interest. Modify your program so the minimum amount is
6000usd. If the value entered is not correct, display an appropriate message to
explain that the interest cannot be calculated. While taking the input make sure
you display appropriate messages indicating what you expect the user to input.

- How will you structure this program


Practice program 8:
Write a program that asks the user whether he/she likes dogs or cats. If the
person answers cats, the program displays “You are a cat lover!”, if the person
answers dogs, the program displays “You are a dog lover!”.

if answer == ‘dogs’ //input is Dogs or DOGS

- What type of conditional would you use here and why?


Presentation -1 (group work)
Watch the following videos:
● How computers Work - Part 1
● How Computers Work - Part 2

Explain what you have seen and learnt by making a presentation of your own. Also
make sure to explain what happens when a user runs a program you write, how
does this relate to the 4 things common to all computers mentioned in this video
(input, storage, processing and output). Don’t worry about how your program is
broken into binary that we will see in the near future.

What makes a good presentation? What should be some criteria while grading
your work?
Conditionals continued...
if , elif and else

If the condition is true the statement after the if executes otherwise, if not the
condition for the elif is checked if it is the true the statement after it is executed,
and if none are true the the statement after the else executes.
if (score > 100):
print (“You win!”)
elif score == 0:
print (“you did not start the game!”)
else:
print (“Oops you loose!”)
------
Practice program 9a:
You are designing a ordering software for a fast food restaurant. There are 5 items
on the menu. Display the items and the prices, allow the user to choose what
he/she wants to eat, the user can only choose one item form the menu but can
have more than one of the same item. Display the final price of the order.

Practice program 9b:


Modify the same program so the customer can choose upto 2 items from the
menu (without using a loop) and one or more pieces of the same items. Display
the final price.

Pay attention to the input and outputs statements, remember you are designing a
software. Make your programs self explanatory and user friendly.
What are the grading criteria?
1. Good use of variables
2. Instructions are neat
3. User friendly and good i/p and o/p statements.
4. Accuracy of the program - should do what it needs to do- Test
5. Check spelling
6. Well organised/ clear code - indenting, variables at the start, comments
Logic Operators
and

Used when two or more conditions need to be true

if ((day==”sunny”) and (temp < 35)):

print (“You don’t need to carry an umbrella”)

or

Used when one of many conditions needs to be true

if ((day==”cloudy”) or (day ==”rainy”) or (temp >= 35))

print(“You better carry an umbrella”)


Practice programs 7b:
Since most banks have a minimum amount that one needs to deposit for a
minimum number of years to be able to earn compound interest. Modify your
program so that the minimum amount should be 6000usd and the minimum time is
3years. If either values is not correct, display an appropriate message to explain
that the interest cannot be calculated. While taking the input make sure you
display appropriate messages indicating what you expect the user to input.

- What will you use to do this?


Can you use nested if statements to do Practice Program 7b?
What are nested if statements?
Practice programs 10:
Write a program that asks the user the year when he/she was born. It checks if the
input is a valid year, assuming that a person is not older than the oldest person in
the world and also not too young. If it is not it asks the user to enter it again.It then
checks whether the year when the person was born was a leap year or not and
displays an appropriate message.

Practice programs 11:


Write a program that takes the Computer Science score of a user, it checks if the
score is a valid value. If it is not it asks the user to enter it again. It then calculates
the grade of the student depending on the score and displays the grade with an
appropriate message.
Use the grading scheme in the link:
https://canvas.colostate.edu/grading-schemes/

Use logical operators wherever possible.


Loops!!!
while loop
i = 1

while i < 6:

print(i)

i += 1 # same as writing i = i+1

What will this program do?


Practice programs 9c:
You are designing a ordering software for a fast food. There are 5 items on the
menu. Display the items and the prices, allow the user to do the following:

1. choose 3 items from the menu and one or more portions of the same items
and display the final price. Alter 9b to do this but this time use a loop.
2. modify the same program so the customer can choose as many items she/he
wants from the menu and one or more portions of the same items, display the
final price.
How is this program different from the previous?
i=1

while (i<6):

print (i, end=' ')

i+=1
Sample program for Nested Loop. Pay close
attention to indenting
digit_printed=1
line_number=1
while (line_number<4):
print ("Line number=",line_number)
while (digit_printed<6):
print (digit_printed, end=' ')
digit_printed+=1
digit_printed=1
print(end='\n')
line_number+=1
Comment statement, used to add notes to make
your program more readable.
digit_printed=1
line_number=0

while (line_number<3):
print ("Line number=",line_number+1) # This only shows the line number
while (digit_printed<6):
print (digit_printed, end=' ')
digit_printed+=1

digit_printed=1
print(end='\n') # This inserts a new line
line_number+=1
Practice programs 10b & Practice programs 11b:
Modify the programs to make sure the input from the user is valid. You do not
proceed with the program until you have a valid input. Do this using loops.
Practice programs 12:
-Using nested loops, write a program that displays the following pattern on the
screen.

*
**
***
****
*****
******
*******
********
*********
**********
Practice programs 13:
-Using nested while loops. Write a program that displays the following pattern on
the screen.

**********
*********
********
*******
******
*****
****
***
**
*
Practice programs 14:
Write a program that displays the squares of all numbers between 0 and 10. Use
the exponential operator to do this.

Practice programs 15:


Write a program that takes a starting number from a user and an ending number
from a user and displays the squares of all numbers between the two numbers
including the numbers.

Practice programs 16:


Write a program that takes a number from a user and find its factorial.

- The input must be a positive number


- Do the calculations using a loop.
5! (! = Factorial)
5! = 5 x 4x 3x2x1= 120

0!

1!

-3!
Practice programs 17, 18 & 19:
Write programs using nested loops to generate each of the following series. (One
program per series)
1 1
1
2 3 12
12
4 5 6 123
123
7 8 9 10 1234
1234
11 12 13 14 15 12345
12345
1234
Series B 123
Series A
12
1

Series C
Lists
Lists are used to store multiple items in a single variable.

fruits = ["apple", "banana", "cherry"]

print(fruits)

print(fruits[0])

Reminds you of anything from JS?

Exercise: http://www.ASmarterWayToLearn.com/python/15.html

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


longer. (p. 54). Mark Myers. Kindle Edition.
Things to keep in mind:

-The first element in a list always has an index of 0, not 1. This means that if
the last element in the list has an index of 9, there are 10 items in the list.

- The same naming rules you learned for ordinary variables apply. Only
letters, numbers, and underscores are legal. The first character can't be a
number. No spaces.

- It's a good idea to make list names plural—cities instead of city, for
example—since a list usually contains multiple things.

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


Adding Elements to a List
Append: used to add an element to the end of the list.

fruits.append (“orange”)

What is the new list?

fruits = ["apple", "banana", "cherry", “orange”]

Insert: used to add an element at a particular position in the list

fruits.insert(2, “strawberry”)

What is the new list?

fruits = ["apple", "banana”, “strawberry", "cherry",


Adding Elements to a List contd…
fruits = fruits + [“ pineapple”, “guava”]

What is the new list?

fruits = ["apple", "banana”, “strawberry", "cherry", “orange”,


“pineapple”, “guava” ]

Changing the value of an elements in the list:


fruits [2] = “peach”

What is the new list?

fruits = ["apple", "banana”, “peach", "cherry", “orange”,


“pineapple”, “guava” ]
Taking a slice from a list

shorter_fruit_list = fruits [2:5]

It takes elements 2,3,4.

What is in shorter_fruit_list ?

shorter_fruit_list = [“peach”, “cherry”, “orange”]

shorter_fruit_list = fruits [:3]

What is now in shorter_fruit_list ?

shorter_fruit_list = [“apple”, “banana”, “peach”]


Taking a slice from a list contd…
shorter_fruit_list = fruits [3:]

What is now in shorter_fruit_list ?

shorter_fruit_list = [“cherry”, “orange”, “pineapple”, “guava” ]

shorter_fruit_list = fruits [:5]

What is shorter_fruit_list ?

shorter_fruit_list = ["apple", "banana”, “peach", "cherry", “orange”]

Exercise: http://www.ASmarterWayToLearn.com/python/17.html

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


Practice Program 20

Write a program that does the following:

- Creates a list with 10 strings (2 pts)


- Creates another list with with 3 elements which made up of 2 slices from the
first list.(2 pts)
- Display both lists with appropriate messages. (2 pts)
- Change the 10th element of the first list (1 pt)
- Change the first element of the second list (1 pt)
- Display the changed lists (2 pts)
- Create a third list by concatenating the first two lists(1 pt)
- Take a slice of the first 3 elements, from the third list and display it (2pts)
- Take a slice of the last 4 elements of the first list and display it. (2 pts)
Deleting Elements from a List

What is currently in fruits?

fruits = ["apple", "banana”, “peach",”apple”, "cherry",


“orange”, “pineapple”, “guava” ]

del fruits[0]

What is the new list?

fruits = ["banana”, “peach", "cherry", “orange”, “pineapple”, “guava” ]

del fruits[4]

What is the new list?


Deleting Elements from a List contd…

You can also remove an element from the list by specifying its value rather than its
position

fruits.remove (“cherry”)

What is the new list?

fruits= ["banana”, “peach", “orange”, “guava” ]

fruits.remove (“guava”)

What is the new list?

fruits= ["banana”, “peach", “orange” ]


Popping Elements from a List

What is the difference between deleting and popping?

fruit_disliked = fruits. pop(2)


What is in fruit_disliked?

fruit_disliked = “orange”
fruits= ["banana”, “peach"]

What if I want to make a list of all the fruits I dislike by popping elements that I
dislike from fruits? How can I do that?
Exercise: http://www.ASmarterWayToLearn.com/python/18.html

Exercise: http://www.ASmarterWayToLearn.com/python/19.html

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


longer. (p. 62 & 68). Mark Myers. Kindle Edition.
Practice Program 21 (20 pts)

Write a program that does the following:

● Creates a list with 10 strings (2 pt)


● Display the list. (1 pts)
● Changes all the elements of the list by taking input from the user. (5 pts)
● Display the changed list (2 pts)
● Deletes the 5th element of the list and displays the changed list (3 pts)
● Pops 3 elements from the list and stores them in a new list (5 pts)
● Displays both the lists with appropriate messages. (2 pts)
Ordered
When we say that lists are ordered, it means that the items have a defined order,
and that order will not change.If you add new items to a list, the new items will be
placed at the end of the list.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a
list after it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value

** https://www.w3schools.com/python/python_lists.asp
Practice programs 22 (15pts):
1. Declares and initializes a list of 8 integers (2pts).
2. Displays the list (2 pts).
3. Calculates the sum of the elements in the list, using a loop and
displays it (3 pts).
4. Asks the user for input and replaces all the elements in the list, using a
loop (3pts).
5. Displays the list with the new elements(2 pts).
6. Calculates the sum of the elements in the list, using a loop and
displays it. Also displays the difference between the two sums (3pts) .
From the tutorial
Lists : https://www.w3schools.com/python/python_lists.asp
Tuples
Tuples are also used to store multiple items in a single variable BUT they cannot
be changed unless they are completely redefined.

Examples when this would be used?

Final_scores = (80, 56, 70, 90, 45, 93, 79, 84)

How is this different from the definition of a list?

What will the line below print?

print(final_scores[4])

45
Changing elements in a tuple
As said earlier, the elements of a tuple cannot be changed.

So if the 7th score in the tuple is wrong what would be have to do?

Final_scores = (80, 56, 70, 90, 45, 93, 54, 84)

If the score in the 3rd place should be in the second place and the score from the
2nd place should be in the 4th place and the element in the 4th place should be in
the 3rd place, what would you have to do?

Final_scores = (80, 70, 90, 56, 45, 93, 54, 84)

Exercise: http://www.asmarterwaytolearn.com/python/20.htmlhapter 20 Exercises

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


For loops
This type of loop is used in a sequence and hence can be used for lists, tuples,
dictionaries, set or string.

Below is an example:

total_As=0
for score in final_scores:
if score >= 80:
total_As+=1

if total_As > 0:
print(“ You have”, total_As, “As, well done!”)

Based on the tuple we have what will the output of the above program be?
Syntax For loops
for <variable> in <loop>:

Indenting: What do you observe?


total_As=0
for score in final_scores:
if score >= 80:
total_As++

if total_As > 0:
print(“ You have”, total_As, “As, well done!”)

Exercise: http://www.asmarterwaytolearn.com/python/21.html
**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it
longer. (p. 62 & 68). Mark Myers. Kindle Edition.
From the tutorial

Tuples:https://www.w3schools.com/python/python_tuples.asp

Loop list: https://www.w3schools.com/python/python_lists_loop.asp


Practice programs 22b:
Rewrite program 22, using the new type of loop you have learnt for steps 3 and 5:

1. Declares and initializes a list of 8 integers.


2. Displays the list.
3. Calculates the sum of the elements in the list, using a ‘for’ loop and displays it
(3 pts).
4. Asks the user for input and replaces all the elements in the list, using a loop
What type of loop????.
5. Displays the list with the new elements, using a ‘for’ loop and simultaneously
calculates the sum of the elements. Displays the sum after calculation (2 pts).
6. Also displays the difference between the two sums.
Practice programs 23:

Using 2 tuples, program a game that displays a country name to the user and asks
him/her to name the capital city. Each time the user answers, you ask if he wants
to continue. The game can at most ask the capitals for 25 countries. To make this
more interesting ask the user to pick a number between 0 and 24 and based on
the number ask the question. The game maintains a score and gives an
appropriate message when it ends.
Searching
Describe a simple algorithm that you can use to search if an element is found in a
list.

Sorting
Lets review selection sort with 2 videos and discuss:

https://youtu.be/0-W8OEwLebQ
https://youtu.be/g-PGLbMth_g
Example: 1
Nums= [7, 4, 5, 9, 8, 2, 1]

start_ind=3

min_ind= 5

curr_ind=7

Nums[start_index] =
Nums[min_ind]

Temp = Nums[min_ind]

Nums[min_ind] =
Nums[start_ind]
Practice programs 24 (individual/group work):

Write a program that does the following:


1. Asks the user how many numbers he/she wants to give.
2. Accepts the numbers from a user and puts them in a list.
3. The program then asks the user to enter a number and checks if the number
is in the list. Make sure you write the code to do this using for loop(s) not
using a method provided in Python. (10 points)
Group Work (20 points):
4. The program then sorts the list in ascending and descending order without
using the methods provided in Python; use loops. Which type of loop can be
used here and why?
5. After each sort, it displays the new list.
Summative Lists/Tuples Project (50 pts):
Make a game using the following:
At least 2 lists/ a combination of a list and a tuple,
at least 2 loops of which at least one is nested,
at least 4 list/ tuple related methods you have learnt.

The game should be interactive and fun. It should be easy to for the user to
understand what he or she needs to do, which doesn’t mean it should be easy to
win the game.

The rubric in the link explains how the game will be graded, let’s refine the
highlighted section:
G11: https://docs.google.com/document/d/1nWpqrfFVewuUt8Krt6GYmemH29GwKav-Lmht9aaj_eU/edit?usp=sharing

G10: https://docs.google.com/document/d/1b2tQyEljEfsf9qCWE2sfn13qW8afthVVzW5vxgP_a7k/edit?usp=sharing
Presentations on:
- 3 levels in programming languages
- History of the internet and how it works.
- Object Oriented Programming
Functions
Do you remember what they are?

Functions are a block of code that do a certain task. They need to be defined but
only execute or run when they are called.

def cm_to_m():

cm = 200

m = cm/100

print(m)

What is the above code designed to do?


What do we need to do to execute a function?

Functions can only execute when they are called.

cm_to_m()

Things to keep in mind:


Function definitions and function calls are dependent on each other.

“A definition without a call never runs. A call without a definition breaks the
program.”**

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


longer. (p. 124). Mark Myers. Kindle Edition.
Syntax for function definitions:
Can you fill it in???

def <functionName>():

Note:
The code within the function always needs to be indented.

A function definition must come before the function call. It is generally a good
practice to define functions and other variables at the start of the program.
Practice programs 25

Define a function that prints “Hello Thalun Bears” when it is called. Call the
function 4 times. (5 points)

Exercise: http://www.ASmarterWayToLearn.com/python/41.html

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


longer. (p. 124). Mark Myers. Kindle Edition.
Parameters and Arguments
What does the function below do?

def product(num1, num2):

prod= num1*num2
num1 num 2 prod
print(prod)

num2 = 100

In this example, num1 and num2 are called “parameters”

How would you call this function?


n1=25 n1 n2

n2 = 2
The values you send when the function are called are “arguments”.

What are the arguments you sent in the call above?

What happens to the arguments you sent in the call above?

Exercise: at http://www.ASmarterWayToLearn.com/python/42.html

**Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


longer. (p. 128). Mark Myers. Kindle Edition.
Practice programs 26
Write a program that has/can do the following:
1. A function that can take a temperature in celsius and display the
temperature in fahrenheit. (5 points)
2. Asks the user today's temperature in celsius. (2 pts)
3. Calls the function with the temperature entered by the user. (2 pts)

Practice programs 27
Write a program that has/can do the following:
4. A function that can take a string and display it. (3 points)
5. Asks the user to enter a string. (2 pts)
6. Calls the function with the string entered by the user. (2 pts)
Returning Values from a Function
What does that mean? Consider the program below.

def product(num1, num2):


3 5 15
prod= num1*num2
num1 num 2 prod
return(prod)

n1=3
n2 = 5
ans = product (n1,n2)
print(ans) 3 5 15
print(prod)//??? ans
n1 n2
Condensing lines of code
Can the last two lines in the program above be condensed? How?
print (product (n1,n2))

Can we have more than one function call in the same line?
ans= prod (n1,(prod (n1,n2))
ans=prod(n1,n2)+prod(45,6)

How would this execute?

Note:
● If you have a function call with in a function call, the …innermost function
call…..always executes first.
● Order of precedence for function connected by an operator is left……. to
Functions used as variables
n1= 25
n2= 5
n3=40
n4=2
ans = product (n1,n2) + product(n3,n4)
ans= n1+n2

Can you explain how this works?


Local vs Global Variables
What does that mean? Consider the program below.
n1= 5
n2 = 10 6 10 50

def product(num1, num2): num1 num 2 prod


prod= num1*num2
num1+=1
print(n1)
return(prod)
5 10 50
ans=product (n1,n2)
n1 n2 ans
print(ans)
print(num2)
Local vs Global Variables
What does that mean? Consider the program below.
n1= 5
product
n2 = 10
ans= 0 32 5

def product(n1, n2): n1 n2 prod


prod=n1*n2
print(“The product of”, n1, “and”, n2, “is”, prod)
print(ans)
return(prod)
Main Program

ans = product (32,5) 5 10 160


print(ans) n1 n2 ans
print(n2)
Note:
● “Good coders avoid using global variables inside functions, because it's
confusing. It's better to pass values to functions using arguments. It's better to
keep all the variables used in functions local.”*

Practice Exercises:
http://www.ASmarterWayToLearn.com/python/47.html

http://www.ASmarterWayToLearn.com/python/48.html

http://www.ASmarterWayToLearn.com/python/49.html

http://www.ASmarterWayToLearn.com/python/50.html

*Myers, Mark. A Smarter Way to Learn Python: Learn it faster. Remember it


longer. Mark Myers. Kindle Edition.
Summative Project (50 pts):
Write a real life program/ mini software using the following:
● at least 1 lists/ tuple
● at least one nested loop
● at least 2 list/ tuple related methods you have learnt
● at least two functions of which at least one should accept arguments and one
should return a value.
● at least one call for each function you define and a minimum of 4 function call
is all, for arguments try passing both values and variables.
● appropriate input/output statements.

The program should be interactive and meaningful. It should be easy for the user
to understand what he or she needs to do.
Grading Criteria:
G11 Rubric: https://docs.google.com/document/d/12CYY7U9qzSTZlJ4x6AoW9RaqDtuwupb8tUBXvzzfiEE/edit?usp=sharing

G10 Rubric: https://docs.google.com/document/d/1P96MCLeUoC14Psvcjpb-JrywELZzHdVEBs1O9a3t68U/edit?usp=sharing

*** Make sure to tell me what your program is about by the 22nd. (5 pts) You can
send a private or group message on Hangouts with this information.
Characteristics Comparison List, Tuple & Sets
List Tuples Sets

A single variable that Single Variable that stores Multiple items in a single
stores multiple items multiple items variable

Expendable, Unchangeable Set items are unchangeable,


Removable but you can remove items and
add new items

Ordered sequence Defined Order(Unchangeable) Unordered Sequence(s)

Allows Data Types: Allows Data Types: Boolean, Allowed Data Types: Any
Boolean, Integers, Integers, String
String

Can have duplicate Can have duplicate elements Cannot have duplicates.
elements
Different access methods Comparison List & Tuple
List Tuples

list[0] will return the first element tuple[0] will also return the first element

list[-1] will return the last element tuple[-1] will also return the last element

list[2:5] will return the elements from index tuple[2:5] will also return the elements from
2 but not until index 5, meaning index 4 index 2 but not until index 5, meaning
index 4

list[:4] will return the elements from index 0 tuple[:4] will also return the elements from
but not until index 4, meaning index 3 index 0 but not until index 4, meaning
index 3

list[2:] will return the elements from index 2 tuple[2:] will also return the elements from
to the end index 2 to the end

list[-4:-1] will return the elements from tuple[-4:-1] will also return the elements
index -4 but not until index -1, meaning from index -4 but not until index -1,
index -2 meaning index -2
Changing items in Tuples
● Tuples are immutable so it is mandatory to change them into a list so that we can update/remove items.
○ First method: Convert into a List Third method: Removing

● Second Method: Add tuple to tuple Fourth method: Deleting


Difference/Similarities between loops used with lists and tuples
There are many similarities between loops used with lists and tuples. The usages of for loops and range loops
are similar to one another, however, due to the difference in the immutable feature of tuples, loops that expend
and append items as the code executes cannot be implemented in a tuple.

This is how lists are extended using a while loop. As for tuples, we have to convert the tuple to a list

In the conventional loops which print all elements in the variable, both Lists and Tuples can be looped in the
same way. In these examples, for loops were used and we observe the identical applications of the loop.
The Different methods used to join lists and tuples
Method to join lists Method to join tuples

(+) sign will also allow lists to join together. (+) sign will allow tuples to join together. It
It is called concatenation of lists. is called concatenation of tuples.
I.e. list1 = [1,2,3] I.e. tuple1 = (1,2,3)
list2 = [“Sam”, “john”] tuple2 = (“Sam”, “john”)
print(list1+list2) will display print(tuple1+tuple2) will display
[1,2,3,”Sam”,”john”)] (1,2,3,”Sam”,”john”)

Appending all items from list 2 to list 1 will Type-cast one tuple to a list and append all
also have the same effect as joining lists items from the remaining tuple to the
I.e. list1 = [1,2,3] newly-created list and type cast the newly
list2 = [“Sam”, “john”] created list back to a tuple
for x in list2: I.e. tuple1 = (1,2,3)
list1.append(x) list2 = (“Sam”, “john”)
print(list1) will display [1,2,3,”Sam”,”john”] list1 = list(tuple1)
for x in list2:
list1.append(x)
tuple1 = tuple(list1)
print(tuple1) will display
(1,2,3,”Sam”,”john”)

extend() method is capable of joining 2 lists Type-cast both tuples into two lists, use the
Unpacking Tuples
We usually assign values to a tuple when we initially create it. This is called
packing a tuple. However, extracting these values back to distinct variables is
known as unpacking.
○ e.g.
The statement print(cougar) would now print “Puma
shoes = ( “ Puma”, “Adidas”, “Nike”) And print(stripes) would print “Adidas” and so forth.

(cougar, stripes, god) = shoes

Using Asterisks:
○ If the number of variables is less than the number of values, it will turn the variable with the
asterisk to a list.

players = (“ronaldo”, “messi”, “Ronaldinho”, “Rooney”, “Beckham”, “CR7”)

(brazil, argentina,* barcelona) = players


Practice programs 23:
Write a program that does the following:

1. Declares and initializes a tuple of 8 integers (2pts).


2. Displays the tuple(2 pts).
3. Asks the user for input and replaces all the elements in the tuple(3pts).
4. Displays the tuple with the new elements (2 pts).
5. Create a new tuple with 5 elements and displays it (3pts) .
6. Join the tuples (2 pts)
7. Displays the joint tuples. (1 pt)
Accessing Sets
● Once a set has been created, you are unable to change it. However, you can still access and add items.

The loop will go through the set and print all


Using the keyword in, we can print and determine an
the elements. element of our choice
Methods to add items to a set
-Once a set is created, you cannot change its items, but you can add new items.
Method for adding a new item Use the add() method.
i.e. Fruits ={“apple”, “banana”, “grapes”}
Fruits.add(“oranges”)

print(Fruits) will print out {“apple”, “banana”,


“grapes”, “oranges”}

Method for adding two sets Use the update() method.


i.e. Fruits ={“apple”, “banana”, “grapes”}
Cars = {“Ford”, “Volkswagen”, “Toyota”}
Fruits.update(Cars)

print(Fruits) will print out {“apple”, “banana”,


“grapes”, “Ford”, “Volkswagen”, “Toyota”}

The parameter inside the update method


does not need to be a set. It can be any
iterable object (tuples, lists, dictionaries)
Methods to remove items from a set
Removing an item from a set Use the remove() method.
i.e. Fruits ={“apple”, “banana”, “grapes”}
Fruits.remove(“apple”)

print(Fruits) will print out {“banana”,


“grapes”}
Note: remove() method will raise an error if
the item to remove does not exist

Removing an item from a set Use the discard() method.


i.e. Fruits ={“apple”, “banana”, “grapes”}
Fruits.discard(“apple”)

print(Fruits) will print out {“banana”,


“grapes”}
Note: discard() method will not raise an
error if the item to remove does not exist

Removing the last item from a set Use the pop() method
i.e. Fruits ={“apple”, “banana”, “grapes”}
x = Fruits.pop()
print(x) will print out “grapes”
print(Fruits) will print out {“apple”,
Loop through a set
Looping through a set can be achieved using For loops. Since we are unable to access
items in a set by referring to an index or a key, we have to loop through the items in the set
using a “for” loop and asking a specified value in a set by using the “in”.
Join sets
Sets are joined using the union() command.
Union command returns a new set containing
all items from both sets

Sets are joined using the update() command.


Update inserts all the items from one set into
another.
Join sets
Sets are joined using the intersect_update()
command. The unique feature of the
intersect_update command is method
keeping only the items that are present in
both sets.

Sets are joined using the


symmetric_difference_update() command. In
contrast to the intersect_update command,
symmetric_difference_update() command will keep
only the elements that are NOT present in both
sets.
All methods of lists
Method name Method’s purpose

append() Adds an element to the end of the list

clear() Removes all elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Adds the elements of a list to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes an element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


All methods of Tuples
Method Name Method Feature

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found

You might also like