0% found this document useful (0 votes)
5 views38 pages

Python Programming Tur

python extensive for beginer

Uploaded by

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

Python Programming Tur

python extensive for beginer

Uploaded by

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

Python Programming - Teaching Guide

Table of Contents

1. Introduction to Python
2. Setting Up the Environment
3. Variables and Data Types
4. Operators and Expressions
5. Conditional Statements
6. Loops
7. Functions
8. Lists and Tuples
9. Dictionaries and Sets
10. Strings and String Methods
11. File Handling
12. Error Handling (Exceptions)
13. Object-Oriented Programming (OOP)
14. Modules and Packages
15. Virtual Environments
16. Working with External Libraries
17. Introduction to Projects

1. Introduction to Python

Objective: Understand what Python is and where it's used.

What is Python?

 Python is a high-level, interpreted programming language known for its readability. It was created
by Guido van Rossum and released in 1991
 Widely used in web development(server side), data science, automation, and AI.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is written.
This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

2. Setting Up the Environment

Objective: Install Python and set up a development environment.

Steps:

 Install Python from python.org


 Use an IDE like VS Code, PyCharm, or an online editor like Replit or Google Colab.

Check Installation:

python --version

Hello World Example:

Python is an interpreted programming language, this means that as a developer you write Python (.py)
files in a text editor and then put those files into the python interpreter to be executed.

The way to run a python file is like this on the command line:

C:\Users\Your Name>python helloworld.py

Where "helloworld.py" is the name of your python file.


Let's write our first Python file, called helloworld.py, which can be done in any text editor. In the file
put

print("Hello, World!")

Simple as that. Save your file. Open your command line, navigate to the directory where you saved
your file, and run:

C:\Users\Your Name>python helloworld.py

The output should read:


Hello, World!

The Python CommandLine

To test a short amount of code in python sometimes it is quickest and easiest not to write the code in a
file. This is made possible because Python can be run as a command line itself.

Type the following on the Windows, Mac or Linux command line:


C:\Users\Your Name>python
Or, if the "python" command did not work, you can try just "py"

From there you can write any python, including our hello world example from
earlier in the tutorial:

C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32
bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more
information.
>>> print("Hello, World!")
Hello, World!

You can type exit() to quit the python command line interface.

Python Indentation

Indentation refers to the spaces at the beginning of a code line.


Where in other programming languages the indentation in code is for readability
only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.

Valid synthax
if 5 > 2:
print("Five is greater than two!")

Syntax Error:
if 5 > 2:
print("Five is greater than two!")

Comments
Python has commenting capability for the purpose of in-code documentation.
Comments start with a #, and Python will render the rest of the line as a comment:

#This is a comment.
print("Hello, World!")

print("Hello, World!") #This is a comment

#print("Hello, World!")
print("Cheers, Mate!")

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

3. Variables and Data Types

Objective: Learn how to store and use data.

Python has no command for declaring a variable.

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


Example:

name = "Alice"
age = 25
height = 5.6
is_student = True
print(name)
print(age)

Variables do not need to be declared with any particular type, and can even
change type after they have been set.

x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Casting
If you want to specify the data type of a variable, this can be done with casting.

x = str(3) # x will be '3'


y = int(3) # y will be 3
z = float(3) # z will be 3.0

You can get the data type of a variable with the type() function.
x = 5
y = "John"
print(type(x))
print(type(y))

String variables can be declared either by using single or double quotes:


x = "John"
# is the same as
x = 'John'

Variable names are case-sensitive.


a = 4
A = "Sally"
#A will not overwrite a
Variable Names

A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for Python variables:

 A variable name must start with a letter or the underscore character


 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and AGE are three different
variables)
 A variable name cannot be any of the Python keywords.

Valid variable names

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal variable names:


2myvar = "John"
my-var = "John"
my var = "John"

Multi Words Variable Names

Variable names with more than one word can be difficult to read.

There are several techniques you can use to make them more readable:

Camel Case

Each word, except the first, starts with a capital letter:

myVariableName = "John"
Pascal Case

Each word starts with a capital letter:

MyVariableName = "John"

Snake Case

Each word is separated by an underscore character:

my_variable_name = "John"

Many Values to Multiple Variables

Python allows you to assign values to multiple variables in one line:

x, y, z = "Orange", "Banana", "Cherry"


print(x)
print(y)
print(z)

One Value to Multiple Variables

And you can assign the same value to multiple variables in one line:

x = y = z = "Orange"
print(x)
print(y)
print(z)

Output Variables
The Python print() function is often used to output variables.

x = "Python is awesome"
print(x)

In the print() function, you output multiple variables, separated by a comma:


x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
You can also use the + operator to output multiple variables:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Notice the space character after "Python " and "is ", without them the
result would be "Pythonisawesome".

For numbers, the + character works as a mathematical operator:


x = 5
y = 10
print(x + y)

In the print() function, when you try to combine a string and a number with
the + operator, Python will give you an error:
x = 5
y = "John"
print(x + y) #will throw an error

Global Variables
Variables that are created outside of a function (as in all of the examples
in the previous pages) are known as global variables.
Global variables can be used by everyone, both inside of functions and
outside.

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

If you create a variable with the same name inside a function, this variable will be local,
and can only be used inside the function. The global variable with the same name will
remain as it was, global and with the original value.

x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()
print("Python is " + x)

The global Keyword

Normally, when you create a variable inside a function, that variable is local, and can only
be used inside that function.

To create a global variable inside a function, you can use the global keyword.

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a function.

x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Data Types:

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset


Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

You can get the data type of any object by using the type() function:
x = 5
print(type(x))

If you want to specify the data type, you can use the following constructor functions:
Python Numbers
There are three numeric types in Python:

 int
 float
 complex

Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex

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

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Float can also be scientific numbers with an "e" to indicate the power of 10.

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Complex
Complex numbers are written with a "j" as the imaginary part:
x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

Type Conversion
You can convert from one type to another with the int(), float(),
and complex() methods:

x = 1 # int
y = 2.8 # float
z = 1j # complex

#convert from int to float:


a = float(x)

#convert from float to int:


b = int(y)

#convert from int to complex:


c = complex(x)

print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))

Note: You cannot convert complex numbers into another number type.

Random Number
Python does not have a random() function to make a random number, but Python has a
built-in module called random that can be used to make random numbers:

Import the random module, and display a random number from 1 to 9:


import random

print(random.randrange(1, 10))

Python Casting

There may be times when you want to specify a type on to a variable. This can be done
with casting. Python is an object-orientated language, and as such it uses classes to define
data types, including its primitive types.

Casting in python is therefore done using constructor functions:

 int() - constructs an integer number from an integer literal, a float literal (by
removing all decimals), or a string literal (providing the string represents a whole
number)
 float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
 str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

Python Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

print("Hello")
print('Hello')

You can use quotes inside a string, as long as they don't match the quotes surrounding the
string:

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

a = '''Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the code.

Strings are Arrays


Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.

However, Python does not have a character data type, a single character is simply a string
with a length of 1.

Square brackets can be used to access elements of the string.

Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
Since strings are arrays, we can loop through the characters in a string, with a for loop.

for x in "banana":
print(x)

To get the length of a string, use the len() function.


a = "Hello, World!"
print(len(a))

To check if a certain phrase or character is present in a string, we can use the keyword in.
txt = "The best things in life are free!"
print("free" in txt)

Use it in an if statement:
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.
txt = "The best things in life are free!"
print("expensive" not in txt)

Use it in an if statement:
print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

Slicing
You can return a range of characters by using the slice syntax.

Specify the start index and the end index, separated by a colon, to return a part of the
string.

Get the characters from position 2 to position 5 (not included):

b = "Hello, World!"
print(b[2:5])

Note: The first character has index 0.

By leaving out the start index, the range will start at the first character:
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])

By leaving out the end index, the range will go to the end:
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])

Use negative indexes to start the slice from the end of the string:

Get the characters:

From: "o" in "World!" (position -5)

To, but not included: "d" in "World!" (position -2)

b = "Hello, World!"
print(b[-5:-2])

Python - Modify Strings


Python has a set of built-in methods that you can use on strings.

Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())

Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())

Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often you want to
remove this space.
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Replace String
The replace() method replaces a string with another string:
a = "Hello, World!"
print(a.replace("H", "J"))

Split String
The split() method returns a list where the text between the specified separator
becomes the list items.

The split() method splits the string into substrings if it finds instances of the separator:

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

String Concatenation
To concatenate, or combine, two strings you can use the + operator.

Merge variable a with variable b into variable c:


a = "Hello"
b = "World"
c = a + b
print©

To add a space between them, add a " ":


a = "Hello"
b = "World"
c = a + " " + b
print(c)

String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers
like this:

age = 36
txt = "My name is John, I am " + age
print(txt)

But we can combine strings and numbers by using f-strings or the format() method!

F-Strings

F-String was introduced in Python 3.6, and is now the preferred way of formatting strings.

To specify a string as an f-string, simply put an f in front of the string literal, and add curly
brackets {} as placeholders for variables and other operations.

age = 36
txt = f"My name is John, I am {age}"
print(txt)

A placeholder can contain variables, operations, functions, and modifiers to format the
value.

Add a placeholder for the price variable:

price = 59
txt = f"The price is {price} dollars"
print(txt)
A placeholder can include a modifier to format the value.

A modifier is included by adding a colon : followed by a legal formatting type,


like .2f which means fixed point number with 2 decimals:

Display the price with 2 decimals:


price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

A placeholder can contain Python code, like math operations:


Perform a math operation in the placeholder, and return the result:
txt = f"The price is {20 * 59} dollars"
print(txt)

Escape Character

To insert characters that are illegal in a string, use an escape character.

An escape character is a backslash \ followed by the character you want to insert.

An example of an illegal character is a double quote inside a string that is surrounded by


double quotes:

You will get an error if you use double quotes inside a string that is surrounded by double
quotes:
txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character \":


txt = "We are the so-called \"Vikings\" from the north."
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods return new values. They do not change the original string.
Python Booleans

Booleans represent one of two values: True or False.

Boolean Values
In programming you often need to know if an expression
is True or False.
You can evaluate any expression in Python, and get one of two
answers, True or False.
When you compare two values, the expression is evaluated and
Python returns the Boolean answer.

print(10 > 9)
print(10 == 9)
print(10 < 9)

When you run a condition in an if statement, Python returns True or False:


Print a message based on whether the condition is True or False:
a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

The bool() function allows you to evaluate any value, and give you True or False in
return,

Evaluate a string and a number:

print(bool("Hello"))
print(bool(15))

Evaluate two variables:

x = "Hello"
y = 15

print(bool(x))
print(bool(y))

Almost any value is evaluated to True if it has some sort of content.

Any string is True, except empty strings.

Any number is True, except 0.

Any list, tuple, set, and dictionary are True, except empty ones.

The following will return True:


bool("abc")
bool(123)
bool(["apple", "cherry", "banana"])

In fact, there are not many values that evaluate to False, except empty values, such
as (), [], {}, "", the number 0, and the value None. And of course the
value False evaluates to False.

The following will return False:


bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

One more value, or object in this case, evaluates to False, and that is if you have an object
that is made from a class with a __len__ function that returns 0 or False:

class myclass():
def __len__(self):
return 0

myobj = myclass()
print(bool(myobj))

Functions can Return a Boolean


You can create functions that returns a Boolean Value:
def myFunction() :
return True

print(myFunction())

You can execute code based on the Boolean answer of a function:

def myFunction() :
return True

if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions that return a boolean value, like
the isinstance() function, which can be used to determine if an object is of a certain data
type:

Check if an object is an integer or not:

x = 200
print(isinstance(x, int))

4. Operators and Expressions

Objective: Use Python's operators to perform calculations.

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

print(10 + 5)

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common


mathematical operations:
Python Assignment Operators

Assignment operators are used to assign values to variables:


Python Comparison Operators

Comparison operators are used to compare two values:

Python Logical Operators

Logical operators are used to combine conditional statements:

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Operator Precedence

Operator precedence describes the order in which operations are performed.

Parentheses has the highest precedence, meaning that expressions inside parentheses
must be evaluated first:

print((6 + 3) - (6 + 3))
Multiplication * has higher precedence than addition +, and therefore multiplications are
evaluated before additions:

print(100 + 5 * 3)

The precedence order is described in the table below, starting with the highest precedence
at the top:

Addition + and subtraction - has the same precedence, and therefore we evaluate the
expression from left to right:

print(5 + 4 - 7 + 3)

5. Conditional Statements

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:
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
These conditions can be used in several ways, most commonly in "if
statements" and loops.

if
An "if statement" is written by using the if keyword.

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than
33, and so we print to screen that "b is greater than a".

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.

If statement, without indentation (will raise an error):


a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

elif
The elif keyword is Python's way of saying "if the previous conditions were not true, then
try this condition".

a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is
true, so we print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding conditions.

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also the elif condition
is not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If

If you have only one statement to execute, you can put it on the same line
as the if statement.

if a > b: print("a is greater than b")

Short Hand If ... Else

If you have only one statement to execute, one for if, and one for else, you
can put it all on the same line:

a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.


You can also have multiple else statements on the same line:

For example

One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And

The and keyword is a logical operator, and is used to combine conditional


statements:

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional


statements:

Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:

Test if a is NOT greater than b:

a = 33
b = 200
if not a > b:
print("a is NOT greater than b")

Nested If
You can have if statements inside if statements,x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.

a = 33
b = 200

if b > a:
pass

6. Loops

Objective: Repeat actions using for and while loops.

Python For Loops


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).

This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

Print each fruit in a fruit list:

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


for x in fruits:
print(x)

The for loop does not require an indexing variable to set beforehand.

The break Statement

With the break statement we can stop the loop before it has looped through all the items:
Exit the loop when x is "banana":

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


for x in fruits:
if x == "banana":
break
print(x)

The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue
with the next:

Do not print banana:

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


for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use
the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.

for x in range(6):
print(x)

Note that range(6) is not the values of 0 to 6, but the values 0 to 5.

The range() function defaults to 0 as a starting value, however it is possible to specify the
starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but
not including 6):

for x in range(2, 6):


print(x)

The range() function defaults to increment the sequence by 1, however it is possible to


specify the increment value by adding a third parameter: range(2, 30, 3):

Increment the sequence with 3 (default is 1):

for x in range(2, 30, 3):


print(x)

Else in For Loop

The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:

Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")

Note: The else block will NOT be executed if the loop is stopped by a break statement.

Break the loop when x is 3, and see what happens with the else block:

for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!"

Nested Loops

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

adj = ["red", "big", "tasty"]


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

for x in adj:
for y in fruits:
print(x, y)

The pass Statement

for loops cannot be empty, but if you for some reason have a for loop with no content,
put in the pass statement to avoid getting an error.

for x in [0, 1, 2]:


pass

For Loop Example:

for i in range(5):
print(i)

While Loop Example:

count = 0
while count < 5:
print(count)
count += 1

7. Functions

Objective: Write reusable blocks of code.

Example:

def greet(name):
return f"Hello, {name}"

print(greet("Bob"))

8. Lists and Tuples

Objective: Store and manipulate collections.

List Example:

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


print(fruits[1])

Tuple Example:

coordinates = (10, 20)


print(coordinates[0])

9. Dictionaries and Sets

Objective: Use key-value pairs and unique collections.

Dictionary Example:
student = {"name": "Alice", "age": 22}
print(student["name"])

Set Example:

unique_numbers = {1, 2, 3, 3}
print(unique_numbers)

Unpack a Collection

If you have a collection of values in a list, tuple etc. Python allows you to extract the values
into variables. This is called unpacking.

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


x, y, z = fruits
print(x)
print(y)
print(z)

10. Strings and String Methods

Objective: Work with text data.

Example:

text = "hello world"


print(text.upper())
print(text.replace("hello", "hi"))

11. File Handling

Objective: Read from and write to files.

Example:

with open("example.txt", "w") as f:


f.write("This is a file.")

with open("example.txt", "r") as f:


print(f.read())
12. Error Handling (Exceptions)

Objective: Handle runtime errors.

Example:

try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")

13. Object-Oriented Programming (OOP)

Objective: Understand classes and objects.

Example:

class Dog:
def __init__(self, name):
self.name = name

def bark(self):
print(f"{self.name} says woof!")

d = Dog("Fido")
d.bark()

14. Modules and Packages

Objective: Organize code into files and import them.

Example:

import math
print(math.sqrt(16))

15. Working with External Libraries

Objective: Use pip and external tools like requests, pandas.


Install a library:

pip install requests

Use requests:

import requests
response = requests.get("https://api.github.com")
print(response.status_code)

16. Introduction to Projects

Objective: Apply what you've learned.

Mini Project Ideas:

 To-Do List App


 Calculator
 Quiz Game
 Weather App using API

End of Teaching Guide.

You might also like