You are on page 1of 179

PYTHON PROGRAMMING FOR ABSOLUTE

BEGINNERS: LEARN PYTHON IN A WEEK


By Andreas Exadaktylos
Variables and Simple Data Types Making your
Operators Program Interactive

Advanced Methods of Statements and Lists - Tuples -


Lists & Dictionaries Loops Dictionaries - Sets

Functions Object-Oriented Modules and


Programming (OOP) Packages
Why Learn Python?

Python was created in 1990 by


Guido van Rossum
Welcome to Python!


Welcome to Python!
1. Python is more straightforward than other programming languages
and ideal for beginners. Most programs require considerably fewer
lines of code to perform the same task compared to other languages
2. Python is an efficient language. Python’s syntax helps you write
“clean” code, easy to read, easy to debug, and easy to extend and
build upon.
3. Python has a wide range of use. You can make games, build web
applications, and solve business problems. Python is also used
heavily in scientific fields for academic research.
4. Python has a large number of third-party tools, such as Pyinstaller
that allow us to package our Python code into stand-alone
executable programs for operating systems like Windows and Mac
OS
5. Python has a great Community. Having a supportive community is
critical in solving problems, especially in your first programming
steps.
List of the most common uses for Python
Designing mathematic, scientific, and
engineering applications

Python, provides access to some cool libraries that make it easier


to create math, scientific, and engineering applications.
The two most popular libraries are NumPy, and SciPy.
These libraries significantly reduce the time you spend writing
specialized code to perform common math, scientific, and
engineering tasks.

List of the most common uses for Python


Working with XML

The eXtensible Markup Language (XML) is the basis of most


data storage needs on the Internet and many desktop
applications today.

If you need to work with a Web service, the primary method for
exchanging information on the Internet (or any other XML
intensive application), Python is a great choice.

List of the most common uses for Python


Creating rough application examples

Developers often need to create a prototype, a rough example


of an application, before getting the resources to develop the
actual application.

Python emphasizes productivity, so you can use it to create


prototypes of an application quickly.

List of the most common uses for Python


Scripting browser-based applications

Even though JavaScript is probably the most popular language


used for browser-based application scripting, Python is a close
second.

Python offers functionality that JavaScript doesn’t provide, and


its high efficiency, makes it possible to create browser-based
applications faster.

List of the most common uses for Python


Python is used just about everywhere
❑ Netflix uses Python to make sure movies play (stream)
without stopping.

❑ Spotify music streaming service uses Python to send you


music.

❑ Activision, the video game company that created call of duty,


uses Python to build games, test, and analyze stuff.

❑ The popular Python web framework Django powers both


Instagram and Pinterest.

❑ LucasFilms’s award winning visual effects company,


Industrial Light & Magic, uses Python to make help make
their magic come to life.

List of the most common uses for Python


Python 2 and Python 3
IDLE-Your Coding Environment
Indentation
➢ Indent Region: Shift selected lines right by the indent width (the
default is four spaces).
➢ Dedent Region: Shift selected lines left by the indent width.
➢ Comment Out Region: Insert two hash in front of selected lines.
➢ Uncomment Region: Remove leading one hash or two hash from
selected lines.
➢ Tabify Region: Turn leading stretches of spaces into tabs. I
recommend using four space blocks to indent Python code
➢ Untabify Region: Turn all tabs into the correct number of spaces.
➢ Toggle Tabs: Open a dialog to switch between indenting with
spaces and tabs.
➢ New Indent Width: Open a dialog to change indent width. The
accepted default by the Python community is four spaces.
How to Customize Python IDLE
There are 5 areas of Python IDLE that
you can customize:

1. Fonts/Tabs
2. Highlights
3. Keys
4. General
5. Extensions
Hello World! - Writing our First Program
Hello World!
Adding Comments
COMMON REASONS TO USE COMMENTS
IN YOUR CODE
❑ Reminding yourself about what the code does, and why you
wrote it
❑ Telling others how to maintain your code
❑ Making your code accessible to other developers
❑ Listing ideas for future updates
❑ Maintaining a list of improvements, you’ve made
How to Find Help
TWO MAIN KINDS OF ERRORS

❑ A syntax error basically means you made a


punctuation mistake. These are the most
common errors. Get used to reading what you’ve
typed very closely and comparing it carefully to
what you should have typed.

❑ Logic errors occur where you’ve misunderstood


what you’re trying to do or what you’ve asked
Python to do. These errors can be difficult to spot
and more difficult to track down.
THE EASIEST WAYS TO GET HELP :

❑ By copying the error message into the Google search

❑ Try asking people directly in a web forum such as https://stackoverflow.com/


Stack Overflow

❑ Through the official Python documentation https://docs.python.org/3/

❑ www.pythontutor.com
Five (5) Beginner Tips for Learning python
Programming
Coding Every Day

❖ Little and often is better than one large chunk a week


❖ Set a timetable
❖ Be realistic about the time you have for this
❖ Solving small problems as time allows
Write It Out

❖ Writing out notes helps you to retain information


better than any other method
❖ Planning for programs with written notes can help
make the solution clearer
❖ It’s often easier to create visual representations when
working with paper and pencil
Go Interactive
Take Breaks

❖ Pomodoro Technique
❖ Timetable breaks into your schedule
❖ Sleep is important for memory formation
❖ Fresh eyes spot ‘obvious’ errors
Ask “Good” Questions

G: Give context on what you’re trying to do, clearly


describing the problem

I’m trying to use an f-


string with formatting
combined with a variable
Can’t print properly to give 6 total digits and
1 decimal place, but I
can’t find the right syntax
Ask “Good” Questions

O: Outline the things you’ve already tried to fix the issue

I’ve tried:
Tried everything print(f”{var}”)
print(f”{:03.1f var}”)
Ask “Good” Questions
O: Offer the best guess as to what the problem might be.
This helps the person who’s helping you not only to know
what you’re thinking, but also to know that you’ve done
some thinking on your own.

I can make the


formatting work using
old-style formatting , but I
No idea what’s wrong can’t see where to insert
the variable in the new
style
Ask “Good” Questions
D: Demo what’s happening—include the code, traceback
error message, or an explanation of the steps you’ve
executed that resulted in the error. This way, the person
helping does not have to try to recreate the issue.

var=34.6
print(“{:06.1f}”.format(var))
# this works, but it's not an f-
string
Variables
List of reserved keywords in Python 3.9

and except lambda with


as finally nonlocal while
assert false None yield
break for not
class from or
continue global pass
def if raise
del import return
elif in True
else is try
MOST COMMONLY USED METHODS OF
CONSTRUCTING A MULTI-WORD
VARIABLE NAME
❖ Camel Case: Second and subsequent words are
capitalized, to make word boundaries easier to see.
❖ Example: numberOfSales
❖ Pascal Case: Identical to Camel Case, except the first
word is also capitalized.
❖ Example: NumberOfSales
❖ Snake Case: Words are separated by underscores.
❖ Example: number_of_sales
Arithmetic Operators
Arithmetic operators in Python include:

❖ Addition
❖ Subtraction
❖ Multiplication
❖ Division
❖ Floor division (also called Integer Division)
❖ Modulo
❖ Exponentiation
❖ Unary Positive
❖ And Unary Negation
Comparison Operators
Logical and Chained Comparison Operators
Logical Operators
BASIC CONCEPTS RELATED TO BOOLEAN
LOGIC IN PYTHON

❖ Boolean is type of value that can be either True or False. In Python,


the Boolean type is bool, which is a subtype of int.
❖ Boolean values are the values True or False (with a capital T and F)
in Python.
❖ A Boolean variable is a variable that can be either True or False.
Boolean variables are commonly used as flags to indicate whether
specific conditions exist.
❖ Boolean or logical operators are AND (logical AND or conjunction),
OR (logical OR or disjunction), and NOT (logical NOT or negation).
The keywords and, or, and not , are the Python operators for these
operations.
Strings
STRING OPERATORS

A couple of operators that can be used on numeric


operands can be applied to strings as well
• The + Operator
• The * Operator

And a membership operator that can be used with


strings
• The in Operator
STRING OPERATORS

The + Operator
➢ Concatenates strings
➢ Returns a string consisting of the
operands joined together
STRING OPERATORS

The * Operator
➢ Creates multiple copies of a string
➢ Returns a string consisting of n
concatenated copies of a string
STRING OPERATORS

The in Operator
❖ A membership operator that can be used
with strings
❖ Returns True if the first operand is
contained within the second
❖ Returns False otherwise
❖ Also can be used as not in
BUILT-IN STRING FUNCTIONS
ESCAPE CHARACTERS

\' - Single Quote


\" - Double Quote
\\ - Backslash
\n - Newline
\r - Carriage Return
\t - Tab
\b - Backspace
\f - Form Feed
\v - Vertical Tab
\onn - Character with octal value xx
\xnn - Character with hex value nn
String Operators & Built-In Functions
ASCII
0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120

0 NUL BS DLE CAN space ( 0 8 @ H P X ` h p x

1 SOH HT DC1 EM ! ) 1 9 A I Q Y a i q y

2 STX LF DC2 SUB " * 2 : B J R Z b j r z

3 ETX VT DC3 ESC # + 3 ; C K S [ c k s {

4 EOT FF DC4 FS $ , 4 < D L T \ d l t |

5 ENQ CR NAK GS % - 5 = E M U ] e m u }

6 ACK SO SYN RS & . 6 > F N V ^ f n v ~

7 BEL SI ETB US ‘ / 7 ? G O W _ g o w DEL


Percentage String Formatting Examples
Code Segment: "%d" % x
Result: "12"
Explanation: The value stored in x is formatted as a decimal (base 10) integer.

Code Segment: "%f" % y


Result: "-2.75"
Explanation: The value stored in y is formatted as a floating-point number.

Code Segment: "%d and %f" % (x, y)


Result: "12 and -2.75"
Explanation: The value stored inxis formatted as a decimal (base 10) integer and
the value stored in y is formatted as a floating-point number. The other
characters in the string are retained without modification.
Percentage String Formatting Examples
Code Segment: "%.4f" % x
Result: "12.0000"
Explanation: The value stored in x is formatted as a floating-point number with 4 digits
to the right of the decimal point.

Code Segment: "%.1f" % y


Result: "-2.8"
Explanation: The value stored in y is formatted as a floating-point number with 1 digit
to the right of the decimal point. The valuewas rounded when itwas formatted
because the number of digits to the right of the decimal point was reduced.
Percentage String Formatting Examples
Code Segment: "%10s" % z
Result: " Andrew"
Explanation: The value stored in z is formatted as a string so that it occupies at least 10
spaces. Because z is only 6 characters long, 4 leading spaces are included
in the result.

Code Segment: "%4s" % z


Result: "Andrew"
Explanation: The value stored in z is formatted as a string so that it occupies at least 4
spaces. Because z is longer than the indicated minimum length, the resulting string is
equal to z.

Code Segment: "%8i%8i" % (x, y)


Result: " 12 -2"
Explanation: Both x and y are formatted as decimal (base 10) integers occupying a
minimum of 8 spaces. Leading spaces are added as necessary. The digits to the right of
decimal point are truncated (not rounded) when y (a floatingpoint number) is
formatted as an integer.
Python 3's f-Strings:
An Improved String Formatting Syntax
String Formatting Syntax Methods

➢ The percent formatting


➢ The string dot format
➢ f-strings
String Indexing
STRING INDEXING
➢ Strings are ordered sequences of character data
➢ Individual characters of a string can be accessed
directly using a numeric index
➢ String indexing in Python is zero-based
➢ The first character in the string has index 0
➢ The next has index 1 … and so on
➢ The index of the last character will be the length of the
string minus one.
STRING INDEXING

a p p l e

0 1 2 3 4
String Indices
STRING INDEXING

-5 -4 -3 -2 -1

a p p l e

0 1 2 3 4
String Indices
String Slicing
STRING SLICING

➢ Indexing syntax that extracts substrings from a string


➢ If d is a string d[m:n] returns the portion of d
➢ Starting with position m
➢ And up to but not including position n
STRING SLICING

➢ Omitting the first and/or last index


➢ Omitting the first index d[:n] starts the slice at the
beginning of the string
➢ Omitting the last index d[m:] extends the slice from
the first index m to the end of the string
➢ Omitting both indexes d[:] returns the entire
original string
➢ It’s not a copy, it’s a reference to the original
string
STRING SLICING

-7 -6 -5 -4 -3 -2 -1
a v o c a d o

0 1 2 3 4 5 6

d='avocado'
d[1:4]
Dates and Times
datetime provides three classes that make up the high-level
interface that most people will use:

➢ datetime.date is an idealized date that assumes the Gregorian


calendar extends infinitely into the future and past. This object
stores the year, month, and day as attributes.

➢ datetime.time is an idealized time that assumes there are 86,400


seconds per day with no leap seconds. This object stores the hour,
minute, second, microsecond, and tzinfo (time zone information)

➢ datetime.datetime is a combination of a date and a time. It has all


the attributes of both classes.
Modules in the standard library to work with dates and times:

➢ calendar outputs calendars and provides functions


using an idealized Gregorian calendar.
➢ datetime supplies classes for manipulating dates and
times.
➢ time provides time-related functions where dates are
not needed.
What is a List?
Important Characteristics of Lists

➢ Lists are ordered


➢ Lists can contain any arbitrary objects
➢ List elements can be accessed by index
➢ Lists can be nested to arbitrary depth
➢ Lists are mutable
➢ Lists are dynamic
A list is an ordered collection of objects

➢ The order used when defining a list is maintained


➢ Lists with the same elements in a different order are
not the same
A list can contain arbitrary objects

➢ The elements of a list can be the same type


➢ Or the elements can be of varying types
➢ Lists can contain complex objects:
➢ Functions
➢ Classes
➢ Modules
A list can contain any number of objects

➢ From zero
➢ To as many as your computer’s memory will allow
➢ A list with a single object is sometimes referred to as a
singleton list
List elements can be accessed by index

➢ Individual elements in a list can be accessed using an


index in square brackets
➢ mylist[m]
➢ List indexing is zero-based
LIST INDEXING

iphone ipad macAir icloud

0 1 2 3
LISTS - INDEXING AND SLICING

➢ List elements can be accessed by index


➢ Individual elements in a list can be accessed using an
index in square brackets
• mylist[m]
➢ List indexing is zero-based
LISTS - INDEXING AND SLICING

➢ List Indexing
a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

'spam' 'egg' 'bacon' 'tomato' 'ham' 'lobster'

0 1 2 3 4 5
List Indices
LISTS - INDEXING AND SLICING

➢ Negative Indexing

-6 -5 -4 -3 -2 -1
'spam' 'egg' 'bacon' 'tomato' 'ham' 'lobster'

0 1 2 3 4 5
List Indices
LISTS - INDEXING AND SLICING

➢ Slicing is indexing syntax that extracts a portion from a list


➢ If a is a list a[m:n] returns the portion of a
• Starting with position m
• And up to but not including position n
LISTS - INDEXING AND SLICING

➢ List Slicing
a[2:5]

-6 -5 -4 -3 -2 -1
'spam' 'egg' 'bacon' 'tomato' 'ham' 'lobster'

0 1 2 3 4 5
List Indices
LISTS - INDEXING AND SLICING

➢ Omitting the first and/or last index


• Omitting the first index a[:n] starts the slice at the
beginning of the list
• Omitting the last index a[m:] extends the slice from the
first index
• m to the end of the list
• Omitting both indexes a[:] returns a copy of the entire
list
• Unlike with a string, it’s a copy, not a reference to
the same object
LISTS - INDEXING AND SLICING
➢ Specifying a Stride in a List Slice
• Adding an additional : and a third index designates a stride
(also called a step)
• For the slice [0:6:2]

'spam' 'egg' 'bacon' 'tomato' 'ham' 'lobster'

0 1 2 3 4 5
List Indices
Tuples
Python Tuple Basics

➢ Tuples are identical to lists in all respects, except for the


following
• Tuples are defined by enclosing the elements in parentheses
instead of square brackets
• t=(‘apple’, ‘banana’, ‘orange’, ‘melon’,’blueberry’,’cherry’)
• Tuples are immutable
WHY USE A TUPLE INSTEAD OF A LIST?

➢ Program execution is faster when manipulating a


tuple than it is for the equivalent list
➢ You don’t want data modified
➢ A Python dictionary requires keys that are of an
immutable type
Sets
WHAT IS A SET?

➢ In mathematics, a set is a well-defined collection of


distinct objects
• Set of even positive numbers less than 10: 2, 4, 6, 8
• Set of perfect squares less than 10: 1, 4, 9
• Intersection of these two sets: the number 4

2, 4, 6, 8 4 1, 4, 9
WHAT IS A SET IN PYTHON?

➢ Python’s built-in set type has the following


characteristics:
➢ Sets are unordered
➢ Set elements are unique and duplicate elements are
not allowed
➢ A set itself may be modified, but the elements
contained in the set must be hashable
IMMUTABLE VS HASHABLE
Hashable
➢ Immutable - A type of object
that cannot be modified
class Foo:
def hash (self):
return 1
after it was created. Immutable
➢ Hashable - A type of object Tuples
Strings
that you can call hash() on. Integers
➢ All immutable objects are
hashable, but not all Booleans
Lists
hashable objects are
immutable. Dictionaries

➢ Python Sets can only include


hashable objects.
If Statements
IF STATEMENTS

➢ if condition 1 is met:
➢ do A
➢ elif condition 2 is met:
➢ do B
➢ elif condition 3 is met:
➢ do C
➢ else: do D
for Loops
FOR LOOPS

for an in iterable:
code
while Loops
WHILE LOOPS
Creating Stacks Using Lists
LIFO — LAST IN, FIRST OUT

Imagine you have some And you want to


blocks... stack them

A B C D A

D
“PUSHING” TO THE STACK

Remaining Blocks Stack

A D

B C
“PUSHING” TO THE STACK

Remaining Blocks Stack

A
“POPPING” THE STACK

Popped Blocks Stack

A
“POPPING” THE STACK

Popped Blocks Stack

B
C
A
“POPPING” THE STACK

Popped Blocks Stack

B C
A
“POPPING” THE STACK

Popped Blocks Stack

A D

B C

Pushing and popping happen in reverseorder


What are Functions?
THE RULES FOR NAMING A FUNCTION:

• They must start with a letter or an underscore


• They should be lowercase
• They can have numbers
• They can be any length, but keep them short
• They can’t be the same as a Python keyword
What Is Object-Oriented Programming (OOP)?
WHAT IS A PROGRAM?

Programs are a set of instructions for manipulating data


in a meaningful way

INPUT DATA MANIPULATE DATA RETURN DATA

How do we manage large programs with lots of data to


manipulate?
WHAT IS A PROGRAM?

Programs are a set of instructions for manipulating data


in a meaningful way

Ask user for birth date Calculate # of days old Display the result

INPUT DATA MANIPULATE DATA RETURN DATA

How do we manage large programs with lots of data to


manipulate?
OBJECT ORIENDED PROGRAMMING (OOP)

• A very common programming paradigm (style of


designing software)
• Makes developing large software projects easier and
more intuitive
• Allows us to think of complex software in terms of
real-world objects and their relationships to one
another
OBJECTS

• An entity or “thing” in your program, often a noun


• Example of an object could be a single person

Properties Behaviors
• Name • Walk
• Age • Talk
• Address • Breathe
Classes in Python
CLASSES
• Classes are used to create objects
• We can create many, unique objects from a single class
• Classes define a type
• The process of creating an object from a class is called
instantiation

Here we create a new variable called my_name


with a value of “Austin”. This variable is actually a my_name=‘Austin’
reference to an object. The type of the object is str
because in order to create it, we instantated the
built-in str class
EXAMPLE: DOORS
Door Class door1
Properties: Height: 50
• height Color: orange
• color is_locked: false
• is_locked open()
close()
Behaviors: toggle_lock()
• open()
• close()
• toggle_lock()
Unique object of type Door
EXAMPLE: DOORS
Door Class door1 door2
Properties: Height: 50 Height: 95
• height Color: orange Color: gray
• color is_locked: false is_locked: true
• is_locked open() open()
close() close()
Behaviors: toggle_lock() toggle_lock()
• open()
• close()
• toggle_lock()
Unique object of type Door
Class and Instance Attributes
EXAMPLE 1: VIDEO GAME

Enemy Class
Properties:
• name
• health
• Power_level

Behaviors:
• attack()
• takedamage()
• defeat()
EXAMPLE 2: WEB BROWSER

Tab Class
Properties:
• title (str)
• is_current (bool)
• page (Page)

Behaviors:
• close()
• reload()
EXAMPLE 2: WEB BROWSER

Tab Class Page Class


Properties: Properties:
• title (str) ………….
• is_current (bool)
• page (Page)
Behaviors:
Behaviors: ………….
• close()
• reload()
THINKING OBJECT-ORIENTLY

• Thinking of software this way takes a lot of practice


• Software design is often harder than actually coding it
• Planning a project is important
• What classes will you define?
• How many objects will you create?
• How will these objects interact with one another?
• It’s very easy to get this wrong , but you get better
with practice
CREATING A CLASS

Class Dog:
pass
INSTANCE ATTRIBUTES

• Properties are actually called attributes


• Instance attributes are unique to each object created
The initializer is called when
Class Dog: the object is instantiated
def _ _ init _ _(self, name, age):
self.name = name
self.age = age

Each dog object will have a


unique name and age value
CLASS ATTRIBUTES

• Properties are actually called attributes


• Instance attributes are unique to each object created
species is a class attribute.
Class Dog: Every dog will be created as
species = ‘mammal’ a mammal

def _ _ init _ _(self, name, age):


self.name = name
self.age = age
Introduction to OOP Inheritance
DON’T REPEAT YOURSELF (DRY)

If you find yourself frequently copying and pasting code


between classes, it may be time to rethink the design
EXAMPLE

• Write a program that constructs lots of people


• These people objects can either be a general person ,
or more specifically, a baby
• The baby has all the same attributes and behaviors as
the general person, but it may implement them
differently
• The baby also needs to be able to nap, unlike the
general person
EXAMPLE

Person Class Baby Class


Attributes: Attributes :
• description • description
• name • name
• age • age

Instance Methods: Instance Methods :


• speak() • speak()
• eat() • eat()
• action() • action()
• nap()

The Baby class


has an extra
method, nap()
EXAMPLE

Person Class Baby Class


Attributes: Attributes :
• description • description
• name • name
• age • age

Instance Methods: Instance Methods :


• speak() • speak()
• eat() • eat()
• action() • action()
• nap()

Changing Person’s action() will require us to


change Baby’s action() too
CLASS RELATIONSHIPS

• How are a baby and a person related in the real


world?
• We can say that a baby ‘is a‘ person, but a person is
not necessarily a baby
• A baby is a specialized version of a more general
person

Person Baby
OBJECT INHERITANCE

• Python classes can inherit from one another


• The child class inherits from the parent class
• The child class automatically implements the parent’s
attributes and methods
• We can redefine baby-specific attributes, and even
extend the baby class to include new functionality

Parent class Child class

Person Baby
CLASS HIERARCHY All classes inherit from object,
including the built-in types like
int and str
• Python classes can inherit
from one another Object
• Here, a baby is a person, and
a person is an object.
str int Person
Therefore, a baby is also an
object. Built-in types
• All objects are of type
Baby
objects, as well as any more
specific types like Person Custom types
Inheritance Example
CONCLUSION

• Inheritance is only one of the fundamental principles


of OOP design
• A basic understanding of OOP opens the doors to
many new programming opportunities
• Thousands of Python libraries and frameworks utilize
OOP
Modules and Packages: Overview
PYTHON MODULES AND PACKAGES

Modular programming refers to the process of breaking a


large, unwieldy programming task into separate, smaller,
more manageable subtasks or modules.
PYTHON MODULES AND PACKAGES

What are advantages of modularizing code in a large


application?

● Simplicity
● Maintainability
● Reusability
● Scoping
PYTHON MODULES AND PACKAGES

❖ Writing a Module
❖ The Module Search Path
❖ The import Statement
❖ The dir() Function
❖ Executing a Module
❖ Reloading a Module
❖ How to Install a Package in Python using PIP
❖ Python Packages
❖ Create Graphics & Shapes Using Python’s Turtle
Module
Writing a Module
WRITING A MODULE

Three different styles of modules in Python

● A module written in Python itself


● A module written in C and loaded dynamically at
run-time
● A built-in module is intrinsically contained in the
interpreter
The Module Search Path
THE MODULE SEARCH PATH

Where can you import a module from?

❖ The interpreter searches for the file


▪ In the current directory
▪ In the PYTHONPATH environment variable list
of directories
▪ The directories configured as part of your
Python installation
THE MODULE SEARCH PATH

Where should you put your module file?

❖ To ensure you module is found place the file in:


• The same directory as the input script or the current
directory
• Modify PYTHONPATH environment variable to contain
the directory where it is located
• Or in one of the directories already in the
PYTHONPATH
❖ In one of the directories configured as part of your Python
installation
THE MODULE SEARCH PATH

Where should you put your module file?

❖ Or you can modify the sys.path list at run time


sys.path.append(r'C:\Users\Andreas\ModulesDirectory')
The import Statement
THE import STATEMENT

What forms can the import statement take?

❖ The simplest form


• import <module_name>
❖ The module contents are not directly accessible to the caller
• A module creates a separate namespace
THE import STATEMENT

What forms can the import statement take?

➢ Individual objects from the module can be imported


• from <module_name> import <name(s)>
➢ The individual objects are directly accessible to the caller
• Objects are imported into the caller’s symbol table
THE import STATEMENT

What forms can the import statement take?

➢ It is possible to import everything from a module at once


• from <module_names> import *
➢ This places all the names of objects into the local symbol table
• With the exception of any that begin with an underscore
• NOTE: This isn’t necessarily recommended
• Unless you know all the names will not conflict and
overwrite existing names
THE import STATEMENT

What forms can the import statement take?

➢ Individual objects can be imported with alternate names


• from <module_name> import <name> as <alt_name>
➢ Making it possible to place names directly into the local symbol
table
• Avoiding conflicts with existing names
THE import STATEMENT

What forms can the import statement take?

➢ Import the entire module under an alternate name


import <module_name> as <alt_name>
Python Packages
PYTHON PACKAGES

How to keep track of a growing number of modules

• Packages allow for a hierarchical structuring of the module


namespace using dot notation
• Example package structure:

pkg

mod1.py

mod2.py
Python's open, read from, and write to a file
The open function

open(file_name, mode)

opens the given filename (from the current


directory) in the specified mode
Basic File Modes

“w” Write mode: wipes existing file content


“r” Read mode: read-only access to the file content
“a” Append mode: writes to the end of the file
Getting a Directory Listing & File Attributes
Basic directory listing functions
With the os module:
➢ os.listdir(dirname) takes in a directory name as a string and returns a list
of all of the files and subdirectories in that directory
➢ os.scandir(dirname) similar behavior to listdir, but returns an iterator of
file objects rather than a list of strings

With the pathlib module:


➢ pathlib.Path.iterdir() works on a path object and returns a similar
iterator to scandir
Useful functions for getting file information

With the os module:


➢ os.stat(path_string) takes in a file or directory path as a string and
returns a stat_result object with the file data
➢ os.scandir(dirname) — In the returned iterator, each object has a .stat()
method that returns the same data as os.stat()

With the pathlib module:


➢ pathlib.Path.iterdir() — each item in the iterator has a .stat() method,
just like in scandir
Making & Deleting Directories
Useful functions for making directories

With the os module:


➢ os.mkdir(dir_name) creates a single subdirectory with the given Name
➢ os.makedirs(path_name) creates full directory trees (including
intermediate directories, as needed)

With the pathlib module:


➢ pathlib.Path.mkdir() creates a directory from the given Path object
Useful functions for deleting directories

Deleting a single directory:


• os.rmdir(dir_path) deletes a single directory, raises OSError if the
directory is non-empty
• pathlib.Path.rmdir() is identical to os.rmdir(), except it operates on a
Path object

Deleting an entire directory tree:


• shutil.rmtree(dir_path) deletes the entire directory tree rooted at
dir_path
Deleting, Copying, Moving, and Renaming Files
Useful functions for deleting files

With the os module:


➢ os.remove(file_path) deletes a single file, raises FileNotFound if the file
doesn’t exist
➢ os.unlink(file_path) is essentially identical to os.remove

With the pathlib module:


➢ pathlib.Path.unlink() is identical to the os module options, except it
operates on a Path object
Useful functions for copying and moving files

Copying:
❑ shutil.copy(src, dst) copies a file (but not its metadata) from the src path
to the dst path — if you need the metadata, use copy2
❑ shutil.copytree(src_dir, dst_dir) copies full directory trees

Moving/Renaming:
❑ shutil.move(src, dst) moves a file or directory from src to dst
❑ os.rename(old, new) renames a file or directory
Dealing with errors
DEALING WITH ERRORS

To properly detect errors:

✓ You need to know about error sources and


why errors occur in the first place
DEALING WITH ERRORS

A debugger is a special kind of tool that lets you stop or


pause application execution, examine the content of
variables, and generally dissect the application to see
what makes it tick.
DEALING WITH ERRORS

The two principal types are:


• Errors that occur at a specific time
• Errors that are of a specific type

Errors occur at specific times. The two major time frames


are:
• Compile time
• Runtime
DEALING WITH ERRORS

Python (and most other programming languages) breaks


errors into the following types:
• Syntactical
• Semantic
• Logical
Common Syntax Problems
COMMON SYNTAX PROBLEMS

1. Misusing the Assignment Operator (=)


2. Misspelling, Missing, or Misusing Python
Keywords
3. Missing Parentheses, Brackets, and Quotes
MISSING PARENTHESES, BRACKETS, AND
QUOTES
● Escape the single quote with a backslash
('don\'t’)

● Surround the entire string in double-quotes


("don't")
Handling Multiple Exceptions
Handling Multiple Exceptions

● Handling multiple exceptions with multiple


except clauses

● Handling more specific to less specific


exceptions
Raising Exceptions
Let’s see some common scenarios in which
you raise exceptions in specific ways:

● Raising exceptions during exceptional


conditions

● Passing error information to the caller


Milestone Project:
Create an interactive Math Game in Python
OVERVIEW
OVERVIEW

MATH GAME

Part 1 Part 2
math-Functions.py math-Game.py
Thank you !!
Project:
Guessing Game: version 2
Check out my other courses!
Please leave your feedback
and an honest review of the course

You might also like