0% found this document useful (0 votes)
213 views91 pages

Midterm CS306- Introduction to Python

The document provides an overview of computers, programming languages, and the Python programming environment. It covers the basics of programming, including syntax, variables, operators, control structures, functions, and recursion, along with practical examples. Additionally, it highlights Python's popularity and ease of use, making it suitable for various applications, including web development and data science.

Uploaded by

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

Midterm CS306- Introduction to Python

The document provides an overview of computers, programming languages, and the Python programming environment. It covers the basics of programming, including syntax, variables, operators, control structures, functions, and recursion, along with practical examples. Additionally, it highlights Python's popularity and ease of use, making it suitable for various applications, including web development and data science.

Uploaded by

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

Introduction

• What are computers?


• Talking about general purpose, binary, digital computers

• Dumb machines that need to be told what to do

• How do we tell them what to do?


• By giving them instructions

• How do we communicate with them?

• Use special languages such as Assembly, FORTRAN, C, Python etc.

• What is a program?
• Precise set of instructions to solve a problems

• Art of writing these instructions is called programming


Programming Languages

• How are instructions written?


• Human readable form

• What are programming languages?


• Specific languages developed to write computer instructions

• Some are machine like languages such as assembly or low level languages

• Others are human readable or high level languages such as FORTRAN, COBOL, C, C++, Python

• Compiled vs interpreted languages


• How do we transform a human readable program into machine understandable

• Compilation vs Interpretation
• Example: Need to cook meat to eat – compiling, Salad vegetables can be eaten as is - interpreting

• Language for the course: Python


Why Python is popular
• Easy to learn: straightforward syntax and very readable
• Versatile: can be used for a wide variety of applications, including web
development, data analysis, and scientific computing.
• Automation: powerful tool for automating repetitive tasks, such as file
handling, web scraping, and software testing.
• Machine learning and AI support: popular choice for machine learning,
artificial intelligence, and data science.
• Active community: Python has a large and supportive development
community.
• Vast ecosystem: Python has a large ecosystem of libraries for data
processing, machine learning, data science, and more.
Setting up the Python environment on your
computer
• Go to the official Python website (https://www.python.org/)

• Select the latest version of Python

• Select the "Windows installer" option

• Click "Download"

• Run the installer

• Follow the on-screen instructions

• Verify the installation by opening a command prompt and typing python -V (or py -V)

• Run Python and display some interactive commands and results


Setting up VS Code as the preferred editor

• Go to the official Visual Studio Code site: https://code.visualstudio.com/

• Locate the latest version of VS Code for your operating system

• Download the installer as an .exe file.

• Install the downloaded file:

• Run the installer and click Next until you reach Finish.

• Choose support for Python when prompted


Our first Python program
1. Open VS Code
2. Type the code
Print(“Hello World”)

3. Save as a .py file


4. Run the program highlighting the output

• Using the Python CLI when needed (will be used in operators module etc.)
Programming Basics
• To design a program properly

1. Analyze the problem


2. Express its essence, with examples
3. Formulate statements precisely
4. Evaluate, test and revise if necessary
5. Pay attention to detail
Example program:

• Find the weight of metal required to make an annular ring with


inner and outer radii 2 cm and 5 cm. The metal sheet has a
grammage of 10 gms/cm2. Assume pi=3.14

• Walk through analysis, variables, precision, testing etc. (with


diagrams)
r=5cm

• r=2cm
The program
• Find area of larger circle:
• A1 = 3.14 * 5 * 5
• Find area of smaller circle:
• A2 = 3.14 * 2 * 2
• Find area of metal sheet to make the ring
• A3 = A1 – A2
• Find the weight of the ring:
• W = A3 * 10
• Answer W is in gms
Writing this program in Python (screen rec.)
# Find area of larger circle:
A1 = 3.14 * 5 * 5
# Find area of smaller circle:
A2 = 3.14 * 2 * 2
# Find area of metal sheet to make the ring
A3 = A1 - A2
# Find the weight of the ring:
W = A3 * 10
# Answer W is in gms
print(“The weight of the metal ring is: “, W, “ grams.”)
Python Syntax
• Set of rules that define how to write Python programs
• Readable: Uses English keywords and indentation
• No punctuation
• Case sensitive
• Reduces errors (missing braces etc.)
• Focuses on logic rather that syntax rules
Code Blocks and Comments
• Uses indentation to define code blocks
• A colon (:) starts a block
• All lines in a block should have the same indentation
• Use spaces or a tab as indentation
• Any number of spaces, but consistently in a single block
Comments
• Comments are indicated by a sharp sign (#)
• Stand-alone or inline comments are both allowed

• The end of a statement is marked by the end of the line


Basic Communications
• Print function
• Used for output
• Overloaded for different datatypes so it knows how to handle them
• (more on print statement later)

• Input function
• Returns a string (always)
• Can be used to prompt for user input
Variables
• What are variables
• Variables created when value assigned; no declaration
• Variables can change types through a new assignment
• The type of a variable can be forced by casting the RHS
• The simple assignment operator (=)
Variable Naming Conventions
• 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)
• A variable name cannot be any of the Python keywords.
• Many values can be assigned to multiple variables: (bad idea)
• x, y, z = 10, "Banana", "Cherry"
Variable Data Types
• str
• int, float, complex
• list, tuple, dict
• set, frozenset
• bool
• bytes, bytearray, memoryview
• NoneType
Operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic operators
Addition +
Subtraction -
Multiplication *
Division /

Floor Division //

Modulus %

Exponentiation **
Assignment operators
=
+=
-=
*=
/=
//=
%=
**=
Expressions
• A combination of operators and operands that is interpreted to
produce another value

• E.g.
c = a+b
Comparison operators

• Equals: a == b

• Not Equals: a != b

• Less than: a < b

• Less than or equal to: a <= b

• Greater than: a > b

• Greater than or equal to: a >= b


The if Statement
• Syntax:
if (condition):
statement(s)
elif (some other condition):
statements(s)
else:
statements
Putting a few concepts together

• Solving a quadratic equation:

ax² + bx + c = 0 a≠ 0

• Roots are
x = [-b±√(b2-4ac)]/2a
Logical Operators
and
or
not
• Usually combined with comparison operators

• and all expressions evaluate to True, then result is True


• or any expression evaluates to True then result is True
• not inverts the value of a logical expression
and Truth Table
C = A and B
1 = True
0 = False
A B C

0 0 0

0 1 0

1 0 0

1 1 1
or Truth Table
C = A or B
1 = True
0 = False
A B C

0 0 0

0 1 1

1 0 1
C
1 1 1
not Truth Table
C = not A
1 = True
0 = False
A C

0 1

1 0
Example using logical operators

Write a Python program that takes a user’s age as input and then
categorizes the person as
• A 'Child’ (age< 13),
• A 'Teen' (13-19),
• An 'Adult' (20-59),
• A 'Senior' (60 and above)
using only if-else statements (no elif allowed).
Flow Charts
• A technique to analyze problems without writing code

• We will use a technique called “Structured Flow Charts”

• Originally devised by DEC engineer

• Use very few symbols and indent only left to right


Flow Charts

• Start / Stop symbol

• Process symbol

• Decision symbol

• Continuation symbol
Flow Charts – Simple sequential problem
Start

Process

Process

Process

Stop
Start
If statement If
Indentation level
Condition?

True

Process A

False

Process B

Stop
Nested If Indentation Level 1

Indentation Level 2

Stop
Loops
• Used whenever we need to repeat a task

• Two broad varieties

• “while” loops – run while some condition is true

• “for” loops – run for a specific number of times


While loop
• Syntax:
while(some condition is true):
Perform some instructions

optional: break
continue
else

❖Loop runs as long as condition is true


❖Must be careful to avoid infinite loops
While loop
Start

while
False
Condition? Exit

True

Process

Stop
The range function
• Syntax:
range(number)
range(start, stop)
range(start, stop, step)
where all arguments are integers

• Returns a “range” object that can be used to iterate through


• Most useful in for-loops
The membership operator
• Syntax:
i in range(number)
(range could be any other group like list etc.)
• Returns True if i is in the range
• Returns False otherwise

• Useful in for-loops
For loop
• Used for iterating over a sequence
• E.g. a range, a list, a tuple, a dictionary, a set, a string
• Syntax:
for x in <some sequence>:
Perform some instructions

optional: break
continue
else
Loop runs through all values in the sequence (zero or more)
For loop
Start

Init loop var

for
False
Var in sequence? Exit

True

Process &
Next var

Stop
Optional loop statements
continue
forces next iteration of the loop skipping any remaining
statements

else
executed after normal termination of the loop

break
exits loop immediately not executing any “else” statements
For loop
• Used for iterating over a sequence
• E.g. a range, a list, a tuple, a dictionary, a set, a string
• Syntax:
for x in <some sequence>:
Perform some instructions

optional: break
continue
else
Loop runs through all values in the sequence (zero or more)
For loop
Start

Init loop var

for
False
Var in sequence? Exit

True

Process &
Next var

Stop
Optional loop statements
continue
forces next iteration of the loop skipping any remaining
statements

else
executed after normal termination of the loop

break
exits loop immediately not executing any “else” statements
Some simple loop examples
• Manual computation vs loops
• Counting and Sums

• Sum of first n integers

• How many numbers between a and b are exactly divisible by c?


(Using debugger to observe execution)

• What is the sum of integers between a and b inclusive?

• What is the sum of even numbers between a and b inclusive?


Functions

• Code blocks used to execute a certain defined process


• Used to break long complex code into easily understood units
• Most useful when the same code block is to be used repeatedly
Functions – Contd.
• Defined using the “def” keyword
• Parentheses must follow the name of the function, with or without
arguments
• Called by giving the name of the function followed by parentheses,
again, with or without arguments
• Can accept arguments (one or more) and return result(s)
• Functions only run when called
• Use a “return” statement to return value(s)
Functions – Contd.
• Number of arguments used to call must match the number of parameters
defined in the function and be in the correct order
• Alternately, use key=value syntax in calling args, then order does not matter.
However, key MUST be defined in the function
• A parameter may be given a default value in the function’s def statement.
This value is used if none provided in the calling statement. All parms
following the one with default value, MUST have default values defined
• Any data type may be passed to a function and it will be treated as the same
type inside the function (e.g. List, etc.)
• Multiple values can be returned as a tuple, a list, a dictionary, a set etc.
Functions – Contd.
• If function uses * before parameter, then it may be called with a
variable number of args and parms will be accessed by indexing
• Function then processes the parms as received
• If number of key values is not known, use ** before parameter
and function will decipher accordingly by using a dictionary
method
Recursion
• When a function calls itself directly or indirectly
• Used when a task can be divided into identical sub-tasks
• Basic structure of a recursive function:
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Recursion
• Examples:
• Sum by recursion
• Factorial by recursion
• Fibonacci series by recursion
Functions – Contd.
• Number of arguments used to call must match the number of parameters
defined in the function and be in the correct order
• Alternately, use key=value syntax in calling args, then order does not matter.
However, key MUST be defined in the function
• A parameter may be given a default value in the function’s def statement.
This value is used if none provided in the calling statement. All parms
following the one with default value, MUST have default values defined
• Any data type may be passed to a function and it will be treated as the same
type inside the function (e.g. List, etc.)
• Multiple values can be returned as a tuple, a list, a dictionary, a set etc.
Functions – Contd.
• Number of arguments used to call must match the number of parameters
defined in the function and be in the correct order
• Alternately, use key=value syntax in calling args, then order does not matter.
However, key MUST be defined in the function
• A parameter may be given a default value in the function’s def statement.
This value is used if none provided in the calling statement. All parms
following the one with default value, MUST have default values defined
• Any data type may be passed to a function and it will be treated as the same
type inside the function (e.g. List, etc.)
• Multiple values can be returned as a tuple, a list, a dictionary, a set etc.
Recursion
• When a function calls itself directly or indirectly
• Used when a task can be divided into identical sub-tasks
• Basic structure of a recursive function:
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Strings
• Defined using single or double quotes
• We can put any character(s) within the quotes
• If defined using “ we can include ‘ within the string and vice versa
• String variables are strings assigned to a variable
• Multi-line strings are enclosed in triple quotes
• Strings are immutable

• We use the print() function to display a string literal or variable


Python functions applicable to strings
• type() applicable to all Python data types, including strings
• str() create a string object
• len() returns the length of a string
Strings as arrays
• Strings are arrays of characters
• A single character is a string of length 1
• We can index through a string using [] starting at base 0
• We can extract a substring using the str[start:end] technique
• Since strings are arrays, we can loop through a string using a for
loop and a membership operator
• Strings are immutable
Escape sequences
• Used when we need a special character to be part of a string

\n \t \r \f
\’ \”
\\
\nnn octal value
\xnn hexadecimal value
String methods (functions)
• Conversion functions:
• Syntax: string.function() returns a new string

capitalize() first character of string to uppercase, rest to lower

casefold() converts string to lowercase (ascii & non-ascii)


lower() converts string to lowercase

title() converts first character of each word to upper case


upper() converts string to uppercase
swapcase() lower case becomes upper case and vice versa
String methods (contd.)
• Trimming leading and trailing white space:

lstrip()
rstrip()
strip()

• Optional argument: Set of characters in quotes that will be


stripped (default: space)
String methods (contd.)
• Justification:

ljust() left justified Left justified

rjust() right justified Right Justified

center() centered string Centered

width
• All require at least one argument (the
total width of the string) and an optional
fill character
String methods (contd.)
count() Returns number of times a string occurs in calling string

• Arg: string containing one or more characters (required).


• Empty string => all characters are counted
String methods (contd.)
find() Finds string and returns index (0 based)
• -1 if not found
• args: value, start, end
index() Same as find() but raises exception if not found

rfind() Finds last location of string and returns index (0 based)


• -1 if not found
• args: value, start, end
rindex() Same as rfind() but raises exception if not found
String methods (contd.)
replace()
• Returns a string where a certain substr is replaced with a new
substr
• args: oldvalue, newvalue, count (default = all occurrences)

expandtabs()
• Returns a string where tabs are replaced by number of spaces
specified
• args: number of spaces used to expand \t (default = 8)
String methods (contd.)
partition(argstring)
• Looks for first occurrence of argstring
• Returns a 3-element tuple containing
• The string preceding the argstring
• The argstring itself
• The string after the argstring
• If not found, returns a tuple containing the original string and two
empty strings
String methods (contd.)
rpartition(argstring)
• Looks for last occurrence of argstring
• Returns a 3-element tuple containing
• The string preceding the argstring
• The argstring itself
• The string after the argstring
• If not found, returns a tuple containing two empty strings and the
original string
String methods (contd.)
splitlines(keeplinebreaks)
• Breaks string into a LIST where each line is a list item
• Arg=True => keep linebreaks. Default = False
split(separator,maxsplit)
• Breaks string into a LIST where each word is a list item
rsplit(separator,maxsplit)
• Starting from right, breaks string into a LIST

• separator defines list items (default = space). Maxsplit = no. of splits to


do. Number of list items = Maxsplit + 1. Default=all.
Special String methods
sep.join(iterable)
• Called using a separator string. Returns a string consisting of all
elements of the iterable (elements must be str), joined by
separator
Special String methods (contd.)
• f strings
f”string with {optional formatting} placeholders”

• Simple method to construct complicated strings for printing


• Formatting is mainly used with numeric and date types
• Very rich formatting options
f strings (contd.)
• f”string {var} string {var}….”
• Automatically transforms var to strings and concatenates

• Add = to print the name of the variable AND its value


• E.g. f”string {var=}” for debugging

• For numbers: {var:[width][.precision][type]}


• Where type=d or f (int or float). Precision specified only for float
f strings (contd.)
• Alignment:
• Right: {var:>[width]}
• Left: {var:<[width]}

• Padding:
• Pad right with char for width: {var:char>[width]}
• Pad left with char for width: {var:char<[width]}

• Rounding to n decimal places:


• {var:.nf}
Checking Substring with membership
• Substr in string
• Substr not in string
• Returns True or false

• String concatenation = addition of two strings


newstr = str1 + str2
Slicing
• Using indexing for slicing a string
newstring = oldstring[from:to] (ending index is NOT included)
newstring = oldstring[from:] (to the end)
newstring = oldstring[:to] (from the beginning, NOT inc to)
• Slicing from the end:
Last index is -1
Can index backwards
e.g. newstring = oldstring[-5:-1] (last index is NOT included)
Determining the type of a string
isalnum() True if alphanumeric string
isalpha() True if alphabetic string
isascii() True if ascii string
isdecimal() True if all characters are decimals
isdigit() True if all characters are digits
isnumeric() True if all characters are digits
isidentifier() True if can be the name of a variable
islower() True if all characters are lower case
isupper() True if all characters are uppercase
isprintable() True if all characters are printable
isspace() True if all characters are white space
istitle() True if string is title case
Lists
• One of four Python data types used to store collections
• (Others are tuples, sets, dictionaries)
• Created by using []
• Can contain any type(s) of data – mixed items allowed
• May also be created using list() constructor (arg=iterable)
• Allow duplicate members.
Lists
• Are ordered and changeable.
• Iterating through lists
• Can use the “for” and “while” loops
• Any element can be changed (type is irrelevant)
• Applicable Python functions: type(), len(), list()
Lists
• Can use range of indices
• Like strings, indices go from 0 to len(list) – 1
• Last element has index = -1
• Negative indexing is permitted

• Behavior is exactly like strings


Checking Substring with membership
• Substr in string
• Substr not in string
• Returns True or false

• String concatenation = addition of two strings


newstr = str1 + str2
Slicing
• Using indexing for slicing a string
newstring = oldstring[from:to] (ending index is NOT included)
newstring = oldstring[from:] (to the end)
newstring = oldstring[:to] (from the beginning, NOT inc to)
• Slicing from the end:
Last index is -1
Can index backwards
e.g. newstring = oldstring[-5:-1] (last index is NOT included)
Determining the type of a string
isalnum() True if alphanumeric string
isalpha() True if alphabetic string
isascii() True if ascii string
isdecimal() True if all characters are decimals
isdigit() True if all characters are digits
isnumeric() True if all characters are digits
isidentifier() True if can be the name of a variable
islower() True if all characters are lower case
isupper() True if all characters are uppercase
isprintable() True if all characters are printable
isspace() True if all characters are white space
istitle() True if string is title case
Lists
• One of four Python data types used to store collections
• (Others are tuples, sets, dictionaries)
• Created by using []
• Can contain any type(s) of data – mixed items allowed
• May also be created using list() constructor (arg=iterable)
• Allow duplicate members.
Lists
• Are ordered and changeable.
• Iterating through lists
• Can use the “for” and “while” loops
• Any element can be changed (type is irrelevant)
• Applicable Python functions: type(), len(), list()
Lists
• Can use range of indices
• Like strings, indices go from 0 to len(list) – 1
• Last element has index = -1
• Negative indexing is permitted

• Behavior is exactly like strings


Lists
• Inserting / changing list elements
• Mutable – unlike strings

• May replace, insert or remove elements by using indexing

• Lists expand and contract according to original and replacement


items
List methods
• Adding elements and extending lists

insert(position, value)
append(value)
extend(iterable) iterable = any Python iterable
List methods
• Deleting elements
remove(value)
pop(optional index else last)
clear()

del list[index]
del list
List comprehension
• Shortcut for creating lists based on condition

newlist = [expression for item in iterable if condition == True]

• Very powerful construct


List sorting
• Lists can be sorted using

sort()
sort(reverse = True)
sort(key = function)
Copying lists
• List2 = list1 does not work!
• Simply creates a reference to the original list

• Need to do a deep copy


• Alternatives are:
copy() method
list() constructor method based on any iterable
using the slice operator [:] which fools the direct copy

You might also like