Python Programming Complete Notes
Python Programming Complete 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.
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
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.
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 −
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.
• 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.
• 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.
• 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
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.
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.
Programmer Assembly language is less programmer friendly High-level language is highly user
friendliness programming language. friendly programming language.
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.
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.
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
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).
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.
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.
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.
Following is the equivalent program written in Python. This program will also produce the
same result Hello, World!
Hello, World!
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
teaching Python as their primary programming language. There are many other good
reasons which makes Python as the top choice of any programmer:
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.
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.
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.
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
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
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!
** 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")
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)
Accessing an Undefined Variable This program will raise a NameError because the
variable x has not been defined before being used.
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
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(4/2)
print(2/4)
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)
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!")
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
result = calculate_area(5)
print(result) # This will print the area using the more precise value of pi
# if x > y:
# print("x is greater than y")
# else:
# print("x is not greater than y")
# 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)
2. Double-Quoted String
double_quoted = "Python is fun!"
print(double_quoted)
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)
2. Repetition You can repeat a string multiple times using the * operator.
words = "Python! "
multiply= words * 100
print(multiply)
3. Indexing You can access individual characters in a string using indexing (starting from
0).
word = "Python"
first_letter = word[1]
print(first_letter)
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 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 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.
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
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!"
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!"
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
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
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)
# 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"]
#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
# 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"]
# Example list
fruits = ["apple", "banana", "cherry"]
del fruits[1]
# Example list
students = ["ali", "ahmed", "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.
Example:
# Example list
fruits = ["apple", "banana"]
# Example list
fruits = ["apple", "banana"]
# Example list
fruits = ["apple", "banana"]
# Insert an element "orange" at index 1
fruits.insert(1, "orange")
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]
slice1 = numbers[2:6]
print(slice1) # Output: [2, 3, 4, 5]
# Example list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# 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)
# 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"]
# Example list
fruits = ["apple", "banana", "cherry"]
# Example list
fruits = ["apple", "banana", "cherry"]
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
# Example list
fruits = ["apple", "banana", "cherry"]
# 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:
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
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
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
num = 7
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
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")
grade = "A"
elif marks >= 75:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
temperature = 30
if temperature > 30:
print("It's hot outside.")
elif temperature < 15:
print("It's cold outside.")
else:
print("The weather is moderate.")
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!")
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.")
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"
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.")
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
else:
print("You do not meet the criteria for enrollment.")
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
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")
age = 65
is_member = False
if age > 60 or is_member:
print("You get a discount")
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")
else:
# Code to execute if condition1 is False
Example:
age = 19
has_ID = True
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 is_admin:
if is_active:
print("Admin access granted")
else:
print("Admin account is inactive")
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)
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)
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)
3. Looping Through a String A for loop can also iterate through the characters in a string:
name = "Pakistan"
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
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]
]
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
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
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
# 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: "))
# 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: "))
# 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: "))
# 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: "))
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:
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)
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)
i = 0
while i < 5:
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()
def Acadmy():
print("well come new students in class")
Acadmy()
result = multiply(6, 4)
print(result) # Output: 8
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}!")
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.
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)
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
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.
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
def greet(name="Guest"):
print(f"Hello, {name}!")
def call(name="Guest"):
print(f"Hello, {name}!")
call("shahban")
call("ali")
#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
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
# Initialize turtle
initializeTurtle()
# Initialize turtle
initializeTurtle()
speed(5)
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()
# Draw a square
for _ in range(4):
forward(200) # Move forward by 100 units
right(90) # Turn right by 90 degrees
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 *
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 *
# 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
import pandas as pd
df = pd.DataFrame(data)
print(df)
Filtering Rows:
df[df['Age'] > 25] # Filter rows where Age > 25
Descriptive Statistics:
df.describe() # Summary statistics for numerical columns
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
# Create a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Occupation': ['Engineer', 'Doctor', 'Artist']}
df = pd.DataFrame(data)
import pandas as pd
from google.colab import files
import pandas as pd
# Now you can read the file from the Drive path
df = pd.read_excel('/content/drive/My Drive/STAFF.xlsx')
# Step 2: Read the Excel file into a DataFrame (replace 'your_file.xlsx' with
the actual file name)
df = pd.read_excel('STAFF.xlsx')
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
df = pd.DataFrame(data)
# 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
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]
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 histogram
plt.hist(data, bins=30)
plt.title("Histogram")
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.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
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.grid(True)
plt.show()
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:
import numpy as np
# Create a 1D array
print(arr)
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.
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.
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.
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
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).
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:
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:
• 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.
• 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.
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: