Python Fundamentals
Python Fundamentals
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.
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.
print(“Hello World”)
print(‘Hello World’)
“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:
Score_ Str1
Math-Score Student_name?
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:
name=”Angelique”
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:
- 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
- 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
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
For the previous example int(age) will give you the integer value of what the user
entered.
“17” 17
age print(Age+1)
print(Age * 2)
print(int(age) + 1)
print(int(“17”)+1)
print(17+1)
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
Eg: If the two numbers entered are 5 and 2, the program should give
statements like this on a new line.
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
z
> greater than
E.g: if (condition)
{
if score > 100:
-
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.
else:
-
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.
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.
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
or
while i < 6:
print(i)
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):
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.
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.
print(fruits)
print(fruits[0])
Exercise: http://www.ASmarterWayToLearn.com/python/15.html
-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.
fruits.append (“orange”)
fruits.insert(2, “strawberry”)
What is in shorter_fruit_list ?
What is shorter_fruit_list ?
Exercise: http://www.ASmarterWayToLearn.com/python/17.html
del fruits[0]
del fruits[4]
You can also remove an element from the list by specifying its value rather than its
position
fruits.remove (“cherry”)
fruits.remove (“guava”)
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
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.
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?
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?
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>:
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
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):
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)
cm_to_m()
“A definition without a call never runs. A call without a definition breaks the
program.”**
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
prod= num1*num2
num1 num 2 prod
print(prod)
num2 = 100
n2 = 2
The values you send when the function are called are “arguments”.
Exercise: at http://www.ASmarterWayToLearn.com/python/42.html
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.
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)
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
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
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
*** 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
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
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.
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.
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
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
index() Searches the tuple for a specified value and returns the position of where it was found