0% found this document useful (0 votes)
4 views77 pages

Python Programming Complete Notes

Uploaded by

TOUQEER RASHID
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)
4 views77 pages

Python Programming Complete Notes

Uploaded by

TOUQEER RASHID
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/ 77

PYTHON PROGRAMMING NOTES

Chapter 1
Introduction to Computer programming

Computer Programming

Computer programming is the act of writing computer programs, which are a sequence of
instructions written using a Computer Programming Language to perform a specified task
by the computer.

Introduction to Computer Program


Before getting into computer programming, let us first understand computer programs and
what they do.
A computer program is a sequence of instructions written using a Computer Programming
Language to perform a specified task by the computer.

The two important terms that we have used in the above definition are −
• Sequence of instructions
• Computer Programming Language
To understand these terms, consider a situation when someone asks you about how to go to
a nearby KFC. What exactly do you do to tell him the way to go to KFC?

You will use Human Language to tell the way to go to KFC, something as follows −
First go straight, after half kilometer, take left from the red light and then drive around one
kilometer and you will find KFC at the right.

Here, you have used English Language to give several steps to be taken to reach KFC. If they
are followed in the following sequence, then you will reach KFC −

1. Go straight
2. Drive half kilometer

3. Take left

4. Drive around one kilometer

5. Search for KFC at your right side

Now, try to map the situation with a computer program. The above sequence of instructions
is actually a Human Program written in English Language, which instructs on how to
reach KFC from a given starting point. This same sequence could have been given in Spanish,
Hindi, Arabic, or any other human language, provided the person seeking direction knows
any of these languages.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Now, let's go back and try to understand a computer program, which is a sequence of
instructions written in a Computer Language to perform a specified task by the computer.
Following is a simple program written in Python programming Language −

print "Hello, World!"

The above computer program instructs the computer to print "Hello, World!" on the
computer screen.

• A computer program is also called a computer software, which can range from two
lines to millions of lines of instructions.
• Computer program instructions are also called program source code and computer
programming is also called program coding.
• A computer without a computer program is just a dump box; it is programs that make
computers active.
As we have developed so many languages to communicate among ourselves, computer
scientists have developed several computer-programming languages to provide instructions
to the computer (i.e., to write computer programs). We will see several computer
programming languages in the subsequent chapters.

Introduction to Computer Programming


If you understood what a computer program is, then we will say: the act of writing
computer programs is called computer programming.
As we mentioned earlier, there are hundreds of programming languages, which can be used
to write computer programs and following are a few of them −

• Java
• C
• C++
• Python
• PHP
• Perl
• Ruby
Uses of Computer Programs
Today computer programs are being used in almost every field, household, agriculture,
medical, entertainment, defense, communication, etc. Listed below are a few applications of
computer programs −

• MS Word, MS Excel, Adobe Photoshop, Internet Explorer, Chrome, etc., are examples
of computer programs.
• Computer programs are being used to develop graphics and special effects in movie
making.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

• Computer programs are being used to perform Ultrasounds, X-Rays, and other
medical examinations.
• Computer programs are being used in our mobile phones for SMS, Chat, and voice
communication.
Computer Programmer

Someone who can write computer programs or in other words, someone who can do
computer programming is called a Computer Programmer.

Based on computer programming language expertise, we can name a computer programmer


as follows −

• C Programmer
• C++ Programmer
• Java Programmer
• Python Programmer
• PHP Programmer
• Perl Programmer
• Ruby Programmer
We assume you are well aware of English Language, which is a well-known Human
Interface Language. English has a predefined grammar, which needs to be followed to write
English statements in a correct way. Likewise, most of the Human Interface Languages
(Hindi, English, Spanish, French, etc.) are made of several elements like verbs, nouns,
adjectives, adverbs, propositions, and conjunctions, etc.

Similar to Human Interface Languages, Computer Programming Languages are also made of
several elements. We will take you through the basics of those elements and make you
comfortable to use them in various programming languages. These basic elements include −

• Programming Environment
• Basic Syntax
• Data Types
• Variables a=5 a =5.1 a = ahmed
• Keywords
• Basic Operators
• Decision Making- condition
• Loops
• Numbers
• Characters
• Strings
• Functions
• File I/O

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Difference between Assembly Language and High-level Language

A computer is simply a machine and hence it cannot perform any task itself. Therefore, to
make a computer functional different coding languages are developed, which are known
as programming languages.

A computer programming language is a language in which the codes are written to instruct
the computer to perform tasks.
Computer programming languages are broadly classified into the following three main
categories −
• Machine Language- low level
• Assembly Language
• High-level Language
What is Assembly Language?
Assembly language is a type of low-level programming language which is used for writing
instructions for computers or other programmable devices. Since, it is a low-level language,
therefore, it can communicate with computer hardware directly.

Explanation:

In assembly language, the computer codes are written using words and expressions that are
easier to understand for human. The computer processor can only execute machine codes,
hence it is required to convert the assembly codes into machine codes. For this purpose, a
utility program is used to convert assembly code into executable machine code. This utility
program which converts assembly code into machine code is called assembler.
Assembler: The program which converts assembly code into machine code is
called assembler.

The major advantages of assembly language are less memory requirement, less execution
time, easier to write instructions and codes, etc.

What is High-level Language?


High-Level Language, also called HLL, is a category of computer programming languages
that use English like statements to write the computer instructions and codes. These are the
most widely used programming languages because they are easy to understand to human
being. However, similar to the assembly language, the CPU cannot process the high-level
language codes directly, i.e. they need to be translated first into the executable machine
codes. For this, there are two types of language translators used namely, interpreter and
compiler.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

The major advantages of high-level languages include easy to write, debug, and understand,
machine independent, etc. The common examples of high-level languages are C, C++, Java,
Python, C#, etc.

Now, let us discuss the important differences between assembly language and high-level
language.

Difference between Assembly Language and High-level Language


The following table highlights all the significant differences between assembly language and
high-level language −
Parameter Assembly Language High-Level Language

Definition Assembly language is a computer programming High-level language is a computer


language in which abbreviated keywords are program language in which
used to write instruction codes. English like statements are used
to write codes.

Language A language translator called “assembler” is High-level language requires an


translator required to convert the assembly language code interpreter or a compiler to
into the machine code. convert the high-level language
codes into the executable machine
codes.

Level of Assembly language is a low-level language. High-level language, as the name


language implies, is high-level language.

Programmer Assembly language is less programmer friendly High-level language is highly user
friendliness programming language. friendly programming language.

Speed of Computer instructions written in assembly Computer instructions written in


execution language execute faster. high-level language execute
slower.

Machine Assembly language is machine dependent. High-level language is machine


dependency independent.

Prone to error Assembly language is more prone to errors. The chances of errors in high-
level languages are less.

Memory Assembly language codes require less memory High-level language codes require
requirement space. more memory space.

Code length The length of executable codes in assembly The length of executable codes in
language is shorter. high-level language is longer.

Debug Assembly language codes are relatively difficult High-level language codes are
to debug. It is more challenging and time- very easy to debug.
consuming.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Complexity Assembly language is a complex programming High-level languages are easy to


language, as to write the instruction codes in write codes without much
assembly language, the programmer must have knowledge about the computer
a deep understanding of hardware and system hardware and architecture.
architecture.

Efficiency Assembly language codes are more efficient. High-level language codes are less
efficient, as the coder has less
control over the underlying
hardware.

Readability The readability of assembly language codes is High-level language codes are
less. more readable.

Development Assembly language programs take more time High-level language programs
time & effort and effort to develop. require less development time
and effort.

Memory Assembly language codes require manual High-level language codes


management memory management. provide automatic memory
management.

Syntax Assembly language uses symbolic High-level languages use


representation of machine codes. keywords and statements similar
to English language.

Applications Assembly language is primarily used to program High-level languages are mainly
processors, microcontrollers, embedded used for developing software
systems, device drivers, etc. applications, web applications,
etc.

Conclusion

To conclude, assembly language is a low-level language in which the codes are written using
symbolic representation of machine codes, whereas high-level languages are programming
languages that use keywords and phrases which are closer to natural language like English
to write the computer instructions. Examples of some commonly used high-level languages
include C, C++, Java, Python, C#, etc.

Algorithm

Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a


certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language

2nd Definition of Algorithm

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

A finite set of steps that must be followed to solve any problem is called an algorithm.
Algorithm is generally developed before the actual coding is done. It is written using English
like language so that it is easily understandable even by non-programmers.

Example Algorithms

Let us first take an example of a real-life situation for creating algorithm. Here is the
algorithm for going to the market to purchase a pen.

What is a Compiler?
A language processor that converts a program written in high-level language into machine
language, entire program at once, is called a compiler. Thus, the input of a compiler is a high-
level language code (called source code), while its output is a machine language code (called
object code).

The following flow diagram gives an illustration of the process

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

A compiler scans whole program and then check it for syntactic and semantic error, once the
code is checked for errors, it is converted into an object code. Then, it can be processed by
the machine to perform the corresponding task. The common programming languages that
use compiler are C, C++, C#, etc.

What is an Interpreter?
A language translator that converts a high-level language program into a machine language
program, one line at a time, is referred to as an interpreter. Interpreters converts the codes
slower than compiler. This is because the interpreter can scan and translate only one
statement of the program at a time. Therefore, interpreters convert the source code into
machine code during the execution of the program.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

So, if you are going to write your programs in PHP, Python, Perl, Ruby, etc., then you will
need to install their interpreters before you start programming.

Difference between Compiler and Interpreter


The following table highlights all the significant differences between a Compiler and an
Interpreter –

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Parameter Compiler Interpreter

Program Compilers scan the entire program The program is interpreted/translated one line
scanning in one go. at a time.

Error detection As and when scanning is performed, One line of code is scanned, and errors
all the errors are shown in the end encountered are shown.
together, not line by line.

Object code Compilers convert the source code Interpreters do not convert the source code into
to object code. object code.

Execution time The execution time of compiler is It is not preferred due to its slow speed. Usually,
less, hence it is preferred. interpreter is slow, and hence takes more time
to execute the object code.

Need of source Compiler doesn’t require the source It requires the source code for execution later.
code code for execution later.

Programming Programming languages that use Programming languages that uses interpreter
languages compilers include C, C++, C#, etc.. include Python, Ruby, Perl, MATLAB, etc.

Types of errors Compiler can check syntactic and Interpreter checks the syntactic errors only.
detected semantic errors in the program
simultaneously.

Size Compiler are larger in size. Interpreters are smaller in size.

Flexibility Compilers are not flexible. Interpreters are relatively flexible.

Efficiency Compilers are more efficient. Interpreters are less efficient.

Hello World Program in Python

Following is the equivalent program written in Python. This program will also produce the
same result Hello, World!

# print function to write Hello, World! */

print "Hello, World!"

which produces the following result −

Hello, World!

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Introduction to Python

Today, Python is one of the most popular programming languages. Although it is a general-
purpose language, it is used in various areas of applications such as Machine Learning,
Artificial Intelligence, web development, IoT, and more.

What is Python?
Python is a very popular general-purpose interpreted, interactive, object-oriented, and high-
level programming language. Python is dynamically-typed and garbage-collected
programming language. It was created by Guido van Rossum during 1985- 1990. Like Perl,
Python source code is also available under the GNU General Public License (GPL).
Python supports multiple programming paradigms, including Procedural, Object Oriented and
Functional programming language. Python design philosophy emphasizes code readability
with the use of significant indentation.

Python Jobs
Today, Python is very high in demand and all the major companies are looking for great
Python Programmers to develop websites, software components, and applications or to
work with Data Science, AI, and ML technologies. there is a high shortage of Python
Programmers whereas market demands more number of Python Programmers due to it's
application in Machine Learning, Artificial Intelligence etc.

Today a Python Programmer with 3-5 years of experience is asking for around $150,000
annual package and this is the most demanding programming language in America. Though
it can vary depending on the location of the Job. It's impossible to list all of the companies
using Python, to name a few big companies are:

• Google
• Intel
• NASA
• PayPal
• Facebook
• IBM
• Amazon
• Netflix
• Pinterest
• Uber
• Many more...

Benefits of Python?
Python is consistently rated as one of the world's most popular programming languages.
Python is fairly easy to learn, so if you are starting to learn any programming language then
Python could be your great choice. Today various Schools, Colleges and Universities are

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

teaching Python as their primary programming language. There are many other good
reasons which makes Python as the top choice of any programmer:

• Python is Open Source which means its available free of cost.


• Python is simple and so easy to learn
• Python is versatile and can be used to create many different things.
• Python has powerful development libraries include AI, ML etc.
• Python is much in demand and ensures high salary
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:

• Python is Interpreted − Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it. This is similar to PERL and
PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
• Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
• Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers to games.

History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.

Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk,
and Unix shell and other scripting languages.

Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public
License (GPL).

For many uninitiated people, the word Python is related to a species of snake. Rossum though attributes
the choice of the name Python to a popular comedy series Monty Python's Flying Circus on BBC.

Who Invented Python?

Python was invented by a Dutch Programmer Guido Van Rossum in the late 1980s. And, Python's
first version (0.9.0) was released in 1991.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Chapter 2
Anatomy of python program with example
1. Shebang Line (Optional)
• In Unix-based systems, a Python script can start with a shebang line (#!) to indicate
the interpreter to be used.
EXAMPLE
#!/usr/bin/env python3
Python Basic Guide
Python has a simple and readable syntax, making it an excellent language for beginners.
Here are some basics of Python syntax:
Comments
Comments in Python start with the # symbol and are used to explain code or make
notes. Comments are ignored by the Python interpreter.
EXAMPLE
# This is a comment
print("Hello, World!") # This is another comment
Variables
Variables are used to store data. In Python, you don’t need to declare the data type of a
variable explicitly. Python will automatically infer the data type based on the value
assigned to the variable.
x = 10 # Integer
y = 3.14 # Float
name = "John" # String
Data Types
Python supports various data types, including integers, floats, strings, lists, tuples,
dictionaries, and more.
• Integers: Whole numbers without decimals.
• Floats: Numbers with decimals.
• Strings: Text enclosed in single or double quotes.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

• Lists: Ordered collections of items.


• Tuples: Immutable collections of items.
• Dictionaries: Key-value pairs.
Indentation
Python uses indentation to define blocks of code, such as loops and functions. Use four
spaces for indentation. Incorrect indentation can lead to syntax errors.
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
Operators
Python supports various operators, including arithmetic, comparison, logical, and
assignment operators.
• Arithmetic operators: +, -, *, /, %, ** (exponentiation), // (floor division).
• Comparison operators: ==, !=, <, >, <=, >=.
• Logical operators: and, or, not.&&|
• Assignment operators: =, +=, -=, *=, /=, %=, **=, //=.
• Bitwise operators: &, |, ^, ~, <<, >>.
• Strings: Strings can be enclosed in single or double quotes. You can use
the + operator to concatenate strings.
greeting = "Hello"
name = "John"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, John!
Control Flow
Python supports various control flow structures, such as if-else statements, loops, and
more.
• If-else statement
if x > 10:
print("x is greater than 10")

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

else:
print("x is less than or equal to 10")
• For Loops
for var in iterable: # statements
• While Loop
while expression:
statement(s)
Functions
Functions are blocks of code that perform a specific task. You can define your own
functions using the def keyword.
Example Code
def greet(name):
print(f"Hello, {name}!")
greet("GeeksforGeeks") # Output: Hello, GeeksforGeeks!
Remember, Python is a dynamically typed language, so you don’t need to declare the
data type of a variable explicitly. Python also uses whitespace (indentation) to
define blocks of code, which is different from many other programming languages.
Class Definitions (If Any)
• Classes allow you to define your own data types and are essential for object-
oriented programming.
python
Copy code
class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return PI * self.radius * self.radius
Module Imports
• This section includes the import statements for any modules or packages you need.
import math

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

import os

1. Syntax Errors: Occur when the code does not follow the correct syntax rules of
Python. These errors are detected by the interpreter before execution.
Python Example
print("Hello, world!"
In this case, the missing closing parenthesis causes a syntax error.
2. Runtime Errors: Happen during program execution, typically due to invalid
operations or incorrect data types. These errors stop the program and need to be handled
to prevent crashes.
Example:
python
x = 10 / 0
Attempting to divide by zero results in a ZeroDivisionError at runtime.
Both types of errors need to be addressed to ensure smooth execution and correct behavior of
Python programs.
Logical Errors:
Occur when the code runs without errors but produces incorrect results due to incorrect
logic.
Example:
Python code
def add_numbers(a, b):
return a - b # Should be a + b
print(add_numbers(5, 3)) # Outputs 2 instead of 8
Name Errors:
Happen when trying to use a variable or function that hasn’t been defined.
Example:
python
print(undeclared_variable) # NameError because 'undeclared_variable' is not defined

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

PYTHON PROGRAMMING PRACTICE NOTES


print ("WELL TO DIT")

Comments Comments in Python start with the # symbol and are used to explain code or
make notes. Comments are ignored by the Python interpreter.
#This SHOWS TO PRINT THE hellow word
print adasdasfasfnsdjnsdjkhsdjs

Variables
Variables are used to store data. In Python, you don’t need to declare the data type of a
variable explicitly. Python will automatically infer the data type based on the value
assigned to the variable.
x = 15 # Integer
y = 3.14 # Float
name = "John" # String

Data Types
Python supports various data types, including integers, floats, strings, lists, tuples,
dictionaries, and more.
Integers: Whole numbers without decimals. Floats: Numbers with decimals. Strings: Text
enclosed in single or double quotes. Lists: Ordered collections of items. Tuples: Immutable
collections of items. Dictionaries: Key-value pairs.
Operators
greeting = 'Hello'
name = "John"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, John!

Control Flow Python supports various control flow structures, such as if-else statements,
loops, and more. If else structure
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")

Functions
def greet(name):
print(f"Hello, {name}!")
greet("GeeksforGeeks") # Output: Hello, GeeksforGeeks!

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

** Class Definitions** (If Any) Classes allow you to define your own data types and are
essential for object-oriented programming.
class Circle:
def __init__(self, radius):
self.radius = radius

def area(self):
return PI * self.radius * self.radius

Syntax Error
print("Hello, World!")

print("sdnasilfheilfnsdkfn4i9o5348o5y348y63p49tu3p4otnk3n4t")

1. Missing Colon in a Function Definition


In this example, the colon (:) is missing at the end of the def line. The error message will
likely be SyntaxError: invalid syntax.
def greet(name)
print("Hello, " + name)

Indentation Error
This code will produce an IndentationError because the print statement inside the if block
is not properly indented.
if 5 > 3:
print("5 is greater than 3")

Unclosed String
In this example, the string is not closed with a quotation mark. The interpreter will raise a
SyntaxError, typically indicating something like SyntaxError: EOL while scanning string
literal.
message = "This is an unclosed string"
print(message)

Run Time Error


Division by Zero This program will raise a ZeroDivisionError because dividing by zero is
undefined.
a = 15 #
b = 50
result1 = a + b
print(result1)

Accessing an Undefined Variable This program will raise a NameError because the
variable x has not been defined before being used.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

z=4214ahmed
print(z)

** Index Out of Range** This program will raise an IndexError because it attempts to access
an index that is out of range for the list numbers. The list only has three elements, so
numbers[5] is invalid.
numbers = [1, 2, 3, 4, 5]
print(numbers[5])

logical errors:
Incorrect Calculation of Average Logical Error: The formula for calculating the average is
incorrect. The +1 should not be added after dividing the sum by the length. This results in a
wrong average.
numbers = [100, 100, 50] #
average = sum(numbers) / len(numbers) +3 #
print("Average:", average)

Wrong Condition in an if Statement Logical Error: The condition age > 18 is incorrect if
the intention is to check if someone is an adult. In most places, someone who is 18 years old
is considered an adult, so the condition should be age >= 18.
age = 15
if age >= 18:
print("You are an mature.")
else:
print("You are not an mature.")

** Incorrect Loop Range** Logical Error: If the intention is to print even numbers from 2 to
18, the loop should start from 0, or the range should be adjusted to range(1, 11). As
written, it prints 2 to 18, but misses 20 because range(1, 10) ends at 9.
for i in range(1, 10):
print(i * 2)

import math

def calculate_area(r):
area = math.pi * r * r
return area

# Example usage
radius = float(input("Enter the radius of the circle: "))
area = calculate_area(radius)
print(f"The area of the circle with radius {radius} is {area}")

# Given radius
radius = 8.0

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Calculate the area using the formula area = r * r * 3.14


area = radius * radius * 3.14

# Print the area


print("The area of the circle is:", area)

y=1
radius = 1.0
x=y**(3/2)+3*2
area=radius*radius*3.14159
print(area)

Y=5
x=Y**+3+3
print(x)

x=5*(3/2)+3*2
print(x)

X=a
1==X

a=10
b=100
c=a+b
print(c)

x,y,z=1,2,3
print(x)
print(y)
print(z)

x,y,z=1,2,3
print(x,y,z)

x,y,z="khalid","Series","Book"
print( x,y,z)

x=3.645
print(type(x))

x=3
print(x)

# Print a message to prompt the user


print("Please enter the first number:")
# Take input from the user for the first number
n = str(input())
print(n)

# Print a message to prompt the user


print("Please enter the first number:")

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Take input from the user for the first number


num1 = int(input())

# Print a message to prompt the user


print("Please enter the second number:")
# Take input from the user for the second number
num2 = int(input())

# Calculate the sum of the two numbers


sum_result = num1 + num2

# Print the result


print("The sum of", num1, "And", num2, "is:", sum_result)

# Print a message to prompt the user


print("Please enter the first number:")
# Take input from the user for the first number
num1 = float(input())
# Print a message to prompt the user
print("Please enter the 2nd number:")
# Take input from the user for the first number
num2 = float(input())
# Calculate the sum of the two numbers
result = num1 + num2
print("the sum two number is",result)

# Print a message to prompt the user


print("Please enter the first number:")
# Take input from the user for the first number
num1 = int(input())
# Print a message to prompt the user
print("Please enter the 2nd number:")
# Take input from the user for the first number
num2 = float(input())

# Print a message to prompt the user


print("Please enter the first number:")
# Take input from the user for the first number
num1 = int(input())
# Print a message to prompt the user
print("Please enter the 2nd number:")
# Take input from the user for the first number
num2 = int(input())
# Calculate the sum of the two numbers
result = num1 + num2
print("the sum two number is",result)

print(4/2)

print(2/4)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

print(4//2)

print(2/4)

pi=3.14
print(type(pi))
num = int(pi)
print("integer number:",num)
print(type(num))

x=19
y=15
a=10
b=20
print(0<a)
print(a<100)
print(0<a and a<100)
print(0<a or a<100)
print(a<x<b)

a=40
b=30
x=20
print(0<a)
print(a<100)
print(0<a and a<100)
print(0<a or a<100)
print(a<x<b)

variable
x=5
y="khalid series"
print('x=',y)

radius= 2.0
area=radius*radius*3.14
print(area,radius )

operator
print(10/5)

print(10//5)

print(5*5)

print(2**3)

print(79%100)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

print(7%2)

Coversion
p=8
num=str(p)
print(num)

p=6.9 #
n=(p)
print(n)

Single-Line Comments A single-line comment starts with a # symbol and extends to the
end of the line.
# This is a single-line comment
print("Hello, World!") # This prints a greeting message

Multi-Line Comments Python does not have a built-in syntax for multi-line comments like
other languages. However, you can achieve the same effect by using multiple single-line
comments or by using triple-quoted strings (''' or """). Triple-quoted strings are typically
used for docstrings (documentation strings), but they can also serve as multi-line
comments if they are not used as docstrings.
# This is a multi-line comment
# It spans multiple lines
# Each line begins with a `#` symbol
print("Python is fun!")

Using Triple-Quoted
"""
This is a multi-line comment.
It uses triple quotes to span
multiple lines.
"""

print("Python is powerful!")

Skipping a Line of Code


x = 10
y = 20 # This line is commented out and won't be executed
z = 30

print(x + y) # This will print 40

Example 2: Debugging by Commenting Out Code

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

def calculate_area(radius):
# pi = 3.14 # Using a fixed value for pi
pi = 3.14159 # Using a more precise value for pi
area = pi * (radius ** 2)
return area

# print(calculate_area(5)) # Commented out to prevent execution

result = calculate_area(5)
print(result) # This will print the area using the more precise value of pi

** Commenting Out Multiple Lines of Code**


x = 5
y = 10

# if x > y:
# print("x is greater than y")
# else:
# print("x is not greater than y")

print("Comparison skipped.") # This line will be executed

# option = "A"
option = "B"

if option == "A":
print("Option A selected")
elif option == "B":
print("Option B selected")
# elif option == "C":
# print("Option C selected")

Chapter 4 Practical
String In Python, a string is a sequence of characters enclosed in either single quotes ('...'),
double quotes ("..."), or triple quotes ('''...''' or """..."""). Strings are used to represent text
data, such as words, sentences, or any other characters.
Examples of Strings in Python 1. Single-Quoted String
s= 'Hello, World two'
print(s)

s= 'Hello, World two'


print(s)

2. Double-Quoted String
double_quoted = "Python is fun!"
print(double_quoted)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

3. Triple-Quoted String (Multi-Line) Triple-quoted strings are often used for multi-line
strings or docstrings.
multi_line_string = """This is a string
that spans multiple lines.
It's very useful for long text."""
print(multi_line_string)

t3 = """This is a string
that spans multiple lines.
It's very useful for long text."""
print(t3)

String Operations 1. Concatenation You can concatenate (join) two or more strings using
the + operator.
name1 = "ahmed"
name2 = "SAMAR"
combine = name1 + "," + name2 + "!"
print(combine)

string1 = "hellow"
string2 = "wolrd"
combine = string1 + "," + string2 + "!"
print(combine)

# Example 1: Combine two strings


combine_1 = "Hello, " + "world!"
print(combine_1) # Output: Hello, world!

# Example 2: Combine three strings


combine_2 = "Python " + "is " + "awesome!"
print(combine_2) # Output: Python is awesome!

# Example 3: Combine string with a variable


name = "Alice"
combine_3 = "Hello, " + name + "!"
print(combine_3) # Output: Hello, Alice!

# Example 1: Combine two strings


combine_1 = "Hello, " + "world!"
print(combine_1) # Output: Hello, world!

# Example 2: Combine three strings


combine_2 = "Python " + "is " + "awesome!"
print(combine_2) # Output: Python is awesome!

# Example 3: Combine string with a variable


name = "Alice"
combine_3 = "Hello," + name + "!"
print(combine_3) # Output: Hello, Alice!

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

2. Repetition You can repeat a string multiple times using the * operator.
words = "Python! "
multiply= words * 100
print(multiply)

# Example 1: Repeat a string 3 times


repeat_1 = "Hello! " * 3
print(repeat_1) # Output: Hello! Hello! Hello!

# Example 2: Repeat a string 5 times


repeat_2 = "Python " * 5
print(repeat_2) # Output: Python Python Python Python Python

# Example 3: Repeat a string 2 times


repeat_3 = "Repeat " * 2
print(repeat_3) # Output: Repeat Repeat

# Example 3: Repeat a string 2 times


repeat_3 = "Repeat " * 3
print(repeat_3) # Output:

3. Indexing You can access individual characters in a string using indexing (starting from
0).
word = "Python"
first_letter = word[1]
print(first_letter)

4. Slicing You can extract a substring using slicing.


word = "Python"
slice_word = word[0:4] # Extracts 'Pyth'
print(slice_word)

String Length You can find the length of a string using the len() function. 1. len() The len()
function returns the length of a string, which is the number of characters it contains.
Examples:
length = len("Hello, World!")
print(length)

# Example 1: Length of a short string


length_1 = len("Hello")
print(length_1) # Output: 5

# Example 2: Length of an empty string


length_2 = len("")
print(length_2) # Output: 0

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 3: Length of a sentence


length_3 = len("Python programming is fun!")
print(length_3) # Output: 27

# Example 1: Length of a short string


length_1 = len("Hello123")
print(length_1)

# Example 2: Length of an empty string


length_2 = len("abx")
print(length_2)

# Example 3: Length of a sentence


length_3 = len("Python programming is fun!")
print(length_3)

Capitalize Converting the first character of a string to uppercase.


# Example 1: Capitalize a word
capitalize_1 = "python".capitalize()
print(capitalize_1) # Output: Python

# Example 2: Capitalize a sentence (only the first letter of the first word i
s capitalized)
capitalize_2 = "hello, world!".capitalize()
print(capitalize_2) # Output: Hello, world!

# Example 3: Capitalize a string with multiple words (only first word is affe
cted)
capitalize_3 = "this is a test.".capitalize()
print(capitalize_3) # Output: This is a test.

# Example 1: Capitalize a word


capitalize_1 = "abbottabad".capitalize()
print(capitalize_1)

# Example 2: Capitalize a sentence (only the first letter of the first word i
s capitalized)
c2 = "hello, world!".capitalize()
print(c2)

# Example 3: Capitalize a string with multiple words (only first word is affe
cted)
capitalize_3 = "this is a test.".capitalize()
print(capitalize_3)

string1 = "print1"
print(string1.capitalize())

2. lower() The lower() method converts all the characters in a string to lowercase.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 1: Lowercase a single word


lower_1 = "HELLO".lower()
print(lower_1) # Output: hello

# Example 2: Lowercase a sentence


lower_2 = "Python Is FUN!".lower()
print(lower_2) # Output: python is fun!

# Example 3: Lowercase a mixed case string


lower_3 = "MixedCase".lower()
print(lower_3) # Output: mixedcase

# Example 2: Lowercase a sentence


lower_2 = "Python Is FUN!".lower()
print(lower_2) # Output:

# Example 1: Lowercase a single word


lower_1 = "HELLO1".lower()
print(lower_1)

# Example 3: Lowercase a mixed case string


lower_3 = "Mixed Case".lower()
print(lower_3)

3. upper() The upper() method converts all the characters in a string to uppercase.
# Example 1: Uppercase a single word
upper_1 = "hello".upper()
print(upper_1) # Output: HELLO

# Example 2: Uppercase a sentence


upper_2 = "Python is fun!".upper()
print(upper_2) # Output: PYTHON IS FUN!

# Example 3: Uppercase a mixed case string


upper_3 = "MixedCase".upper()
print(upper_3) # Output: MIXEDCASE

# Example 1: Uppercase a single word


upper_1 = "hello".upper()
print(upper_1)

# Example 2: Uppercase a sentence


upper_2 = "Python is fun!".upper()
print(upper_2)

# Example 3: Uppercase a mixed case string


upper_3 = "MixedCase".upper()
print(upper_3)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

strip() The strip() method removes any leading (spaces at the beginning) and trailing
(spaces at the end) whitespace characters from a string.
# Example 1: Strip leading and trailing spaces
strip_1 = " Hello, World! ".strip()
print(strip_1) # Output: "Hello, World!"

# Example 2: Strip leading spaces only


strip_2 = " Leading spaces".strip()
print(strip_2) # Output: "Leading spaces"

# Example 3: Strip trailing spaces only


strip_3 = "Trailing spaces ".strip()
print(strip_3) # Output: "Trailing spaces"

# Example 1: Strip leading and trailing spaces


strip_1 = " Hello, World! ".strip()
print(strip_1) #

# Example 2: Strip leading spaces only


strip_2 = " Leading spaces"
print(strip_2.strip()) # Output:

# Example 3: Strip trailing spaces only


strip_3 = "Trailing spaces ".strip()
print(strip_3) # Output: "Trailing spaces"

5. replace() The replace() method replaces a specified substring within a string with
another substring.
Examples:
# Example 1: Replace a word
replace_1 = "Hello, World!".replace("World", "Python")
print(replace_1) # Output: "Hello, Python!"

# Example 2: Replace a character


replace_2 = "apple".replace("p", "b")
print(replace_2) # Output: "abble"

# Example 3: Replace multiple occurrences


replace_3 = "banana".replace("a", "o")
print(replace_3) # Output: "bonono"

# Example 1: Replace a word


replace_1 = "Hello, World!".replace("Hello", "Python")
print(replace_1)

# Example 2: Replace a character


replace_2 = "apple".replace("a", "c")
print(replace_2)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 3: Replace multiple occurrences


replace_3 = "banana".replace("a", "o")
print(replace_3)

startswith() The startswith() method checks if a string starts with a specified substring.
# Example 1: Check if a string starts with "Python"
starts_with_1 = "Python programming is fun".startswith("Python")
print(starts_with_1) # Output: True

# Example 2: Check if a string starts with "Hello"


starts_with_2 = "Hello, World!".startswith("Hello")
print(starts_with_2) # Output: True

# Example 3: Check if a string starts with "Goodbye"


starts_with_3 = "Good morning!".startswith("Goodbye")
print(starts_with_3) # Output: False

# Example 1: Check if a string starts with "Python"


starts_with_1 = "Python programming is fun".startswith("Python")
print(starts_with_1)

# Example 2: Check if a string starts with "Hello"


starts_with_2 = "Hello, World!".startswith("Hello")
print(starts_with_2)

# Example 3: Check if a string starts with "Goodbye"


starts_with_3 = "Good morning!".startswith("Goodbye")
print(starts_with_3)

endswith() The endswith() method checks if a string ends with a specified substring.
Examples:
# Example 1: Check if a string ends with "fun"
ends_with_1 = "Python programming is fun".endswith("fun")
print(ends_with_1) # Output: True

# Example 2: Check if a string ends with "World!"


ends_with_2 = "Hello, World!".endswith("World!")
print(ends_with_2) # Output: True

# Example 3: Check if a string ends with "morning"


ends_with_3 = "Good night!".endswith("morning")
print(ends_with_3) # Output: False

# Example 1: Check if a string ends with "fun"


ends_with_1 = "Python programming is fun".endswith("fun")
print(ends_with_1)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 2: Check if a string ends with "World!"


ends_with_2 = "Hello, World!".endswith("World!")
print(ends_with_2)

# Example 3: Check if a string ends with "morning"


ends_with_3 = "Good night!".endswith("morning")
print(ends_with_3)

6. String Methods Python provides many built-in methods to manipulate strings, such as:
lower(): Converts all characters to lowercase. upper(): Converts all characters to
uppercase. strip(): Removes leading and trailing whitespace. replace(): Replaces a
substring with another substring. split(): Splits a string into a list of substrings.
text = " Hello, Python! "
print(text.lower()) # Output: ' hello, python! '
print(text.upper()) # Output: ' HELLO, PYTHON! '
print(text.strip()) # Output: 'Hello, Python!'
print(text.replace("Python", "World")) # Output: ' Hello, World! '
print(text.split(',')) # Output: [' Hello', ' Python! ']

string = "print"
name1="alilksjewisjuereklrjfr"
print(name1)
print(string)

Chapter 5 LIST
In Python, a list is a collection of items (or elements) that can be of different data types,
stored in a specific order. Lists are mutable, meaning you can change their content after
they are created. They are defined by placing the elements inside square brackets [],
separated by commas.
# Creating a list of integers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(numbers)

n1 = [1.1, 2.5, 3.7, 4.7, 5, 6, 7, 8, 9, 10]


print(n1[2])

# Creating a list of strings


fruits = ['apple', 'banana', 'cherry']
print(fruits)

# Creating a list with mixed data types


mixed_list = [1, "apple", 3.14, True]
print(mixed_list)

# Accessing elements in a list


print(numbers[0]) # Output: 1
print(fruits[1]) # Output: banana

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Modifying an element in a list


fruits[2] = "orange"
print(fruits) # Output: ['apple', 'banana', 'orange']

# Adding an element to a list


fruits.append("grape")
print(fruits) # Output: ['apple', 'banana', 'orange', 'grape']

# Removing an element from a list


fruits.remove("banana")
print(fruits) # Output: ['apple', 'orange', 'grape']

# Slicing a list
print(mixed_list[1:3]) # Output: ['apple', 3.14]

Forward Accessing This involves accessing elements using positive index numbers,
starting from 0 for the first element, 1 for the second, and so on.
Backward Accessing This involves accessing elements using negative index numbers,
where -1 represents the last element, -2 represents the second-to-last, and so on.
Example:
# Example list
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Forward Accessing (using positive indices)


print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
print(fruits[4]) # Output: elderberry

#example
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
# Backward Accessing (using negative indices)
print(fruits[-1]) # Output: elderberry
print(fruits[-3]) # Output: cherry
print(fruits[-5]) # Output: apple

Explanation: Forward Accessing: bold text


fruits[0] gives you the first element: "apple". fruits[2] gives you the third element: "cherry".
fruits[4] gives you the fifth element: "elderberry". Backward Accessing:
fruits[-1] gives you the last element: "elderberry". fruits[-3] gives you the third-to-last
element: "cherry". fruits[-5] gives you the first element: "apple".
1. Changing an Element in a List Definition: Changing an element in a list involves
updating the value of an existing element at a specific index.
Example:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example list
students = ["Maliaka", "Maira", "Alishba"]
# Change the second element (index 1) from "banana" to "orange"
students[2] = "samiya"
print(students)

Explanation: The element at index 1, which was "banana", is replaced with "orange".
2. Removing an Element from a List Definition: Removing an element from a list involves
deleting an element from the list, either by specifying the element itself or by its index.
Example:
# Example list
fruits = ["apple", "banana", "cherry"]

# Remove the element "banana" from the list


fruits.remove("banana")

print(fruits) # Output: ['apple', 'cherry']

# Alternatively, remove the element at index 1 (which is now "cherry")


del fruits[1]

print(fruits) # Output: ['apple']

# Example list
fruits = ["apple", "banana", "cherry"]

# Remove the element "banana" from the list


fruits.remove("banana")

print(fruits) # Output: ['apple', 'cherry']

del fruits[1]

print(fruits) # Output: ['apple']

# Example list
students = ["ali", "ahmed", "shahban"]

# Remove the element "banana" from the list


students.remove("shahban")

print(students) # Output:

Explanation: The first remove("banana") deletes the "banana" element, and del fruits[1]
removes the element at index 1.
3. Adding an Element to a List Definition: Adding an element to a list involves inserting a
new element at the end of the list or at a specific index.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Example:
# Example list
fruits = ["apple", "banana"]

# Add an element "cherry" to the end of the list


fruits.append("cherry")

print(fruits) # Output: ['apple', 'banana', 'cherry']

# Insert an element "orange" at index 1


fruits.insert(1, "orange")

print(fruits) # Output: ['apple', 'orange', 'banana', 'cherry']

# Example list
fruits = ["apple", "banana"]

# Add an element "cherry" to the end of the list


fruits.append("cherry")

print(fruits) # Output: ['apple', 'banana', 'cherry']

# Example list
fruits = ["apple", "banana"]
# Insert an element "orange" at index 1
fruits.insert(1, "orange")

print(fruits) # Output: ['apple', 'orange', 'banana',]

Explanation:
The append("cherry") method adds "cherry" to the end of the list. The insert(1, "orange")
method inserts "orange" at index 1, shifting the other elements to the right.
List slicing is a technique in Python that allows you to access a portion (or "slice") of a list
by specifying a range of indices. Slicing returns a new list that includes elements from the
start index up to, but not including, the end index.
list_name[start:end:step]

start: The index where the slice starts (inclusive). If omitted, it defaults to 0. end: The index
where the slice ends (exclusive). If omitted, it defaults to the length of the list. step: The
step size between each index in the slice. If omitted, it defaults to 1
# Example list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slice from index 2 to 5

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

slice1 = numbers[2:6]
print(slice1) # Output: [2, 3, 4, 5]

# Slice from the beginning to index 4


slice2 = numbers[:6]
print(slice2) # Output: [0, 1, 2, 3, 4]

# Slice from index 5 to the end


slice3 = numbers[5:]
print(slice3) # Output: [5, 6, 7, 8, 9]

# Slice the entire list with a step of 2 (every second element)


slice4 = numbers[::2]
print(slice4) # Output: [0, 2, 4, 6, 8]

# Slice with a negative step (reversing the list)


slice5 = numbers[::-1]
print(slice5) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

# Example list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slice from index 2 to 5


slice1 = numbers[2:6]
print(slice1)

# Example list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from the beginning to index 4
slice2 = numbers[:5]
print(slice2)

# Example list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Slice from the beginning to index 4
slice2 = numbers[5:]
print(slice2) # Output:

# Example list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Slice the entire list with a step of 2 (every second element)
slice4 = numbers[::3]
print(slice4)

:5 5: ::5 ::-5
# Example list
numbers = [2, 4, 6, 8, 10]
# Slice with a negative step (reversing the list)
slice5 = numbers[-4:]
print(slice5)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example list
numbers = [2, 4, 6, 8, 10]
# Slice with a negative step (reversing the list)
slice5 = numbers[:-4]
print(slice5)

Explanation: Slice from index 2 to 5: numbers[2:6] gives you the elements from index 2 up
to 5, which are [2, 3, 4, 5]. Slice from the beginning to index 4: numbers[:5] gives you the
first five elements, [0, 1, 2, 3, 4]. Slice from index 5 to the end: numbers[5:] gives you all
elements starting from index 5 to the end, [5, 6, 7, 8, 9]. Slice with a step of 2: numbers[::2]
selects every second element, resulting in [0, 2, 4, 6, 8]. Slice with a negative step:
numbers[::-1] reverses the list.
Membership Operators in Python Membership operators are used to test whether a
specific value is a member of a sequence (such as a list, string, tuple, etc.). There are two
membership operators in Python:
in: Returns True if the specified value is found in the sequence. not in: Returns True if the
specified value is not found in the sequence. Examples
1. Using in Operator
# Example list
fruits = ["apple", "banana", "cherry"]

# Check if "banana" is in the list


result = "banana" in fruits
print(result) # Output: True

# Check if "grape" is in the list


result = "grape" in fruits
print(result) # Output: False

# Example list
fruits = ["apple", "banana", "cherry"]

# Check if "banana" is in the list


result = "banana1" in fruits
print(result) # Output: True

# Example list
fruits = ["apple", "banana", "cherry"]

result = "grape" in fruits


print(result) #

Explanation: "banana" in fruits returns True because "banana" is an element of the fruits
list. "grape" in fruits returns False because "grape" is not an element of the fruits list.
2. Using not in Operator

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example list
fruits = ["apple", "banana", "cherry"]

# Check if "banana" is not in the list


result = "banana" not in fruits
print(result) # Output: False

# Example list
fruits = ["apple", "banana", "cherry"]
# Check if "grape" is not in the list
result = "grape" not in fruits
print(result) # Output: True

Explanation:
"banana" not in fruits returns False because "banana" is indeed in the list. "grape" not in
fruits returns True because "grape" is not in the list. Summary in: Checks for the presence
of an element in a sequence. not in: Checks for the absence of an element in a sequence.
These operators are commonly used in conditional statements to perform actions based on
whether an element exists in a sequence or not.

Chapter 6
conditional statement A conditional statement in Python allows the program to execute a
certain block of code only if a specified condition is true. The most common conditional
statement is the if statement.
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")

age = 18
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Explanation: The if statement checks the condition age >= 18. If it's true, it executes the
first block (print("You are eligible to vote.")). If the condition is false, the else block is
executed.
if statement An if statement in Python is used to test a condition. If the condition evaluates
to True, the code inside the if block will be executed. If the condition is False, the program
skips the if block and continues executing the code that follows. Syntax:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

if condition:
# Code to execute if the condition is True

Example:
age = 20
if age >= 18:
print("You are eligible to vote.")

temperature = 30
if temperature > 25:
print("It's a hot day!")

Explanation: The if statement checks the condition temperature > 25. If the condition is
true (in this case, if the temperature is greater than 25), it executes the code inside the
block and prints: "It's a hot day!" If the condition is false (temperature is less than or equal
to 25), the program simply skips the block without printing anything. The if statement
allows the program to make decisions based on conditions.
In Python, the if and else statements are used to perform conditional operations.
The if statement evaluates a condition. If the condition is true, the code inside the if block
runs. The else statement provides an alternative action if the condition in the if statement is
false. Example:
number = 10

if number > 11:


print("The number is positive.")
else:
print("The number is not positive.")

Explanation: The if statement checks if number > 0. If the condition is true, it executes the
code inside the if block and prints: "The number is positive." If the condition is false, the
else block runs, printing: "The number is not positive." This allows the program to choose
between two possible outcomes based on the condition.
Indentation in Python refers to the spaces or tabs at the beginning of a line of code. In
Python, indentation is used to define the structure and flow of the program, such as
grouping code into blocks for loops, conditional statements, and functions.
Unlike many other programming languages that use curly braces {} or keywords to group
code, Python uses indentation to indicate which statements belong to the same block of
code. This is mandatory, and incorrect indentation will result in errors.
Example:
if 5 > 2:
print("5 is greater than 2") # This line is indented, so it belongs to
the 'if' block
print("This is part of the same block") # Same indentation level, so p

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

art of the same block


else:
print("This is in the 'else' block") # Indented, so belongs to the 'el
se' block

Key Points: Consistent Indentation: All lines within the same block must have the same
level of indentation. Syntax Requirement: Python will raise an IndentationError if
indentation is inconsistent or missing.
else statement The else statement in Python is used to define a block of code that will run
if the condition in the if statement is False. It provides an alternative action when the if
condition is not met.
Syntax:
if condition:
# Code to execute if the condition is True
else:
# Code to execute if the condition is False

Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Explanation: The if statement checks the condition age >= 18. If the condition is True (if
the age is 18 or older), the first block runs and prints: "You are eligible to vote." If the
condition is False (if the age is less than 18), the else block runs and prints: "You are not
eligible to vote." The else statement ensures that an alternative action is performed when
the condition in the if statement is not satisfied.
age = 18

if age >= 18:


print("You are an Mature.")
else:
print("You are a minor.")

num = 7

if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

elif statement The elif statement in Python stands for "else if" and is used to check
multiple conditions in a sequence. It allows the program to test multiple expressions for
True and execute the corresponding block of code for the first condition that evaluates to
True. If none of the conditions are true, an optional else block can be used to handle the
case where no conditions are met.
Syntax:
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if none of the above conditions are True

marks = 40
if marks >= 90:
print("Grade: A1")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: c")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: F")

Topic 1: Elif Statement Example 1: Grading System


marks = 0
if marks >= 90:
print("Grade: A1")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: c")
elif marks >= 50:
print("Grade: D")
else:
print("Grade: F")

# Example 1: Grading System


marks = 75

if marks >= 90:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"

print(f"Your grade is: {grade}")

temperature = 30
if temperature > 30:
print("It's hot outside.")
elif temperature < 15:
print("It's cold outside.")
else:
print("The weather is moderate.")

Example 2: Weather Condition


# Example 2: Weather Condition
weather = "rainy"

if weather == "sunny":
print("Let's go for a picnic!")
elif weather == "rainy":
print("Don't forget your umbrella.")
elif weather == "cloudy":
print("It might rain later.")
else:
print("Stay indoors!")

Example 3: Age Group Classification


# Example 3: Age Group Classification
age = 12

if age < 13:


category = "Child"
elif age < 20:
category = "Teenager"
elif age < 65:
category = "Adult"
else:
category = "Senior"

print("You are classified as: {category}")

Example 4: Day of the Week

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 4: Day of the Week


day = 9

if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
elif day == 4:
print("Thursday")
elif day == 5:
print("Friday")
elif day == 6:
print("Saturday")
elif day == 7:
print("Sunday")
else:
print("Invalid day number.")

Example 5: Simple Calculator


# Example 5: Simple Calculator
operation = "add"
num1 = 10
num2 = 5

if operation == "add":
result = num1 + num2
elif operation == "subtract":
result = num1 - num2
elif operation == "multiply":
result = num1 * num2
elif operation == "divide":
result = num1 / num2
else:
result = "Invalid operation"

print(f"The result is: {result}")

Explanation: The if statement checks if marks >= 90. If it's True, it prints "Grade: A". If the
first condition is False, the program checks the next condition with elif marks >= 80. If this
is True, it prints "Grade: B". The program continues checking subsequent elif conditions
until one is True. If none of the if or elif conditions are met, the else block runs, printing
"Grade: D". The elif statement helps handle multiple conditions efficiently.
number = 0

if number > 0:
print("The number is positive.")

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

elif number < 0:


print("The number is negative.")
else:
print("The number is zero.")

AND logical operator


The and logical operator in Python is used to combine two or more conditions. It returns
True only if both conditions are true. If either condition is false, the result will be False.
Syntax:
if condition1 and condition2:
# Code to execute if both conditions are True

AND Logical Operator Examples


age= 15
CNIC = True
if age >= 18 and CNIC:
print("You are allowed to enter in ETEA TEST.")
else:
print("You are not allowed to enter in ETEA TEST.")

Explanation: The if statement checks two conditions: age >= 18 (True) has_ID (True) Since
both conditions are True, the block of code inside the if statement is executed, and it prints:
"You are allowed to enter." If either condition were false (for example, age < 18 or has_ID =
False), the program would skip the if block and execute the else block, printing: "You are
not allowed to enter." The and operator is useful when you need multiple conditions to be
true for a block of code to execute.
Example 2: Check Eligibility for a License
# Example 1: Check Eligibility for a License
age = 20
passed_test = True

if age >= 18 or passed_test:


print("You are eligible for a driving license.")
else:
print("You are not eligible for a driving license.")

Example 2: Student Enrollment


# Example 2: Student Enrollment
gpa = 3.5
extracurriculars = True

if gpa >= 3.0 or extracurriculars:


print("You can enroll in the honors program.")

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

else:
print("You do not meet the criteria for enrollment.")

# Example 1: Checking if a number is between 10 and 20


num = 15
if num > 10 and num < 20:
print(f"{num} is between 10 and 20")

# Example 2: Checking if both conditions are true


age = 25
has_license = True
if age > 18 and has_license:
print("You are allowed to drive")

# Example 3: Checking if a string has both characters


password = "python123"
if "p" in password and "1" in password:
print("Password contains both 'p' and '1'")

# Example 4: Checking multiple conditions


temperature = 22
humidity = 60
if temperature >= 20 and humidity <= 70:
print("The weather is comfortable")

# Example 5: Checking for pass in multiple subjects


maths = 85
science = 90
if maths >= 40 and science >= 40:
print("Passed both subjects")

# Example 2: Checking if both conditions are true


age = 25
has_license = True
if age > 18 and has_license:
print("You are allowed to drive")

# Example 1: Checking if a number is between 10 and 20


num = 15
if num >= 10 and num < 20:
print(f"{num} is between 10 and 20")

# Example 3: Checking if a string has both characters


password = "python123"
if "p" in password and "1" in password:
print("Password contains both 'p' and '1'")

# Example 4: Checking multiple conditions


temperature = 22
humidity = 60
if temperature >= 20 and humidity <= 70:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 5: Checking for pass in multiple subjects


maths = 35
science = 90
if maths >= 40 or science >= 40:
print("Passed both subjects")

OR logical operator
The or logical operator in Python is used to combine two or more conditions. It returns
True if at least one of the conditions is true. If both conditions are false, the result will be
False.
Syntax:
if condition1 or condition2:
# Code to execute if at least one condition is True

Example:
age = 78
has_permission = False

if age >= 18 or has_permission:


print("You are allowed to enter.")
else:
print("You are not allowed to enter.")

Explanation: The if statement checks two conditions: age >= 18 (False) has_permission
(True) Since the second condition is True, the block of code inside the if statement is
executed, and it prints: "You are allowed to enter." If both conditions were false (e.g., age <
18 and has_permission = False), the else block would run, printing: "You are not allowed to
enter." The or operator is useful when you want the code to execute if at least one of
multiple conditions is true.
# Example 1: Checking if either condition is true
has_fever = False
has_cough = True
if has_fever or has_cough:
print("You might be sick")

# Example 2: Checking if one of the conditions is satisfied


hour = 22
if hour < 9 or hour > 17:
print("Office is closed")

# Example 3: Checking for a valid password


password = "secure"
if len(password) >= 8 or "@" in password:
print("Password is strong")

# Example 4: Verifying either condition for discount

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

age = 65
is_member = False
if age > 60 or is_member:
print("You get a discount")

# Example 5: Checking eligibility for a loan


salary = 4000
credit_score = 650
if salary >= 3000 or credit_score > 700:
print("You are eligible for a loan")

# Example 1: Checking if either condition is true


has_fever = False
has_cough = True
if has_fever or has_cough:
print("You might be sick")

NOT logical operator in python


NOT logical operator in python The not logical operator in Python is used to reverse the
boolean value of a condition. It returns True if the condition is False, and False if the
condition is True.
Syntax:
if not condition:
# Code to execute if the condition is False

Example:
is_raining = True

if not is_raining:
print("You can go outside without an umbrella.")
else:
print("You need an umbrella.")

Explanation: The variable is_raining is set to False. The if not is_raining statement reverses
this condition, effectively checking if is_raining is False. Since is_raining is False, the if block
is executed, and it prints: "You can go outside without an umbrella." If is_raining were True,
the program would execute the else block and print: "You need an umbrella." The not
operator is useful when you need to check if a condition is not true.
# Example 1: Checking if a number is not zero
x = 5
if not x == 0:
print("x is not zero")

# Example 2: Negating a condition


logged_in = False
if not logged_in:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

print("You are not logged in")

# Example 3: Inverting a boolean value


is_sunny = True
if not is_sunny:
print("It is not sunny")

# Example 4: Using 'not' to check membership


students = ["Alice", "Bob", "Charlie"]
student_name = "David"
if not student_name in students:
print(f"{student_name} is not in the class")

# Example 5: Using 'not' in a nested condition


age = 15
if not age >= 18:
print("You are not an adult")

# Example 1: Checking if a number is not zero


x = 5
if not x == 0:
print("x is not zero")

# Example 2: Negating a condition


logged_in = False
if not logged_in:
print("You are logged in")

# Example 3: Inverting a boolean value


is_sunny = True
if not is_sunny:
print("It is not sunny")

# Example 4: Using 'not' to check membership


students = ["Alice", "Bob", "Charlie"]
student_name = "David"
if not student_name in students:
print(f"{student_name} is not in the class")

NESTED IF statement A nested if statement in Python is when one if statement is placed


inside another if or else block. This allows for multiple levels of condition checking, where
one condition is tested inside another condition's block.
Syntax:
if condition1:
# Code to execute if condition1 is True
if condition2:
# Code to execute if both condition1 and condition2 are True
else:
# Code to execute if condition1 is True but condition2 is False

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

else:
# Code to execute if condition1 is False

Example:
age = 19
has_ID = True

if age >= 18:


if has_ID:
print("You are allowed to enter.")
else:
print("You need an ID to enter.")
else:
print("You are not old enough to enter.")

Explanation: The outer if statement checks if age >= 18. If True, the program then
evaluates the inner if statement. The inner if checks if has_ID is True. If both conditions are
True, it prints: "You are allowed to enter." If the first condition is true but has_ID is False, it
prints: "You need an ID to enter." If age >= 18 is False, the outer else block runs, printing:
"You are not old enough to enter."
Nested if: Allows for more complex decision-making processes where multiple conditions
need to be tested in a hierarchical manner.
score = 1001

if score >= 60:


print("You passed.")
if score >= 90 and score <=100 :
print("Excellent!")
else:
print("You failed.")

# Example 1: Checking a range using nested if


num = 35
if num > 0:
if num < 50:
print(f"{num} is between 0 and 50")

# Example 2: Validating age and experience


age = 30
experience = 5
if age >= 25:
if experience >= 3:
print("Eligible for the job")

# Example 3: Checking user permissions


is_admin = True
is_active = False

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

if is_admin:
if is_active:
print("Admin access granted")
else:
print("Admin account is inactive")

# Example 4: Checking nested conditions for marks


marks = 75
if marks >= 50:
if marks >= 75:
print("Grade: A")
else:
print("Grade: B")

# Example 5: Multi-level condition checking


time = 15
if time >= 12:
if time < 18:
print("Good afternoon")
else:
print("Good evening")

# Example 1: Checking a range using nested if


num = 35
if num > 0:
if num < 50:
print(f"{num} is between 0 and 50")

# Example 2: Validating age and experience


age = 30
experience = 5
if age >= 25:
if experience >= 3:
print("Eligible for the job")

# Example 3: Checking user permissions


is_admin = True
is_active = False
if is_admin:
if is_active:
print("Admin access granted")
else:
print("Admin account is inactive")

# Example 4: Checking nested conditions for marks


marks = 77
if marks >= 50:
if marks >= 75:
print("Grade: A")
else:
print("Grade: B")

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Example 5: Multi-level condition checking


time = 15
if time >= 12:
if time < 10:
print("Good afternoon")
else:
print("Good evening")

Chapter 7 Loop
What is Loop in python? In Python, a loop is a control structure that repeatedly executes a
block of code as long as a condition is true or for a fixed number of iterations. Python
provides two main types of loops:
1. For Loop
2. while loop
1. For loop in python language
A for loop in Python is used to iterate over a sequence of elements (such as a list, tuple,
string, or a range of numbers) and execute a block of code for each element in that
sequence. It is especially useful when you know the number of iterations in advance.
The general syntax of a for loop in Python is:
for variable in iterable:
# Block of code to be executed

1. Looping Through a List You can use a for loop to iterate through the items of a list:
fruits = ["apple", "banana", "cherry", ""]
for fruit in fruits:
print(fruit)

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


for element in fruits:
print(element)

Pakistan = ["lahore", "abbottabad", "karachi", "......"]


for city in Pakistan:
print(city)

2. Looping Through a Range of Numbers The range() function is often used to loop
through a sequence of numbers. Here's how to use it in a for loop:
for i in range(0, 6): # Loops through numbers from 1 to 5
print(i)

for k in range(5, 11):


print(k)

Examples of Using for Loop with range()

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

1. Basic range(stop) Example If you only pass one argument, range(n) generates
numbers from 0 to n-1.
for i in range(10):
print(i)

range(start, stop, step) Example You can also specify the step value (i.e., how much to
increment by after each iteration).
for i in range(1, 10, 2): # Will generate numbers 1, 3, 5, 7, 9 (increments
by 2)
print(i)

for i in range(1, 20, 3):


print(i)

for n in range(10, 20, 2):


print(i)

for n in range(1, 50, 10):


print(n)

3. Looping Through a String A for loop can also iterate through the characters in a string:
name = "Pakistan"

for letter in name:


print(letter)

nested for loop A nested for loop in Python is a loop inside another loop. The inner for
loop is executed for each iteration of the outer loop, allowing you to iterate over multi-
dimensional data or perform more complex iteration patterns.
Structure of a Nested for Loop
for outer_variable in outer_iterable:
for inner_variable in inner_iterable:
# Block of code

Python Program Using Nested for Loop


fruits = ["apple", "banana", "cherry"]
adjectives = ["sweet", "ripe", "juicy"]

# Nested for loop to pair each fruit with each adjective


for fruit in fruits:
for adjective in adjectives:
print(f"The {adjective} {fruit}")

Examples of Nested for Loops:


1. Basic Nested for Loop Example In this example, we loop through two ranges using a
nested for loop.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

for i in range(3): # Outer loop


for j in range(2): # Inner loop
print(f"i = {i}, j = {j}")

Nested for Loop You can nest one for loop inside another to handle multi-dimensional
data, like a list of lists.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

for row in matrix:


for element in row:
print(element, end=" ")
print() # Print a new line after each row

2. Multiplication Table Using Nested for Loop A common use case for nested loops is
generating a multiplication table.
for i in range(1, 6): # Outer loop controls the rows
for j in range(1, 6): # Inner loop controls the columns
print(i * j, end=" ")
print() # Newline after each row

while loop in python


A while loop in Python repeatedly executes a block of code as long as a specified condition
remains True. The loop will continue to run until the condition becomes False. Structure of
a while loop:
while condition:
# Block of code to execute

The condition is evaluated before each iteration. If the condition is True, the block of code
inside the loop runs. Once the condition becomes False, the loop stops.
Examples of while Loops:
1. Basic while Loop This example demonstrates a simple while loop that runs as long
as a counter variable is less than or equal to 5.
i = 0
while i <= 10:
print(i)
i += 2 # Increment the counter to avoid infinite loop

j = 1
while j <= 10:
print(j)
j += 2 # Increment the counter to avoid infinite loop

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

j = 1
while j <= 20:
print(j)
j += 5 # Increment the counter to avoid infinite loop

Write a program, a user enters any number between 100 and 500. the program asks the
user to enter the correct input until the user enters the number within a given range in the
program
Here's a Python program that continuously asks the user to enter a number between 100
and 500. The program keeps prompting the user until they enter a valid number within this
range:
# Program to validate user input within the range of 100 to 500

# Ask for user input


number = int(input("Enter a number between 100 and 500: "))

# While the number is not in the correct range, keep asking for input
while number < 100 or number > 500:
print("Invalid input. Please try again.")
number = int(input("Enter a number between 100 and 500: "))

# Once a valid number is entered, print a confirmation


print(f"Thank you! You entered {number}, which is within the range.")

# Program to validate user input within the range of 100 to 500

# Ask for user input


number = int(input("Enter a number between 100 and 500: "))

# While the number is not in the correct range, keep asking for input
while number < 100 or number > 500:
print("Invalid input. Please try again.")
number = int(input("Enter a number between 100 and 500: "))

# Once a valid number is entered, print a confirmation


print(f"Thank you! You entered {number}, which is within the range.")

# Program to validate user input within the range of 100 to 500

# Ask for user input


number = int(input("Enter a number between 100 and 500: "))

# While the number is not in the correct range, keep asking for input
while number < 100 or number > 500:
print("Invalid input. Please try again.")
number = int(input("Enter a number between 100 and 500: "))

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Once a valid number is entered, print a confirmation


print(f"Thank you! You entered {number}, which is within the range.")

# Program to validate user input within the range of 10 to 50

# Ask for user input


number = int(input("Enter a number between 10 and 50: "))

# While the number is not in the correct range, keep asking for input
while number < 10 or number > 50:
print("Invalid input. Please try again.")
number = int(input("Enter a number between 10 and 50: "))

# Once a valid number is entered, print a confirmation


print(f"Thank you! You entered {number}, which is within the range.")

Explanation: The program first asks the user to input a number. The while loop checks
whether the number is outside the valid range (less than 100 or greater than 500). If the
number is not within the range, it prints an error message and prompts the user to enter
the number again. Once the user enters a valid number within the range, the loop stops,
and a confirmation message is displayed.
In this loop, the condition i <= 5 is checked before each iteration, and i is incremented by 1
after each iteration. Once i becomes 6, the loop stops.
2. while Loop with break The break statement can be used to exit a while loop
prematurely, even if the loop condition is still True.
i = 1
while i <= 10:
if i == 7:
break # Exit the loop when i is 7
print(i)
i += 1

i = 1
while i <= 10:
print(i)
i += 1

In this case, the loop stops when i becomes 7 due to the break statement, even though the
condition i <= 10 is still True.
3. while Loop with continue The continue statement skips the current iteration and
moves to the next iteration without executing the rest of the loop body for that iteration.
i = 0
while i < 5:
i += 1
if i == 3:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

continue # Skip printing when i is 3


print(i)

i = 1
while i <= 10:
print(i)
i -= 1

In this example, when i equals 3, the continue statement skips the rest of the loop body, so
3 is not printed.
4. Infinite while Loop A while loop that runs indefinitely can be created when the
condition never becomes False. Infinite loops are generally avoided, but they may be useful
in some scenarios (e.g., waiting for a user input or handling server requests).
while True:
user_input = input("Enter 'exit' to stop: ")
if user_input == 'exit':
break # Exit the loop when user types 'exit'

In this example, the loop runs forever until the user types 'exit'.
5. Counting Down with a while Loop This is an example of counting down from a given
number.
count = 5
while count > 0:
print(f"Countdown: {count}")
count -= 1 # Decrease count

Sum of First N Natural Numbers This example calculates the sum of the first 5 natural
numbers using a while loop.
n = 5
total = 0
i = 1
while i <= n:
total += i
i += 1
print("Sum:", total)

1. break Statement: The break statement is used to exit a loop prematurely. It


immediately terminates the loop, and the program continues execution from the first
statement after the loop.
Syntax of the break statement:
Loop
Condition:
break

Example 1: break in a while loop

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

i = 1
while i <= 10:
if i == 5:
break # Exit loop when i equals 5
print(i)
i += 1

i = 1
while i <= 100:
if i == 50:
break # Exit loop when i equals 5
print(i)
i += 1

i = 1
while i <= 10:
print(i)
i += 1

When i becomes 5, the break statement is executed, and the loop terminates before
completing all iterations.
Example 2: break in a for loop
for num in range(1, 10):
if num == 7:
break # Exit loop when num equals 7
print(num)

The loop stops at 7, and all numbers up to 6 are printed.


2. continue Statement: The continue statement is used to skip the current iteration of a
loop and move to the next iteration. It does not terminate the loop but skips the remaining
code inside the loop for that iteration.
Python continue Statement Syntax
Loop
Condition:
Continue

Example 1: continue in a while loop


P = 0
while P < 10:
P += 1
if P == 3:
continue # Skip the rest of the code when i equals 3
print(P)

i = 0
while i < 5:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

i += 1
print(i)

i = 0
while i < 8:
i += 1
if i == 7:
continue # Skip the rest of the code when i equals 3
print(i)

When i equals 3, the continue statement skips the print(i) statement for that iteration, so 3
is not printed.
Example 2: continue in a for loop
for num in range(1, 6):
if num == 3:
continue # Skip printing the number 3
print(num)

CHAPTER NO. 8
What is a Function in Python? A function in Python is a block of reusable code that is
designed to perform a specific task. Functions help break down a program into smaller,
modular parts that can be reused and tested independently. A function in Python can take
input, process it, and return an output.
Understanding a Function: Reusability: Functions allow code to be reused without
rewriting it. Modularity: By dividing a program into functions, the program becomes more
organized and easier to manage. Abstraction: You can hide the complex logic of a task
inside a function and use it without worrying about the implementation details.
def function_name(parameters):
# function body
return result # optional

def: Keyword used to define a function. function_name: Name of the function (should
follow standard naming conventions).\n parameters: Inputs to the function (optional). ::
Indicates the start of the function block. Function Body: The block of code that performs
the function's task, indented by four spaces or a tab. return: Returns a value from the
function (optional, but important for output).
Example 1: Function without Parameters This function prints "Hello, World!" to the
console. Write a program to print Hellow, World using Function
def DIT():
print("wellcome to DIT class")
DIT()

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

def Acadmy():
print("well come new students in class")
Acadmy()

Example 2: Function with Parameters


write a program to sum two number and give output using function
This function takes two numbers as input and returns their sum.
def sub(a, b):
return a - b
result = sub(3, 5)
print(result) # Output: 8

def multiply(a, b):


return a * b

result = multiply(6, 4)
print(result) # Output: 8

def multipy(a, b):


return a * b
result = multiply(3, 5)
print(result)

def divide(a, b):


return a / b
result = divide(15, 5)
print(result)

def subtract(a, b):


return a - b
result = subtract(30, 50)
print(result)

Example 3: Function with a Default Parameter This function greets a user by name, with
a default name if none is provided.
def greet_user(name="Guest"):
print(f"Hello, {name}!")

greet_user("Alice") # Output: Hello, Alice!


greet_user() # Output: Hello, Guest!

def greet_user(name="Guest"):
print(f"Hello, {name}!")
greet_user("shaban")

Example 4: Function Returning Multiple Values This function returns both the sum and
the difference of two numbers.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

def sum_and_diff(a, b):


return a + b, a - b

result_sum, result_diff = sum_and_diff(10, 4)


print(result_sum, result_diff) # Output: 14 6

Example 5: Function with a List Parameter This function takes a list of numbers and
returns their average.
def calculate_average(numbers):
return sum(numbers) / len(numbers)

average = calculate_average([10, 20, 30, 40])


print(average) # Output: 25.0

Print Statement in Python The print() statement in Python is used to display output on
the console. It is primarily used for debugging or showing information to the user. The
print() statement prints the given object or value and does not affect the function's return
or program flow. Syntax:
print(object, ..., sep=' ', end='\n')

Return Statement in Python The return statement is used to exit a function and
optionally pass a value back to the caller. It allows a function to return data that can be
used later in the program. Unlike print(), return does not display output to the console; it
provides a result back to the part of the program that called the function.
Syntax:
def function_name():
return value

Example of return:
def add(a, b):
return a + b

result = add(100, 10)


print(result) # Output: 30

def multiply(a, b):


return a * b

result = multiply(100, 10)


print(result) # Output: 10

Variable Scope in Python A variable is only available from inside the region it is created.
This is called scope.
Variable scope refers to the context within which a variable can be accessed.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Based on the scope, we can classify Python variables into two types:
1. Local Variables 2. Global Variables
Local Scope A variable created inside a function belongs to the local scope of that function,
and can only be used inside that function.
Example A variable created inside a function is available inside that function:
def myfunc():
x = 300
print(x)
myfunc()

def print_x():
x=10000
print(x)
print_x()

def available():
z = 100000
print(z)
available()

Global Scope A variable created in the main body of the Python code is a global variable
and belongs to the global scope.
Global variables are available from within any scope, global and local.
Example A variable created outside of a function is global and can be used by anyone:
y = 2000

def world():
print(y)

world()

Default Argument in Python A default argument in Python allows you to define a default
value for a function parameter. This means if no value is provided for that parameter when
calling the function, the default value will be used. Default arguments help make functions
more flexible and reduce the need to specify all arguments every time the function is called.
Syntax for Default Argument: When defining a function, you can assign default values to
one or more parameters using the = operator.
def function_name(param1=default_value1, param2=default_value2):
# Function body

Example of Default Argument:

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

def greet(name="Guest"):
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!


greet() # Output: Hello, Guest!

def call(name="Guest"):
print(f"Hello, {name}!")

call("shahban")
call("ali")

def my_Function(location="CMS Peshawar"):


print(f"The Location is, {location}!")

#my_Function()
my_Function("CMS Nowshehra")

Chapter No.9
Working With Graphics
Introduction to Turtle
In Python, a turtle refers to an object that represents a pen or cursor used to draw on a
canvas. This concept comes from the "turtle graphics" system, originally developed for
educational purposes in computer science. The turtle can be moved around the screen by
issuing commands, and as it moves, it can draw lines and shapes.
Definition of a Turtle: A turtle in Python is an object created from the Turtle class in the
turtle module. This object follows a set of commands (such as move forward, turn, lift the
pen) to create drawings on the canvas. The turtle can be controlled programmatically to
create various graphical outputs like lines, circles, and complex shapes.
Key Features of a Turtle: Movable cursor: The turtle moves on the screen according to
the commands given. Drawing: It draws shapes and patterns by moving with its pen down.
Direction-based: It can be turned left or right by a specified angle. Pen control: You can
lift or lower the pen to control whether the turtle draws while moving.
Key Concepts: Turtle: A cursor that moves around the screen, drawing as it goes. Canvas:
The area where the turtle moves and draws. Commands: You can give the turtle
commands like "move forward" or "turn," and it will follow them, creating drawings.
Basic Commands: turtle.forward(distance): Moves the turtle forward by the specified
distance. turtle.backward(distance): Moves the turtle backward by the specified distance.
turtle.left(angle): Turns the turtle left by the specified angle (in degrees).
turtle.right(angle): Turns the turtle right by the specified angle (in degrees).
turtle.penup(): Lifts the turtle's pen, so it won't draw when moving. turtle.pendown():
Lowers the turtle's pen, so it will draw when moving. turtle.circle(radius): Draws a circle

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

with the specified radius. turtle.goto(x, y): Moves the turtle to the specified (x, y)
coordinates. turtle.speed(speed): Sets the turtle's speed (1 is slowest, 10 is fastest).
!pip install ColabTurtle

Example: Drawing a Straight Line with Turtle


import turtle

# Create a turtle instance


t = turtle.Turtle()

# Set the speed of the turtle (1 is slowest, 10 is fastest)


t.speed(1)
# Move the turtle forward to draw a line
t.forward(200) # Draw a line of 200 units
# Hide the turtle and display the window
t.hideturtle()
turtle.done()

!pip install ColabTurtle

# Import ColabTurtle after installing it


from ColabTurtle.Turtle import *

# Initialize turtle
initializeTurtle()

# Set speed (1 is slowest, 10 is fastest)


speed(1)

# Move forward to draw a line


forward(200)

Explanation: initializeTurtle(): Initializes the turtle graphics in Google Colab. speed(5):


Sets the turtle's speed (optional, but useful to control the drawing speed). forward(200):
Moves the turtle forward by 200 units, drawing a line. done(): Completes the drawing
process. This will successfully display the turtle drawing a line in Google Colab.
# Install ColabTurtle if not installed already
#!pip install ColabTurtle

# Import ColabTurtle after installing it


from ColabTurtle.Turtle import *

# Initialize turtle
initializeTurtle()

# Set speed (1 is slowest, 10 is fastest)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

speed(5)

# Move forward to draw a line


backward(200)

# No need to call done() in ColabTurtle

Draw a Square using ColabTurtle Now, use the following code to draw a square:
# Import ColabTurtle after installing it
from ColabTurtle.Turtle import *

# Initialize turtle
initializeTurtle()

# Set the speed of the turtle


speed(1)

# Draw a square
for _ in range(4):
forward(200) # Move forward by 100 units
right(90) # Turn right by 90 degrees

# Complete the drawing


done()

Explanation: initializeTurtle(): Initializes the turtle for drawing in Colab. for _ in


range(4): Repeats the block 4 times to create the four sides of the square. forward(100):
Moves the turtle forward by 100 units for each side of the square. right(90): Turns the
turtle 90 degrees to the right after drawing each side, creating the square shape.
Step 2: Draw a Rectangle Now, use the following code to draw a rectangle:
# Import ColabTurtle after installing it
from ColabTurtle.Turtle import *

# Initialize the turtle (no need for windowSize argument)


initializeTurtle()
# Set speed (1 is slowest, 10 is fastest)
speed(1)
# Draw a rectangle
for _ in range(2):
forward(150) # Move forward by 150 units (length of the rectangle)
right(90) # Turn right by 90 degrees
forward(100) # Move forward by 100 units (width of the rectangle)
right(90) # Turn right by 90 degrees
# No need to call done() in ColabTurtle

Explanation: initializeTurtle(): Initializes the turtle without extra arguments. for _ in


range(2): The loop runs twice, drawing two sets of opposite sides to form a rectangle.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Speed and drawing commands: speed(5) controls the turtle's speed, and the forward and
right commands create the shape.
** Code to Simulate Drawing a Circle**
# Import ColabTurtle after installing it
from ColabTurtle.Turtle import *

# Initialize the turtle


initializeTurtle()

# Set speed (1 is slowest, 10 is fastest)


speed(10)

# Draw a circle by moving forward and turning slightly


for _ in range(360):
forward(1) # Move forward by 1 unit
right(1) # Turn right by 1 degree

# No need to call done() in ColabTurtle

initializeTurtle(): Initializes the turtle for drawing. speed(8): Sets a moderate speed for
the turtle to move around. for _ in range(360): Repeats the movement 360 times (1
degree for each step, creating a full circle). forward(1): Moves the turtle forward by 1 unit
at a time. right(1): Turns the turtle right by 1 degree for each step.
Draw a Star Now, use the following code to draw a star in Colab:
# Import ColabTurtle after installing it
from ColabTurtle.Turtle import *

# Initialize the turtle


initializeTurtle()

# Set speed (1 is slowest, 10 is fastest)


speed(5)

# Draw a star
for _ in range(5):
forward(150) # Move forward by 150 units
right(144) # Turn right by 144 degrees to form the star shape

# No need to call done() in ColabTurtle

Explanation: initializeTurtle(): Initializes the turtle for drawing. speed(5): Sets a


moderate speed for the turtle to move. for _ in range(5): Repeats the movement 5 times to
create the star's five points. forward(150): Moves the turtle forward by 150 units for each
star point. right(144): Turns the turtle by 144 degrees, the angle necessary to form a
perfect star.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Panda library in python


The Pandas library in Python is a powerful and widely-used data analysis and manipulation
tool. It provides flexible, high-performance data structures such as DataFrames and Series
that make it easier to work with structured data, such as tables, time series, and other
datasets. Pandas is built on top of the NumPy library and is commonly used for data cleaning,
transformation, and analysis.
Key Features of Pandas:
DataFrame: A 2-dimensional table-like data structure with labeled rows and columns,
similar to a spreadsheet or SQL table.
Series: A 1-dimensional array-like object that holds data, similar to a column in a DataFrame
or an array.
Data Manipulation: Allows easy slicing, indexing, filtering, and aggregation of data.
Handling Missing Data: Supports operations to detect, handle, and fill missing or null data.
File I/O: Supports reading from and writing to various file formats, such as CSV, Excel, SQL,
JSON, etc
Data Transformation: Provides methods for merging, grouping, reshaping, and pivoting
data for analysis.
Installation: You can install Pandas using pip if it's not already installed:
pip install pandas

Basic Examples: Creating a DataFrame:


import pandas as pd

# Creating a DataFrame from a dictionary


data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Occupation': ['Engineer', 'Doctor', 'Artist']
}
df = pd.DataFrame(data)
print(df)

import pandas as pd

# Creating a DataFrame from a dictionary


data = {
'Name': ['Saad', 'waseem', 'raees'],
'Age': [16, 18, 18],
'Occupation': ['student1', 'doctor', 'STUDENT']
}

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

df = pd.DataFrame(data)
print(df)

Reading from a CSV File:


# Read data from a CSV file
df = pd.read_csv('posts.xlsx')

Basic Data Operations: Accessing Columns:


df['Name'] # Access the 'Name' column

Filtering Rows:
df[df['Age'] > 25] # Filter rows where Age > 25

Descriptive Statistics:
df.describe() # Summary statistics for numerical columns

Handling Missing Data:


# Filling missing values
df.fillna(0, inplace=True)

# Dropping rows with missing values


df.dropna(inplace=True)

Use Cases: Data Analysis: Pandas is used extensively for exploratory data analysis (EDA)
and to prepare data for machine learning models. Data Wrangling: Helps clean and
organize raw data for better insights and visualization. Time Series Analysis: Pandas
supports time-series data, making it ideal for working with time-stamped data.
How to Work with Excel Files Using Pandas
1. Install Pandas and openpyxl: You need the pandas library and openpyxl (for .xlsx
files). Install them using pip:
pip install pandas openpyxl

Reading Excel Files The pandas.read_excel() function reads Excel files into a DataFrame.
You can specify the file name, sheet name, and other parameters.
Example 1: Read an Excel File
import pandas as pd

# Read an Excel file


df = pd.read_excel('POSTS.xlsx')

# Display the DataFrame


print(df)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Occupation': ['Engineer', 'Doctor', 'Artist']}

df = pd.DataFrame(data)

# Write the DataFrame to an Excel file


df.to_excel('output.xlsx', index=True)

from google.colab import files

# Upload the file


uploaded = files.upload()
# Read the uploaded file
df = pd.read_excel('STAFF.xlsx')

# Display the DataFrame


print(df)

from google.colab import files


# Upload the file
uploaded = files.upload()

# Read the uploaded file


df = pd.read_excel('STAFF.xlsx')

# Display the DataFrame


print(df)

# Read the uploaded file


df = pd.read_excel('STAFF.xlsx')

# Display the DataFrame


print(df)

import pandas as pd
from google.colab import files

# Upload the file


uploaded = files.upload()

# Read the uploaded file


df = pd.read_excel('STAFF.xlsx')

# Display the DataFrame


print(df)

import pandas as pd

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Read an Excel file


df = pd.read_excel('STAFF DATA.xlsx')

# Display the DataFrame


print(df)

Example: Accessing Excel File from Google Drive

from google.colab import drive

# Mount Google Drive


drive.mount('/content/drive')

# Now you can read the file from the Drive path
df = pd.read_excel('/content/drive/My Drive/STAFF.xlsx')

# Display the DataFrame


print(df)

# List all column headers


print(df.columns)

from google.colab import files


import pandas as pd

# Step 1: Upload the Excel file


uploaded = files.upload()

# Step 2: Read the Excel file into a DataFrame (replace 'your_file.xlsx' with
the actual file name)
df = pd.read_excel('STAFF.xlsx')

# Step 3: Print the DataFrame to confirm it's loaded (optional)


print(df)

Write Excel File Using Pandas: Install Necessary Libraries: If you haven't already, you'll
need to install Pandas and openpyxl to handle Excel files with the .xlsx extension.
!pip install pandas openpyxl

Basic Example of Writing to Excel: Here's an example of writing a DataFrame to an Excel


file.
import pandas as pd

# Create a sample DataFrame


data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Occupation': ['Engineer', 'Doctor', 'Artist']}

df = pd.DataFrame(data)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Write the DataFrame to an Excel file


df.to_excel('output1.xlsx', index=False) # index=False prevents writing row
indices

# Print confirmation
print("DataFrame written to 'output1.xlsx'.")

Explanation:
to_excel(): This function writes the DataFrame to an Excel file.
index=False: Prevents Pandas from writing row numbers (indices) to the Excel file. If you
want the indices, you can omit this parameter.
what is matplotlib in python?
Matplotlib is a widely used plotting library in Python that allows for the creation of static,
animated, and interactive visualizations. It is highly customizable and provides control over
every aspect of a figure, making it ideal for creating detailed and publication-quality plots.
Key Features of Matplotlib: 2D Plotting: Supports various types of plots, such as line plots,
scatter plots, bar charts, histograms, pie charts, etc. Customizable: ‘
bold text You can control the size, color, and style of the plots and add labels, titles, legends,
and annotations. ‘
Integration: Works well with libraries like NumPy for numerical data, Pandas for data
frames, and SciPy for scientific computing.
Interactive: You can interact with plots in environments like Jupyter Notebooks and Google
Colab.
Installation: If Matplotlib isn’t installed, you can install it using pip:
pip install matplotlib

Basic Concepts:
Figure: The whole figure, including all elements (plots, axes, titles).
Axes: The area of the figure where the data is plotted (it’s like a plot inside the figure).
Plot: The actual chart that visualizes the data.
Basic Plotting with Matplotlib: Here's how you can create a simple line plot using
Matplotlib:
Example 1: Simple Line Plot
import matplotlib.pyplot as plt

# Example data

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

x = [11, 12, 5, 14, 15]


y = [2, 4, 6, 8, 10]

# Create a line plot


plt.plot(x, y)

# Add a title, labels, and grid


plt.title("Simple Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)

# Display the plot


plt.show()

Common Plot Types in Matplotlib: Line Plot: Line plots are useful for visualizing trends
over time or continuous data.
plt.plot(x, y)
plt.show()

Scatter Plot: Scatter plots are used to show relationships or distributions between two
variables.
# Example data
x = [5, 7, 8, 7, 2, 17, 2, 9]
y = [99, 86, 87, 88, 100, 86, 103, 87]

# Create a scatter plot


plt.scatter(x, y)
plt.title("Scatter Plot")
plt.show()

Bar Plot: Bar plots are great for comparing different categories of data.
# Example data
categories = ['A', 'B', 'C', 'D']
values = [4, 7, 1, 8]

# Create a bar plot


plt.bar(categories, values)
plt.title("Bar Plot")
plt.show()

Histogram: Histograms are used to display the distribution of a dataset.


import numpy as np

# Generate random data


data = np.random.randn(1000)

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Create a histogram
plt.hist(data, bins=30)
plt.title("Histogram")
plt.show()

Pie Chart: Pie charts are used to display proportional data.


labels = ['A', 'B', 'C', 'D']
sizes = [15, 30, 45, 10]

# Create a pie chart


plt.pie(sizes, labels=labels, autopct='%1.1f%%')
plt.title("Pie Chart")
plt.show()

Customizing Plots: Matplotlib provides extensive customization options. You can adjust
colors, line styles, markers, figure size, and more.
Example: Customizing a Line Plot
plt.plot(x, y, color='green', marker='o', linestyle='--', linewidth=2, marker
size=6)
plt.title("Customized Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()

Subplots: You can create multiple plots in the same figure using subplots.
# Create two subplots (1 row, 2 columns)
plt.subplot(1, 2, 1) # First subplot
plt.plot(x, y)
plt.title("Plot 1")

plt.subplot(1, 2, 2) # Second subplot


plt.scatter(x, y)
plt.title("Plot 2")

plt.show()

Combining NumPy and Matplotlib Matplotlib works well with NumPy for generating
numerical data and visualizing it.
import numpy as np
import matplotlib.pyplot as plt

# Generate data using NumPy


x = np.linspace(0, 10, 100)
y = np.sin(x)

# Plot the sine wave

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.show()

what is numpy library in python

NumPy (Numerical Python) is a powerful open-source library in Python that provides


support for large, multi-dimensional arrays and matrices, along with a wide collection of
mathematical functions to operate on these arrays efficiently. It is a fundamental package for
scientific computing in Python and is often used as a base for more complex data
manipulation libraries like Pandas and machine learning libraries like TensorFlow and
PyTorch.

Key Features of NumPy:

1. N-Dimensional Array: NumPy’s core data structure is the ndarray, an efficient multi-
dimensional array that supports various data types.
2. Mathematical Functions: Provides a wide range of functions for performing
operations like linear algebra, statistics, trigonometry, and random number
generation.
3. Broadcasting: Automatically expands arrays of different shapes for element-wise
operations without making unnecessary copies of data.
4. Memory Efficiency: Arrays consume far less memory compared to standard Python
lists, and operations on arrays are performed faster.
5. Integration: Works well with other libraries such as Pandas, Matplotlib, and SciPy.
Installation:

You can install NumPy using pip:

pip install numpy

Key Concepts in NumPy:

1. NumPy Arrays (ndarray):


The ndarray is the core of NumPy, allowing you to perform mathematical operations on large
datasets. It is similar to Python lists but offers more functionality and efficiency.

Example: Creating an Array

import numpy as np

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

# Create a 1D array

arr = np.array([1, 2, 3, 4, 5])

print(arr)

what is matplotlib in python?

Matplotlib is a widely used plotting library in Python that allows for the creation of static,
animated, and interactive visualizations. It is highly customizable and provides control over
every aspect of a figure, making it ideal for creating detailed and publication-quality plots.

Key Features of Matplotlib:

1. 2D Plotting: Supports various types of plots, such as line plots, scatter plots, bar
charts, histograms, pie charts, etc.
2. Customizable: You can control the size, color, and style of the plots and add labels,
titles, legends, and annotations.
3. Integration: Works well with libraries like NumPy for numerical data, Pandas for
data frames, and SciPy for scientific computing.
4. Interactive: You can interact with plots in environments like Jupyter Notebooks and
Google Colab.

Tkinter is the standard Python library for creating graphical user interfaces (GUIs). It
provides a simple way to build windows, dialogs, buttons, menus, text boxes, and other user
interface components in a desktop application. Tkinter is built on the Tk GUI toolkit, which
is cross-platform, meaning it works on Windows, macOS, and Linux.

Key Features of Tkinter:

1. Built-in Library: Tkinter comes pre-installed with Python, so you don't need to
install it separately.
2. Cross-Platform: GUIs built with Tkinter will run on multiple operating systems
without modification.
3. Simple and Easy to Use: Tkinter provides an intuitive interface for creating window-
based applications.
4. Widgets: Tkinter provides a variety of pre-built components (called widgets) such as
buttons, labels, frames, text boxes, and more.
5. Event-Driven Programming: Tkinter supports event-based programming, making
it easy to handle user actions like button clicks, mouse movements, and key presses.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

Installation:

Since Tkinter comes with Python by default, you typically don’t need to install it. However,
for some systems, you might need to install the tk package if it’s missing:

# For Debian/Ubuntu

sudo apt-get install python3-tk

Basic Concepts in Tkinter:


1. Window: The main application window.
2. Widgets: Elements like buttons, labels, text boxes, etc., that the user interacts with.
3. Geometry Managers: Used to control the layout of widgets in the window (e.g., pack,
grid, place).
4. Event Binding: Attaches events like button clicks to functions.
what is django library in python?

Django is a high-level web framework for Python that simplifies the process of building
robust, scalable, and secure web applications. It encourages rapid development by providing
built-in components that handle many aspects of web development, such as authentication,
database management, form handling, and more. Django follows the Model-View-
Controller (MVC) architectural pattern, although it refers to it as Model-View-Template
(MVT).

Key Features of Django:

1. Batteries-Included: Django provides everything you need to build web applications


without needing third-party libraries for common tasks.
2. ORM (Object-Relational Mapping): Automatically handles database operations,
allowing you to work with databases in a Pythonic way without writing raw SQL.
3. URL Routing: It allows easy mapping of URLs to views, making it straightforward to
build SEO-friendly and human-readable URLs.
4. Security: Django provides built-in protection against common security
vulnerabilities like cross-site scripting (XSS), cross-site request forgery (CSRF), SQL
injection, and clickjacking.
5. Admin Interface: It includes an auto-generated admin interface, making it easier to
manage and modify data.
6. Scalability: Django is designed to scale and handle high traffic while maintaining
performance.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

7. Form Handling: Django provides built-in forms, making it easy to handle user input
and validation.
8. Templating Engine: Django uses a templating engine for dynamic HTML generation,
separating business logic from the presentation layer.
MVT Architecture in Django:

1. Model: Defines the structure of the database. It represents the data and how it is
stored in the database.
2. View: Contains the business logic and handles user requests. It processes data and
returns a response, typically an HTML page or JSON data.
3. Template: Defines the presentation layer, rendering the data into HTML for the user
interface.
Installing Django:

You can install Django using pip:

pip install django

what is kotlin library in python ?


There is no Kotlin library in Python itself, as Kotlin is a modern, statically-typed
programming language primarily targeting the JVM (Java Virtual Machine). It is used to
build Android applications, server-side applications, and more. Kotlin and Python are two
distinct programming languages, each with its own ecosystem, libraries, and use cases.

However, you might be referring to the possibility of using Kotlin in combination with
Python or interacting with each other through certain libraries or tools. Here are a few
possibilities where Kotlin and Python might interact:

1. Using Python from Kotlin (via Jython or JNI)

• Jython is a Python implementation that runs on the JVM. It allows you to run Python
code within Java or Kotlin applications. With Jython, Kotlin code can directly call
Python code, allowing integration between the two languages.
• You can also use Java Native Interface (JNI) to interact with Python code from
Kotlin, but this approach is more complex and lower level.
2. Interfacing with Python Libraries from Kotlin

If you need to use Python libraries (especially for data science or machine learning) within a
Kotlin project, there are some tools and libraries that facilitate this:

• KotlinPy: A Kotlin library that enables integration with Python code, allowing Kotlin
applications to call Python functions.

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

• KotlinDL: A Kotlin library for deep learning, built on top of TensorFlow. It allows
Kotlin developers to use Python-based deep learning models, providing an easy
interface to interact with machine learning models typically developed in Python.
Kotlin for Scripting in Python

In some cases, Kotlin can be used as a scripting language within JVM-based applications,
including those written in Python using Jython or other interoperability tools.

what is micro python library in python?


MicroPython is a lean and efficient implementation of the Python 3 programming language,
optimized to run on microcontrollers and embedded systems. It provides a Python
environment that is specifically designed to run in resource-constrained environments, such
as small microcontroller units (MCUs) with limited RAM and storage. MicroPython enables
developers to write Python code for devices like ESP32, ESP8266, Pyboard, Arduino, and
other hardware platforms.

Key Features of MicroPython:

1. Lightweight and Efficient: MicroPython is optimized to run on microcontrollers


with very limited resources (as low as 256 KB of code space and 16 KB of RAM).
2. Hardware Access: It provides modules to interact directly with hardware
components, such as GPIO pins, PWM, I2C, SPI, ADC, DAC, UART, etc.
3. Interpreted Language: Like Python, it is interpreted, so you can write scripts quickly
and test them in real-time on embedded systems.
4. Cross-Platform: It can run on different types of microcontroller platforms, including
STM32, ESP32, ESP8266, and more.
5. Interactive REPL: MicroPython offers an interactive REPL (Read-Eval-Print Loop)
mode for testing and running commands directly on the device, which is useful for
debugging.
what is pygame library in python?
Pygame is a cross-platform set of Python modules designed for writing video games. It
provides functionality to manage graphics, sound, and input devices, enabling the creation
of 2D games and multimedia applications in Python. Pygame builds on top of the Simple
DirectMedia Layer (SDL) library, allowing developers to handle things like rendering
images, playing sounds, and processing user input (keyboard, mouse, joystick) in a game
loop.

Key Features of Pygame:

1. 2D Graphics Rendering: Pygame provides tools for loading, rendering, and


transforming images (sprites) and shapes (rectangles, circles, etc.).

Prepared by : Sir Touqeer , National Academy Abbottabad


PYTHON PROGRAMMING NOTES

2. Sound and Music: It supports loading and playing sound effects (like .wav files) and
background music (like .mp3 or .ogg files).
3. Input Handling: You can capture user input from keyboards, mice, and game
controllers.
4. Game Loop: Pygame provides a framework for a game loop where you can update
the game state and render frames in real-time.
5. Cross-Platform: It works on multiple platforms, including Windows, macOS, and
Linux.
Installing Pygame:

You can install Pygame using pip:

pip install pygame

Prepared by : Sir Touqeer , National Academy Abbottabad

You might also like