SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2015
Midterm Review
What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
Lists
A Closer Look At Our First Program
• # My first Python program.
– This is a comment – it’s for you, not the computer
– Comments begin with # and are not statements.
• print("Hello, World!")
– displays a line of text, namely “Hello, World!”.
– We call a function named print and pass it the information to be
displayed.
– A function is a collection of programming instructions that carry
out a particular task.
– It is part of the Python language.
Print Function Syntax
Let’s Talk About Variables…
• Variables are reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
• Variables in Python consist of an alphanumeric name beginning in a letter or
underscore. Variable names are case sensitive.
• Python variables do not have to be explicitly declared to reserve memory
space. The declaration happens automatically when you assign a value to a
variable. The equal sign (=) is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable.
• Examples:
counter = 100
miles = 1000.0
name = "John"
Image Credit: ClipArt Best
Python variable
names can have
unlimited length –
but keep them short!
Let’s Talk About Python Math!
Normal Stuff
Weird Stuff
5%2 = 1
Modulo (%) Is Your Friend
• A man has 113 cans of Coke. He also has a group of boxes that can hold 12 cans
each. How many cans will he have left over once he’s loaded all of the boxes?
• On a military base the clock on the wall says that the time is 23:00. What time of
day is this?
• My friend has 10,432 ping pong balls that he needs to put into storage. My car can
transport 7,239 balls. How many will be left after I leave?
What Comes First?
Precedence Rules
• The precedence rules you learned in algebra apply during the evaluation of
arithmetic expressions in Python:
– Exponentiation has the highest precedence and is evaluated first.
– Unary negation is evaluated next, before multiplication, division, and
remainder.
– Multiplication, division, and remainder are evaluated before addition and
subtraction.
– Addition and subtraction are evaluated before assignment.
– With two exceptions, operations of equal precedence are left associative,
so they are evaluated from left to right. Exponentiation and assignment
operations are right associative, so consecutive instances of these are evaluated from right to
left.
– You can use parentheses to change the order of evaluation
• "PEMDAS", which is turned into the phrase "Please Excuse My Dear Aunt
Sally". It stands for "Parentheses, Exponents, Multiplication and Division, and
Addition and Subtraction".
3**2
-5
2+3*4/6
sum = 2+3
2+3*4/6
sum = 3**2**5
(2+3)*4/5
Image Credit: www.pinterest.com
Precedence Rules: Examples
• Simplify 4 + 32
• Simplify 4 + (2 + 1)2
• Simplify 4 + [–1(–2 – 1)]2
• Simplify 4( –2/3 + 4/3)
• Three people ate dinner at a restaurant and want to split the
bill. The total is $35.27, and they want to leave a 15 percent
tip. How much should each person pay?
Image Credit: pixgood.com
Not All Numbers Are Created Equal
• Integers are the numbers you can easily count, like 1,
2, 3, as well as 0 and the negative numbers, like –1, –2,
–3.
• Decimal numbers (also called real numbers) are the
numbers with a decimal point and some digits after it,
like 1.25, 0.3752, and –101.2.
• In computer programming, decimal numbers are also
called floating-point numbers, or sometimes floats for
short (or float for just one of them). This is because the
decimal point “floats” around. You can have the
number 0.00123456 or 12345.6 in a float.
Image Credit: www.clipartpanda.com
Mixed-Mode Arithmetic
and Type Conversions
• Performing calculations involving both integers and
floating-point numbers is called mixed-mode arithmetic.
• Conversions
– Determine type: type()
– Drop decimal: int()
– Round up / down: round()
– Change to decimal: float()
– Change to string: str()
Image Credit: personaltrainerbusinesssystems.com
Cool Kid Stuff:
Increment / Decrement / E-Notation
• Incrementing: sum = sum + 1
– sum += 1
• Decrementing: sum = sum – 1
– sum -= 1
• E-Notation
– 1,000,000 = 1 x 10**6 = 1e6
Image Credit: www.toonvectors.com
Say Hello To Strings!
• Your computer programs will have to process text
in addition to numbers.
• Text consists of characters: letters, numbers,
punctuation, spaces, and so on.
• A string is a sequence of characters.
• Example: “John Smith”
Image Credit: imgarcade.com
How Do We Deal With Strings?
• Strings can be stored in variables:
answer = “a”
• A string literal denotes a particular string:
“Mississippi”
• In Python, string literals are specified by enclosing a
sequence of characters within a matching pair of either
single or double quotes.
“fire truck” or ‘fire truck’
Image Credit: imgarcade.com
Strings and Characters
• Strings are sequences of Unicode characters.
• You can access the individual characters of a
string based on their position within the
string.
• This position is called the index of the
character.
Image Credit: www.fontspace.com
0 1 2 3 4
First Last
String Indexes
• name = “TILEZ”
• len(name) = 5
• name[0] = “T”, name[4] = “Z”
0 1 2 3 4
All Characters Have Numbers
• A character is stored internally as an integer value. The
specific value used for a given character
is based on its ASCII code (or Unicode code).
• Python provides two functions related to character encodings.
– The ord function returns the number used to represent a given
character. ord(“A”) = 65
– The chr function returns the character associated
with a given code. chr(65) = “A”
Image Credit: www.clipartpanda.com
Input and Output
• When a program asks for user input, it should first print a message that
tells the user which input is expected. Such a message is called a prompt.
In Python, displaying a prompt and reading the keyboard input is
combined in one operation.
– first = input("Enter your first name: ")
• The input function displays the string argument in the console window
and places the cursor on the same line, immediately following the string.
– Enter your first name: █
Image Credit: blogs.msdn.com
Numerical Input
• The input function can only obtain a string of text from the
user.
• To read an integer value, first use the input function to obtain
the data as a string, then convert it to an integer using the int
function.
numBottles = input("Please enter the number of bottles: ")
bottles = int(numBottles)
bottlePrice = input("Enter price per bottle: ")
price = float(bottlePrice)
Image Credit: www.canstockphoto.com
Formatted Output
• To control how your output looks, you print a formatted string and then provide the values
that are to be “plugged in”.
• If the value on the right of the “%” is a string, then the % symbol becomes the string format
operator.
• The construct %10.2f is called a format specifier: it describes how a value should be
formatted.
– The 10 specifies the size of the field, the 2 specified the number of digits after the “.”.
– The letter f at the end of the format specifier indicates that we are formatting a floating-point value. Use d for an
integer value and s for a string;
Formatted Output
• To specify left justification for a string, add a minus sign
before the string field width:
title1 = "Quantity:“
title2 = "Price:"
print("%-10s %10d" % (title1, 24))
print("%-10s %10.2f" % (title2, 17.29))
• The result is:
Quantity: 24
Price: 17.29
Image Credit: www.theindianrepublic.com
Python Format Specifier Examples
Say Hello To The “IF” Statement
• In Python, an IF statement is used to
implement a decision.
• When a condition is fulfilled, one set of
statements is executed. Otherwise, another
set of statements is executed
Image Credit: www.clipartpanda.com
Syntax Of Python IF Statement
Tabs
• Blockstructured code has the property that nested statements are indented by one
or more levels:
if totalSales > 100.0 :
discount = totalSales * 0.05
totalSales = totalSales − discount
print("You received a discount of $%.2f" % discount)
else :
diff = 100.0 − totalSales
if diff < 10.0 :
print("purchase our item of the day & you can receive a 5% discount.")
else :
print("You need to spend $%.2f more to receive a 5% discount." % diff)
Image Credit: www.clipartpanda.com
Relational Operators
Equality
Testing
Requires
2 “=“
Note: relational operators have a lower precedence than arithmetic operators
Examples Of Relational Operators
What Is A “Nested Branch”?
• It is often necessary to include an if statement
inside another. Such an arrangement is called
a nested set of statements.
• Example:
Is the
club
full?
Arrive at
the club
Are you
on the
VIP list?
Wait in car
Go right in
Wait in line
Y
Y
N
N
Example of a “Nested Branch”
if (peopleInClub < maxPeopleInClub) :
if (youName == VIPListName) :
goRightIn
else :
waitInLine
else :
waitInCar
Problems With “Super Nesting”
• Difficult to read
• Shifted too far to the right due to indentation
Image Credit: www.clipartbest.com
A Better Way: elif
If (classScore >=90) :
print(“You got an A!”)
elif (classScore >= 80) :
print(“You did ok, you got a B!”)
elif (classScore >=70) :
print(“So-so, you got a C”)
elif (classScore >= 60) :
print(“Oh –oh, you got a D”)
else :
print(“Dang it, you got an F”)
Image Credit: jghue.blogspot.com
Note that you have to test the more specific conditions first.
How Do You Do Things
Over And Over Again?
• In Python, loop statements repeatedly execute instructions until a
goal has been reached.
• In Python, the while statement implements such a repetition. It has
the form:
while condition :
statement1
statement 2
• As long as the condition remains true, the statements inside the
while statement are executed.
Image Credit: etc.usf.edu
Body
Condition
How Can I Loop For A Given Number
Of Times?
• You can use a while loop that is controlled by a
counter:
counter = 1 # Initialize the counter.
while counter <= 10 : # Check the counter.
print(counter)
counter = counter + 1 # Update the loop variable
Note: Some people call this loop count-controlled.
Image Credit: www.dreamstime.com
The For Statement
The for loop can be used to iterate over the contents of any container, which is an
object that contains or stores a collection of elements. Thus, a string is a container
that stores the collection of characters in the string.
What’s The Difference Between While
Loops and For Loops?
• In the for loop, the element variable is
assigned stateName[0] , stateName[1] , and so
on.
• In the while loop, the index variable i is
assigned 0, 1, and so on.
Image Credit: www.clipartpanda.com
The Range Function
• Count-controlled loops that iterate over a range of integer values are very
common.
• To simplify the creation of such loops, Python provides the range function
for generating a sequence of integers that can be used with the for loop.
• The loop code:
for i in range(1, 10) : # i = 1, 2, 3, ..., 9
print(i)
prints the sequential values from 1 to 9. The range function generates a
sequence of values based on its arguments.
• The first argument of the range function is the first value in the sequence.
• Values are included in the sequence while they are less than the second
argument
Image Credit: www.best-of-web.com
You Can Do The Same Thing With
While And For Loops
for i in range(1, 10) : # i = 1, 2, 3, ..., 9
print(i)
i = 1
while i < 10 :
print(i)
i = i + 1
Image Credit: www.rgbstock.com
Note that the ending value (the second argument to the range function) is not included
in the sequence, so the equivalent while loop stops before reaching that value, too.
Stepping Out…
• By default, the range function creates the
sequence in steps of 1. This can be changed
by including a step value as the third
argument to the function:
for i in range(1, 10, 2) : # i = 1, 3, 5, ..., 9
print(i)
Image Credit: megmedina.com
Review: The Many Different Forms Of
A Range
Secret Form Of print Statement
• Python provides a special form of the print function that prevents it
from starting a new line after its arguments are displayed.
print(value1, value2, end="")
• By including end="" as the last argument to the first print function,
we indicate that an empty string is to be printed after the last
argument is printed instead of starting a new line.
• The output of the next print function starts on the same line where
the previous one left off.
Image Credit: www.clipartpanda.com
4 Steps To Creating A Python List
1. Convert each of the names into strings by surrounding the
data with quotes.
2. Separate each of the list items from the next with a comma.
3. Surround the list of items with opening and closing square
brackets.
4. Assign the list to an identifier (movies in the preceding code)
using the assignment operator (=).
“COP 2271c” “Introduction to Computation and Programming” 3
“COP 2271c”, “Introduction to Computation and Programming”, 3
[“COP 2271c”, “Introduction to Computation and Programming”, 3]
prerequisites = [“COP 2271c”, “Introduction to Computation and Programming”, 3]
COP 2271c Introduction to Computation and Programming 3
Image Credit: Clipart Panda
How To Access A List
• A list is a sequence of elements, each of which has an
integer position or index.
• To access a list element, you specify which index you
want to use.
• That is done with the subscript operator ([] ) in the
same way that you access individual characters in a
string.
• For example:
print(values[5]) # Prints the element at index 5
Image Credit: imgkid.com
Access Your List Data Using The Square
Bracket Notation
print (prerequisites[0]) COP 2271c
print (prerequisites[1]) Introduction to Computation and Programming
print (prerequisites[2]) 3
Image Credit: Clipart Panda
You Can Create
Multidimensional Lists
• Lists can hold data of mixed type.
• But it gets even better than that: lists can hold
collections of anything, including other lists.
• Simply embed the inner list within the enclosing
list as needed.
multiDim = [[123],[456],[789]] =
1 2 3
4 5 6
7 8 9
Image Credit: www.rafainspirationhomedecor.com
Playing With Lists: Append
• Add teacher: Dr. Jim Anderson
• Add year: 2015
Note: Python lists can contain data of mixed types. You can mix strings with
numbers within the same Python list. You can mix more than just strings and
numbers -- you can store data of any type in a single list.
prerequisites = [“COP 2271c”, “Introduction to Computation and Programming”, 3]
Image Credit: ClipArt Best
Playing With Lists: Pop
• Allows you to remove the item that is at the
end of a list
prereqs[course].pop()
CHM 2045 , Chemistry 1 , 3 , Dr. Anderson , 2015X
Image Credit: blog.poolproducts.com
Playing With Lists: Remove
• Allows you to specify which list item you want
to remove no matter where in the list it is
located
prereqs[course].remove("Dr. Anderson")
CHM 2045 , Chemistry 1 , 3 , Dr. AndersonX
Image Credit: www.pinterest.com
Playing With Lists: Insert
• Allows you to add an item to a list in a
specified location on the list
prereqs[course].insert(2,"Really Hard")
CHM 2045 , Chemistry 1 , Really Hard , 3
Image Credit: ekskavatör
Playing With Lists: Extend
• Allows multiple list items to be added to an
existing list
prereqs[course].extend(["Dr. Anderson", "2015"])
CHM 2045 , Chemistry 1 , Really Hard , 3 , Dr. Anderson , 2015
Image Credit: www.clipartpanda.com
How To Access A List
• A list is a sequence of elements, each of which has an
integer position or index.
• To access a list element, you specify which index you
want to use.
• That is done with the subscript operator ([] ) in the
same way that you access individual characters in a
string.
• For example:
print(values[5]) # Prints the element at index 5
Image Credit: imgkid.com
Appending Elements
• Start with an empty list
goodFood=[]
• A new element can be appended to the end of the list with the append
method:
goodFood.append(“burgers”)
• The size, or length, of the list increases after each call to the append
method. Any number of elements can be added to a list:
goodFood.append(“ice cream”)
goodFood.append(“hotdog”)
goodFood.append(“cake”)
Image Credit: www.pinterest.com
Inserting an Element
• Sometimes, however, the order is important and a new element has to be
inserted at a specific position in the list. For example, given this list:
friends = ["Harry", "Emily", "Bob", "Cari"]
suppose we want to insert the string "Cindy" into the list following the fist
element, which contains the string "Harry". The statement:
friends.insert(1, "Cindy")
achieves this task
• The index at which the new element is to be inserted must be between 0 and the
number of elements currently in the list. For example, in a list of length 5, valid
index values for the insertion are 0, 1, 2, 3, 4, and 5. The element is inserted
before the element at the given index, except when the index is equal to the
number of elements in the list. Then it is appended after the last element:
friends.insert(5, "Bill")
This is the same as if we had used the append method.
Image Credit: www.crazywebsite.com
Finding An Element
• If you simply want to know whether an element is present in a list, use the in
operator:
if "Cindy" in friends :
print("She's a friend")
• Often, you want to know the position at which an element occurs. The index
method yields the index of the fist match. For example,
friends = ["Harry", "Emily", "Bob", "Cari", "Emily"]
n = friends.index("Emily") # Sets n to 1
• If a value occurs more than once, you may want to find the position of all
occurrences. You can call the index method and specify a starting position for the
search. Here, we start the search after the index of the previous match:
n2 = friends.index("Emily", n + 1) # Sets n2 to 4
Image Credit: www.theclipartdirectory.com
Removing an Element
• Pop
– The pop method removes the element at a given position. For example, suppose we start with the
list
friends = ["Harry","Cindy","Emily","Bob","Cari","Bill"]
To remove the element at index position 1 ("Cindy") in the friends list, you use the command:
friends.pop(1)
If you call the pop method without an argument, it removes and returns the last element of the list.
For example, friends.pop() removes "Bill".
• Remove
– The remove method removes an element by value instead of by position.
friends.remove("Cari")
Image Credit: www.clipartpanda.com
Let’s Talk About: Tables
• It often happens that you want to store
collections of values that have a two-
dimensional tabular layout.
• Such data sets commonly occur in financial and
scientific applications.
• An arrangement consisting of rows and
columns of values is called a table, or a matrix.
Image Credit: www.rafainspirationhomedecor.com
How To Create Tables
• Python does not have a data type for creating
tables.
• A two-dimensional tabular structure can be
created using Python lists.
• A table is simply a list in which each element is
itself another list
Accessing Elements Of A Table
• To access a particular element in the table,
you need to specify two index values in
separate brackets to select the row and
column, respectively.
medalCount = counts[3][1] = 0
That’s All!

More Related Content

What's hot (20)

PPT
AOSPINE2010TLIF
Masato Tanaka
 
PPTX
Cauda Equina syndrome
Spiro Antoniades
 
PDF
Acl graft fixation options
orthoprinciples
 
PPT
Selective fusion for idiopathic scoliosis review by dr.shashidhar b k
Dr. Shashidhar B K
 
PPTX
Cauda equina syndrome
MUHAMMAD HOSSAIN
 
PPTX
Legg calve perthes disease
Bijay Mehta
 
PPTX
The Antero-lateral ligament "the whole story"
Zagazig University
 
PPTX
Reverse shoulder biomechanics
Moby Parsons
 
PPTX
Dr. yt reddy distal radius fractures modified
varuntandra
 
PPTX
Adolescent idiopathic scoliosis patient examination
Modar Alshaowa
 
PPTX
Keinbock disease
sukesh a n
 
DOCX
Anatomy of hip joint (1)
Sibasis Pattanayak
 
PPTX
Meniscus Meniscal Root Ligament Lesions, MRI of PMMRL tears posterior horn of...
aliahmadi9
 
PPT
Arthroscopic cuff repair
orthoprince
 
PPTX
Discoid Meniscus
Dr Nirav Mungalpara
 
PPTX
PRE OPERATIVE TEMPLATING IN TOTAL HIP ARTHROPLASTY
Yeshwanth Nandimandalam
 
PPTX
2017 upto date osteoprosis
qasimsamejo
 
PPT
Forearm instability
Bahaa Kornah
 
PPTX
Lecture 3 shah radiology in foot and ankle
Selene G. Parekh, MD, MBA
 
PDF
Ao artìculo
Gabriel Trujillo
 
AOSPINE2010TLIF
Masato Tanaka
 
Cauda Equina syndrome
Spiro Antoniades
 
Acl graft fixation options
orthoprinciples
 
Selective fusion for idiopathic scoliosis review by dr.shashidhar b k
Dr. Shashidhar B K
 
Cauda equina syndrome
MUHAMMAD HOSSAIN
 
Legg calve perthes disease
Bijay Mehta
 
The Antero-lateral ligament "the whole story"
Zagazig University
 
Reverse shoulder biomechanics
Moby Parsons
 
Dr. yt reddy distal radius fractures modified
varuntandra
 
Adolescent idiopathic scoliosis patient examination
Modar Alshaowa
 
Keinbock disease
sukesh a n
 
Anatomy of hip joint (1)
Sibasis Pattanayak
 
Meniscus Meniscal Root Ligament Lesions, MRI of PMMRL tears posterior horn of...
aliahmadi9
 
Arthroscopic cuff repair
orthoprince
 
Discoid Meniscus
Dr Nirav Mungalpara
 
PRE OPERATIVE TEMPLATING IN TOTAL HIP ARTHROPLASTY
Yeshwanth Nandimandalam
 
2017 upto date osteoprosis
qasimsamejo
 
Forearm instability
Bahaa Kornah
 
Lecture 3 shah radiology in foot and ankle
Selene G. Parekh, MD, MBA
 
Ao artìculo
Gabriel Trujillo
 

Viewers also liked (10)

ODP
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland
 
PPT
Python Introduction
Mohammad Javad Beheshtian
 
PDF
Lesson1 python an introduction
Arulalan T
 
PDF
Introduction to python
Yi-Fan Chu
 
PDF
Python Intro
Tim Penhey
 
PPTX
Python PPT
Edureka!
 
PPTX
Introduction to python for Beginners
Sujith Kumar
 
PPTX
Python in the Hadoop Ecosystem (Rock Health presentation)
Uri Laserson
 
ODP
Python Presentation
Narendra Sisodiya
 
PPT
Introduction to Python
Nowell Strite
 
Python Ireland Feb '11 Talks: Introduction to Python
Python Ireland
 
Python Introduction
Mohammad Javad Beheshtian
 
Lesson1 python an introduction
Arulalan T
 
Introduction to python
Yi-Fan Chu
 
Python Intro
Tim Penhey
 
Python PPT
Edureka!
 
Introduction to python for Beginners
Sujith Kumar
 
Python in the Hadoop Ecosystem (Rock Health presentation)
Uri Laserson
 
Python Presentation
Narendra Sisodiya
 
Introduction to Python
Nowell Strite
 
Ad

Similar to An Introduction To Python - Python Midterm Review (20)

PPTX
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
PPTX
An Introduction To Python - Variables, Math
Blue Elephant Consulting
 
PPT
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
sakchaisengsui
 
PPTX
Programming with python
sarogarage
 
PDF
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
rohithzach
 
PPTX
lecture 2.pptx
Anonymous9etQKwW
 
PDF
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
PPTX
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
PPTX
03 Variables - Chang.pptx
Dileep804402
 
PPTX
Python.pptx
EliasPetros
 
PPTX
Review old Pygame made using python programming.pptx
ithepacer
 
PPTX
Python Basics by Akanksha Bali
Akanksha Bali
 
PPTX
MODULE. .pptx
Alpha337901
 
PDF
introduction to python programming course 2
FarhadMohammadRezaHa
 
PPTX
Learning to code with Python! (MVA).pptx
JoshuaJoseph70
 
PPTX
Learning to code with Python! (Microsoft Virtual Academy).pptx
JoshuaJoseph70
 
PPTX
Python.pptx
AKANSHAMITTAL2K21AFI
 
PDF
python.pdf
BurugollaRavi1
 
PDF
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
PDF
python 34💭.pdf
AkashdeepBhattacharj1
 
PPT_1_9102501a-a7a1-493e-818f-cf699918bbf6.pptx
myatminsoe180
 
An Introduction To Python - Variables, Math
Blue Elephant Consulting
 
PythonCourse_02_Expressions.ppt Python introduction turorial for beginner.
sakchaisengsui
 
Programming with python
sarogarage
 
python2oxhvoudhuSGFsughusgdogusuosFU.pdf
rohithzach
 
lecture 2.pptx
Anonymous9etQKwW
 
03-Variables, Expressions and Statements (1).pdf
MirHazarKhan1
 
Pythonlearn-02-Expressions123AdvanceLevel.pptx
AninditaSarkarNaha
 
03 Variables - Chang.pptx
Dileep804402
 
Python.pptx
EliasPetros
 
Review old Pygame made using python programming.pptx
ithepacer
 
Python Basics by Akanksha Bali
Akanksha Bali
 
MODULE. .pptx
Alpha337901
 
introduction to python programming course 2
FarhadMohammadRezaHa
 
Learning to code with Python! (MVA).pptx
JoshuaJoseph70
 
Learning to code with Python! (Microsoft Virtual Academy).pptx
JoshuaJoseph70
 
python.pdf
BurugollaRavi1
 
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python 34💭.pdf
AkashdeepBhattacharj1
 
Ad

Recently uploaded (20)

PDF
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
PDF
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
PPTX
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
PPTX
SD_GMRC5_Session 6AB_Dulog Pedagohikal at Pagtataya (1).pptx
NickeyArguelles
 
PPTX
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
PDF
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
PPTX
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PPTX
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PPTX
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
PPTX
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
PDF
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
PDF
I3PM Case study smart parking 2025 with uptoIP® and ABP
MIPLM
 
PPTX
Different types of inheritance in odoo 18
Celine George
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
AI-assisted IP-Design lecture from the MIPLM 2025
MIPLM
 
PPTX
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
PPTX
Navigating English Key Stage 2 lerning needs.pptx
JaysonClosa3
 
DIGESTION OF CARBOHYDRATES ,PROTEINS AND LIPIDS
raviralanaresh2
 
Lean IP - Lecture by Dr Oliver Baldus at the MIPLM 2025
MIPLM
 
Natural Language processing using nltk.pptx
Ramakrishna Reddy Bijjam
 
SD_GMRC5_Session 6AB_Dulog Pedagohikal at Pagtataya (1).pptx
NickeyArguelles
 
Ward Management: Patient Care, Personnel, Equipment, and Environment.pptx
PRADEEP ABOTHU
 
CAD25 Gbadago and Fafa Presentation Revised-Aston Business School, UK.pdf
Kweku Zurek
 
ENGlish 8 lesson presentation PowerPoint.pptx
marawehsvinetshe
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
Exploring Linear and Angular Quantities and Ergonomic Design.pptx
AngeliqueTolentinoDe
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
PLANNING A HOSPITAL AND NURSING UNIT.pptx
PRADEEP ABOTHU
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
TechSoup Microsoft Copilot Nonprofit Use Cases and Live Demo - 2025.06.25.pdf
TechSoup
 
I3PM Case study smart parking 2025 with uptoIP® and ABP
MIPLM
 
Different types of inheritance in odoo 18
Celine George
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
AI-assisted IP-Design lecture from the MIPLM 2025
MIPLM
 
Life and Career Skills Lesson 2.pptxProtective and Risk Factors of Late Adole...
ryangabrielcatalon40
 
Navigating English Key Stage 2 lerning needs.pptx
JaysonClosa3
 

An Introduction To Python - Python Midterm Review

  • 1. An Introduction To Software Development Using Python Spring Semester, 2015 Midterm Review
  • 2. What’s In Your Python Toolbox? print() math strings I/O IF/Else elif While For Lists
  • 3. A Closer Look At Our First Program • # My first Python program. – This is a comment – it’s for you, not the computer – Comments begin with # and are not statements. • print("Hello, World!") – displays a line of text, namely “Hello, World!”. – We call a function named print and pass it the information to be displayed. – A function is a collection of programming instructions that carry out a particular task. – It is part of the Python language.
  • 5. Let’s Talk About Variables… • Variables are reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. • Variables in Python consist of an alphanumeric name beginning in a letter or underscore. Variable names are case sensitive. • Python variables do not have to be explicitly declared to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. • The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. • Examples: counter = 100 miles = 1000.0 name = "John" Image Credit: ClipArt Best Python variable names can have unlimited length – but keep them short!
  • 6. Let’s Talk About Python Math! Normal Stuff Weird Stuff 5%2 = 1
  • 7. Modulo (%) Is Your Friend • A man has 113 cans of Coke. He also has a group of boxes that can hold 12 cans each. How many cans will he have left over once he’s loaded all of the boxes? • On a military base the clock on the wall says that the time is 23:00. What time of day is this? • My friend has 10,432 ping pong balls that he needs to put into storage. My car can transport 7,239 balls. How many will be left after I leave?
  • 8. What Comes First? Precedence Rules • The precedence rules you learned in algebra apply during the evaluation of arithmetic expressions in Python: – Exponentiation has the highest precedence and is evaluated first. – Unary negation is evaluated next, before multiplication, division, and remainder. – Multiplication, division, and remainder are evaluated before addition and subtraction. – Addition and subtraction are evaluated before assignment. – With two exceptions, operations of equal precedence are left associative, so they are evaluated from left to right. Exponentiation and assignment operations are right associative, so consecutive instances of these are evaluated from right to left. – You can use parentheses to change the order of evaluation • "PEMDAS", which is turned into the phrase "Please Excuse My Dear Aunt Sally". It stands for "Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction". 3**2 -5 2+3*4/6 sum = 2+3 2+3*4/6 sum = 3**2**5 (2+3)*4/5 Image Credit: www.pinterest.com
  • 9. Precedence Rules: Examples • Simplify 4 + 32 • Simplify 4 + (2 + 1)2 • Simplify 4 + [–1(–2 – 1)]2 • Simplify 4( –2/3 + 4/3) • Three people ate dinner at a restaurant and want to split the bill. The total is $35.27, and they want to leave a 15 percent tip. How much should each person pay? Image Credit: pixgood.com
  • 10. Not All Numbers Are Created Equal • Integers are the numbers you can easily count, like 1, 2, 3, as well as 0 and the negative numbers, like –1, –2, –3. • Decimal numbers (also called real numbers) are the numbers with a decimal point and some digits after it, like 1.25, 0.3752, and –101.2. • In computer programming, decimal numbers are also called floating-point numbers, or sometimes floats for short (or float for just one of them). This is because the decimal point “floats” around. You can have the number 0.00123456 or 12345.6 in a float. Image Credit: www.clipartpanda.com
  • 11. Mixed-Mode Arithmetic and Type Conversions • Performing calculations involving both integers and floating-point numbers is called mixed-mode arithmetic. • Conversions – Determine type: type() – Drop decimal: int() – Round up / down: round() – Change to decimal: float() – Change to string: str() Image Credit: personaltrainerbusinesssystems.com
  • 12. Cool Kid Stuff: Increment / Decrement / E-Notation • Incrementing: sum = sum + 1 – sum += 1 • Decrementing: sum = sum – 1 – sum -= 1 • E-Notation – 1,000,000 = 1 x 10**6 = 1e6 Image Credit: www.toonvectors.com
  • 13. Say Hello To Strings! • Your computer programs will have to process text in addition to numbers. • Text consists of characters: letters, numbers, punctuation, spaces, and so on. • A string is a sequence of characters. • Example: “John Smith” Image Credit: imgarcade.com
  • 14. How Do We Deal With Strings? • Strings can be stored in variables: answer = “a” • A string literal denotes a particular string: “Mississippi” • In Python, string literals are specified by enclosing a sequence of characters within a matching pair of either single or double quotes. “fire truck” or ‘fire truck’ Image Credit: imgarcade.com
  • 15. Strings and Characters • Strings are sequences of Unicode characters. • You can access the individual characters of a string based on their position within the string. • This position is called the index of the character. Image Credit: www.fontspace.com 0 1 2 3 4 First Last
  • 16. String Indexes • name = “TILEZ” • len(name) = 5 • name[0] = “T”, name[4] = “Z” 0 1 2 3 4
  • 17. All Characters Have Numbers • A character is stored internally as an integer value. The specific value used for a given character is based on its ASCII code (or Unicode code). • Python provides two functions related to character encodings. – The ord function returns the number used to represent a given character. ord(“A”) = 65 – The chr function returns the character associated with a given code. chr(65) = “A” Image Credit: www.clipartpanda.com
  • 18. Input and Output • When a program asks for user input, it should first print a message that tells the user which input is expected. Such a message is called a prompt. In Python, displaying a prompt and reading the keyboard input is combined in one operation. – first = input("Enter your first name: ") • The input function displays the string argument in the console window and places the cursor on the same line, immediately following the string. – Enter your first name: █ Image Credit: blogs.msdn.com
  • 19. Numerical Input • The input function can only obtain a string of text from the user. • To read an integer value, first use the input function to obtain the data as a string, then convert it to an integer using the int function. numBottles = input("Please enter the number of bottles: ") bottles = int(numBottles) bottlePrice = input("Enter price per bottle: ") price = float(bottlePrice) Image Credit: www.canstockphoto.com
  • 20. Formatted Output • To control how your output looks, you print a formatted string and then provide the values that are to be “plugged in”. • If the value on the right of the “%” is a string, then the % symbol becomes the string format operator. • The construct %10.2f is called a format specifier: it describes how a value should be formatted. – The 10 specifies the size of the field, the 2 specified the number of digits after the “.”. – The letter f at the end of the format specifier indicates that we are formatting a floating-point value. Use d for an integer value and s for a string;
  • 21. Formatted Output • To specify left justification for a string, add a minus sign before the string field width: title1 = "Quantity:“ title2 = "Price:" print("%-10s %10d" % (title1, 24)) print("%-10s %10.2f" % (title2, 17.29)) • The result is: Quantity: 24 Price: 17.29 Image Credit: www.theindianrepublic.com
  • 23. Say Hello To The “IF” Statement • In Python, an IF statement is used to implement a decision. • When a condition is fulfilled, one set of statements is executed. Otherwise, another set of statements is executed Image Credit: www.clipartpanda.com
  • 24. Syntax Of Python IF Statement
  • 25. Tabs • Blockstructured code has the property that nested statements are indented by one or more levels: if totalSales > 100.0 : discount = totalSales * 0.05 totalSales = totalSales − discount print("You received a discount of $%.2f" % discount) else : diff = 100.0 − totalSales if diff < 10.0 : print("purchase our item of the day & you can receive a 5% discount.") else : print("You need to spend $%.2f more to receive a 5% discount." % diff) Image Credit: www.clipartpanda.com
  • 26. Relational Operators Equality Testing Requires 2 “=“ Note: relational operators have a lower precedence than arithmetic operators
  • 28. What Is A “Nested Branch”? • It is often necessary to include an if statement inside another. Such an arrangement is called a nested set of statements. • Example: Is the club full? Arrive at the club Are you on the VIP list? Wait in car Go right in Wait in line Y Y N N
  • 29. Example of a “Nested Branch” if (peopleInClub < maxPeopleInClub) : if (youName == VIPListName) : goRightIn else : waitInLine else : waitInCar
  • 30. Problems With “Super Nesting” • Difficult to read • Shifted too far to the right due to indentation Image Credit: www.clipartbest.com
  • 31. A Better Way: elif If (classScore >=90) : print(“You got an A!”) elif (classScore >= 80) : print(“You did ok, you got a B!”) elif (classScore >=70) : print(“So-so, you got a C”) elif (classScore >= 60) : print(“Oh –oh, you got a D”) else : print(“Dang it, you got an F”) Image Credit: jghue.blogspot.com Note that you have to test the more specific conditions first.
  • 32. How Do You Do Things Over And Over Again? • In Python, loop statements repeatedly execute instructions until a goal has been reached. • In Python, the while statement implements such a repetition. It has the form: while condition : statement1 statement 2 • As long as the condition remains true, the statements inside the while statement are executed. Image Credit: etc.usf.edu Body Condition
  • 33. How Can I Loop For A Given Number Of Times? • You can use a while loop that is controlled by a counter: counter = 1 # Initialize the counter. while counter <= 10 : # Check the counter. print(counter) counter = counter + 1 # Update the loop variable Note: Some people call this loop count-controlled. Image Credit: www.dreamstime.com
  • 34. The For Statement The for loop can be used to iterate over the contents of any container, which is an object that contains or stores a collection of elements. Thus, a string is a container that stores the collection of characters in the string.
  • 35. What’s The Difference Between While Loops and For Loops? • In the for loop, the element variable is assigned stateName[0] , stateName[1] , and so on. • In the while loop, the index variable i is assigned 0, 1, and so on. Image Credit: www.clipartpanda.com
  • 36. The Range Function • Count-controlled loops that iterate over a range of integer values are very common. • To simplify the creation of such loops, Python provides the range function for generating a sequence of integers that can be used with the for loop. • The loop code: for i in range(1, 10) : # i = 1, 2, 3, ..., 9 print(i) prints the sequential values from 1 to 9. The range function generates a sequence of values based on its arguments. • The first argument of the range function is the first value in the sequence. • Values are included in the sequence while they are less than the second argument Image Credit: www.best-of-web.com
  • 37. You Can Do The Same Thing With While And For Loops for i in range(1, 10) : # i = 1, 2, 3, ..., 9 print(i) i = 1 while i < 10 : print(i) i = i + 1 Image Credit: www.rgbstock.com Note that the ending value (the second argument to the range function) is not included in the sequence, so the equivalent while loop stops before reaching that value, too.
  • 38. Stepping Out… • By default, the range function creates the sequence in steps of 1. This can be changed by including a step value as the third argument to the function: for i in range(1, 10, 2) : # i = 1, 3, 5, ..., 9 print(i) Image Credit: megmedina.com
  • 39. Review: The Many Different Forms Of A Range
  • 40. Secret Form Of print Statement • Python provides a special form of the print function that prevents it from starting a new line after its arguments are displayed. print(value1, value2, end="") • By including end="" as the last argument to the first print function, we indicate that an empty string is to be printed after the last argument is printed instead of starting a new line. • The output of the next print function starts on the same line where the previous one left off. Image Credit: www.clipartpanda.com
  • 41. 4 Steps To Creating A Python List 1. Convert each of the names into strings by surrounding the data with quotes. 2. Separate each of the list items from the next with a comma. 3. Surround the list of items with opening and closing square brackets. 4. Assign the list to an identifier (movies in the preceding code) using the assignment operator (=). “COP 2271c” “Introduction to Computation and Programming” 3 “COP 2271c”, “Introduction to Computation and Programming”, 3 [“COP 2271c”, “Introduction to Computation and Programming”, 3] prerequisites = [“COP 2271c”, “Introduction to Computation and Programming”, 3] COP 2271c Introduction to Computation and Programming 3 Image Credit: Clipart Panda
  • 42. How To Access A List • A list is a sequence of elements, each of which has an integer position or index. • To access a list element, you specify which index you want to use. • That is done with the subscript operator ([] ) in the same way that you access individual characters in a string. • For example: print(values[5]) # Prints the element at index 5 Image Credit: imgkid.com
  • 43. Access Your List Data Using The Square Bracket Notation print (prerequisites[0]) COP 2271c print (prerequisites[1]) Introduction to Computation and Programming print (prerequisites[2]) 3 Image Credit: Clipart Panda
  • 44. You Can Create Multidimensional Lists • Lists can hold data of mixed type. • But it gets even better than that: lists can hold collections of anything, including other lists. • Simply embed the inner list within the enclosing list as needed. multiDim = [[123],[456],[789]] = 1 2 3 4 5 6 7 8 9 Image Credit: www.rafainspirationhomedecor.com
  • 45. Playing With Lists: Append • Add teacher: Dr. Jim Anderson • Add year: 2015 Note: Python lists can contain data of mixed types. You can mix strings with numbers within the same Python list. You can mix more than just strings and numbers -- you can store data of any type in a single list. prerequisites = [“COP 2271c”, “Introduction to Computation and Programming”, 3] Image Credit: ClipArt Best
  • 46. Playing With Lists: Pop • Allows you to remove the item that is at the end of a list prereqs[course].pop() CHM 2045 , Chemistry 1 , 3 , Dr. Anderson , 2015X Image Credit: blog.poolproducts.com
  • 47. Playing With Lists: Remove • Allows you to specify which list item you want to remove no matter where in the list it is located prereqs[course].remove("Dr. Anderson") CHM 2045 , Chemistry 1 , 3 , Dr. AndersonX Image Credit: www.pinterest.com
  • 48. Playing With Lists: Insert • Allows you to add an item to a list in a specified location on the list prereqs[course].insert(2,"Really Hard") CHM 2045 , Chemistry 1 , Really Hard , 3 Image Credit: ekskavatör
  • 49. Playing With Lists: Extend • Allows multiple list items to be added to an existing list prereqs[course].extend(["Dr. Anderson", "2015"]) CHM 2045 , Chemistry 1 , Really Hard , 3 , Dr. Anderson , 2015 Image Credit: www.clipartpanda.com
  • 50. How To Access A List • A list is a sequence of elements, each of which has an integer position or index. • To access a list element, you specify which index you want to use. • That is done with the subscript operator ([] ) in the same way that you access individual characters in a string. • For example: print(values[5]) # Prints the element at index 5 Image Credit: imgkid.com
  • 51. Appending Elements • Start with an empty list goodFood=[] • A new element can be appended to the end of the list with the append method: goodFood.append(“burgers”) • The size, or length, of the list increases after each call to the append method. Any number of elements can be added to a list: goodFood.append(“ice cream”) goodFood.append(“hotdog”) goodFood.append(“cake”) Image Credit: www.pinterest.com
  • 52. Inserting an Element • Sometimes, however, the order is important and a new element has to be inserted at a specific position in the list. For example, given this list: friends = ["Harry", "Emily", "Bob", "Cari"] suppose we want to insert the string "Cindy" into the list following the fist element, which contains the string "Harry". The statement: friends.insert(1, "Cindy") achieves this task • The index at which the new element is to be inserted must be between 0 and the number of elements currently in the list. For example, in a list of length 5, valid index values for the insertion are 0, 1, 2, 3, 4, and 5. The element is inserted before the element at the given index, except when the index is equal to the number of elements in the list. Then it is appended after the last element: friends.insert(5, "Bill") This is the same as if we had used the append method. Image Credit: www.crazywebsite.com
  • 53. Finding An Element • If you simply want to know whether an element is present in a list, use the in operator: if "Cindy" in friends : print("She's a friend") • Often, you want to know the position at which an element occurs. The index method yields the index of the fist match. For example, friends = ["Harry", "Emily", "Bob", "Cari", "Emily"] n = friends.index("Emily") # Sets n to 1 • If a value occurs more than once, you may want to find the position of all occurrences. You can call the index method and specify a starting position for the search. Here, we start the search after the index of the previous match: n2 = friends.index("Emily", n + 1) # Sets n2 to 4 Image Credit: www.theclipartdirectory.com
  • 54. Removing an Element • Pop – The pop method removes the element at a given position. For example, suppose we start with the list friends = ["Harry","Cindy","Emily","Bob","Cari","Bill"] To remove the element at index position 1 ("Cindy") in the friends list, you use the command: friends.pop(1) If you call the pop method without an argument, it removes and returns the last element of the list. For example, friends.pop() removes "Bill". • Remove – The remove method removes an element by value instead of by position. friends.remove("Cari") Image Credit: www.clipartpanda.com
  • 55. Let’s Talk About: Tables • It often happens that you want to store collections of values that have a two- dimensional tabular layout. • Such data sets commonly occur in financial and scientific applications. • An arrangement consisting of rows and columns of values is called a table, or a matrix. Image Credit: www.rafainspirationhomedecor.com
  • 56. How To Create Tables • Python does not have a data type for creating tables. • A two-dimensional tabular structure can be created using Python lists. • A table is simply a list in which each element is itself another list
  • 57. Accessing Elements Of A Table • To access a particular element in the table, you need to specify two index values in separate brackets to select the row and column, respectively. medalCount = counts[3][1] = 0

Editor's Notes

  • #2: New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.