0% found this document useful (0 votes)
5 views

Python Notes

The document provides an overview of Python, a high-level, open-source programming language created by Guido Van Rossum, highlighting its features such as ease of learning, portability, and support for multiple programming paradigms. It covers fundamental concepts including program structure, data types, variables, operators, and memory management, as well as best practices for naming conventions and code readability. Additionally, it discusses user input, output, and the importance of indentation in Python syntax.

Uploaded by

hiyahir222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python Notes

The document provides an overview of Python, a high-level, open-source programming language created by Guido Van Rossum, highlighting its features such as ease of learning, portability, and support for multiple programming paradigms. It covers fundamental concepts including program structure, data types, variables, operators, and memory management, as well as best practices for naming conventions and code readability. Additionally, it discusses user input, output, and the importance of indentation in Python syntax.

Uploaded by

hiyahir222
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Python Unit 1 Notes

Introduction

Python is a high level programming language for general purpose


programming.

It is an open source, interpreted, object-oriented programming language.

It was created by Dutch programmer, Guido Van Rossum.

The first version was released on Feb 20, 1991.

Features

1. Easy to learn and use

2. Interpreted language: code is executed line by line, which simplifies


debugging and testing

3. Portable Language: platform independent

4. Dynamically Typed: doesn’t require explicit declaration of variable types.


The type is determined at runtime, making it flexible and reducing boiler
plate code.

5. Opensource and Community Support

6. Object Oriented and Procedural

7. High Level Language: it abstracts complex details of hardware, allowing


developers to focus on programming logic without worrying about low-
level details like memory management.

8. Large Ecosystem: large standard library that provides a rich set of


modules and functions so you do not have to write your own code for
every single thing.

9. Functional Programming: It supports functional programming, which


emphasizes the use of pure functions, immutability, and high order
functions. Eg: Map, Reduce, Filter, Lambda, High order functions.

Python Unit 1 Notes 1


10. Automatic Memory Management: It has an automatic garbage collection
feature that manages memory allocation and deallocation, preventing
memory leaks.

Python Shell
Python is an interpreted scripting language, so it doesn’t need to be compiled.
Python comes with a python shell (interactive shell). It waits for the python
code from the user. When you enter the code, it interprets the code and shows
the result in the next line.
Program Structure

# This is a comment

# importing module
import random

# defining variables
x = 10
y = "Hello world"
z = True

# performing arithmetic operations


result = x + 5

# using if else
if z:
print(y)
else:
print(z)

# defining a function
def greet(name):
print("Hello, " + name + "!")

Python Unit 1 Notes 2


# using the function
greet("Mohammad")

Indentation

An indentation is a white space in a text. It is used in many languages to


increase code readability. However, python uses indentation to create blocks
of code. In other programming languages, curly brackets are used to create
code blocks instead of indentation.

>>> "Hello World" # this will cause an indentation error


>>>"Hello world" # this will run without error

Identifiers
Identifiers are the names used to identify variables, functions, classes or other
objects. They are user-defined names that follow specific rules and
conventions.

Rules for writing identifiers

Identifiers can only contain letters ( a-z , A-Z , digits 0-9 , and
underscores _ ).

Identifiers cannot begin with a number.

Identifiers are case sensitive.

Reserved keywords cannot be used as identifiers.

Identifiers cannot include symbols like @ , $ , & , # ,etc.

Identifiers cannot have spaces. Us underscores _ for readability.

Naming Conventions

Use snake case(lowercase with underscore separating words) for


variables and functions. my_variable

Use pascal case(Capitalize the first letter of each word) for class
names. MyClass

Use all uppercase letters with underscores for constant. PI = 3.14

Python Unit 1 Notes 3


Keywords
They are reserved words that have a special meaning and cannot be used as
identifiers for variables, functions, or other objects.

False, None, True, and, as, assert, async, await, break, class, continue, de
f, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, no
nlocal, not, or, pass,raise, return, try, while, with, yield

Comments
Any text preceded by a hash(#) symbol is considered a comment and is not
executed when the code runs.

# This is single line comment


"""This is multiline
comment
"""

Escape Sequences

\\ # used for backslash print("C:\\path\\to\\file")


\' # used for single quote
\" # used for double quote
\n # used for newline
\t # used for horizontal tab
\v # used for vertical tab
\0 # used for represent null character print("Hello\0 World") -> Hello World

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

1. Text Type: str

2. Numeric Type: int , float , complex

3. Sequence Type: list , tuple , range

Python Unit 1 Notes 4


4. Mapping Type: dict

5. Set Types: set , frozenset

6. Boolean Type: bool

7. Binary Types: bytes , bytearray , memoryview

8. None Type: NoneType

x = "Hello World" #str


x = 20 #int: whole number, positive/negative, without decimals, of unlimite
d length
x = 20.5 #float: positive/negative, containing one or more decimals
x = 1j #complex: written with "j" as the imaginary part
x = ["apple", "banana", "cherry"] #list
x = ("apple", "banana", "cherry") #tuple
x = range(6) #range
x = {"name": "john", "age": 36} #dict
x = {"apple", "banana", "cherry"} #set
x = frozenset({"apple", "banana", "cherry"}) #frozenset
x = True #bool
x = b"Hello" #bytes
x = bytearray(5) #bytearray
x = memoryview(bytes(5)) #memoryview
x = None #NoneType

Check Data Types: To check the data type of certain data/variable we use
the type() function.

x = 10
print(type(x)) # int

Type Casting

Converting one data type to another data type.

Python Unit 1 Notes 5


num_int = 10
print(num_int) # 10
num_float = float(num_int)
print(num_float) # 10.0

Variables

It stores data in computer memory. A mnemonic variable is a variable name


that can be easily remembered and associated. A variable refers to memory
address in which data is stored. Number at the beginning, special character,
hyphen are not allowed when naming a variable. A variable can have a short
name(x,y,z) but a more descriptive name(firstname, lastname,etc) is highly
recommended.

# invalid variable names


first-name
first@name
1num

Assignments

Simple Assignment

x = 10

Multiple Assignment

Multiple Value to Multiple Variables

name, age, country = "mohammad", 22, "India"


print(name, age, country)

One Value to Multiple Variables

x = y = z = 10 # also known as chain assignment


print(x,y,z) 10

Python Unit 1 Notes 6


Dynamic Typing

The same variable can hold different types of values at different times.

x = 42 # x is an integer
x = "Python" # Now x is a string
x = [1, 2, 3] # Now x is a list

Unpacking Collections

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

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


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

Store remaining value to another variable

num = [1,2,3,4,5]
one, *rest = num
print(one)
print(rest)

Printing variables

x = "Hello"
y = " World"
print(x + y) # Hello World
# but if you use numbers then it will give error
a = 10
b = "Text"
print(a+b) # error

Global Variables

Python Unit 1 Notes 7


Variables that are created outside the function. It can be used inside and
outside of the function.

x = 10
def func():
print(x)

func() # 10

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

x = 10

def glb():
x = 20
print(x)

glb() # 20
print(x) # 10

Global Keyword

Normally, when you create a variable inside a function it is a local variable.


It can be accessed only inside. But we can make local variable global by
appending global keyword at the beginning of the variable without
declaring the value.

def func():
global x
x = 10

print(x) # 10
---------------------------

Python Unit 1 Notes 8


# if you want to change the value of global variable inside the function
x = "Normal Text"

def fun():
global x
x = "Edited Text"

fun()
print(x)

Mutable & Immutable Data Types

1. Mutable Data Types: It can be modified after their creation, meaning the
same object in memory is updated without creating a new object. Eg: list,
dict, set, byte array, user-defined classes.

lst = [1,2,3]
lst[0] = 0
lst.append(4)
print(lst) # [0,2,3,4]

2. Immutable Data Types: It cannot be modified after they are created. Any
operation that appears to modify the object actually creates a new object
in memory. Eg: int, float, complex, str, tuple, frozenset, bytes, bool

x = 10
x = x + 10 # a new integer object is created with value 15
print(x) # 15
------------------------
x=3
y=x

# changing value of x
x = 13

Python Unit 1 Notes 9


print(id(x) == id(y)) # false because x now points to a distinct integer o
bject

Check the id of an object

Every python object has a distinct address that informs the application where
the item is located in memory. Python have id() function to read the object’s
memory address.

string = "Hello"
print(id(string)) # 12381972831

Operators
Operators are used to perform operations on variables and values.

# Arithmetic Operators
x + y # addition
x - y # subtraction
x * y # multiplication
x / y # division
x % y # modulus
x ** y # exponential
x // y # floor division: it roundts the results down to the nearest whole num
ber
------------------------
# Assignment Operators
x = 5 # value of x is 5
x += 5 # x = x + 5
x -= 5 # x = x - 5
x *= 5 # x = x * 5
x /= 5 # x = x / 5
x %= 5 # x = x % 5
x **= 5 # x = x ** 5
x //= 5 # x = x // 5
x &= 5 # x = x & 5
x |= 5 # x = x | 5

Python Unit 1 Notes 10


x ^= 5 # x = x ^ 5
x >>= 5 # x = x >> 5
x <<= 5 # x = x << 5
print(x := 5) # x = 5 print(x)
------------------------
# Comparision Operators
x == y # equal
x != y # not equal
x > y # greater than
x < y # less than
x >= y # greater than or equal to
x <= y # less than or equal to
------------------------
# Logical Operators
x < 5 and x < 10 # Returns True if both statements are true
x < 5 or x < 4 # Returns True if one of the statements is true
not(x < 5 and x < 10) # Reverse the result, returns False if the result is true
------------------------
# Identity Operators
x is y # returns true if both variables are the same object, with same mem
ory loca..
x is not y # returns true if both variables are not the same object
------------------------
# Membership Operators
x in y # returns true if seq with the specific value is present in the object
x not in y # return true if seq with the specific value is not present in the o
bject
------------------------
# Bitwise Operators
x & y # sets each bit to 1 if both bits are 1
x | y # sets each bit to 1 if one of two bits is 1
x ^ y # sets each bit to 1 if only one of two bits is 1
~x # inverts all the bits
x << 2 # x * (2 ** 2)
x >> 2 # x / (2 ** 2)

Python Unit 1 Notes 11


Operators Precedence

It describes the order in which operations are performed. If two operators


have the same precedence, the expression is evaluated from left to right.

() # parenthesis
** # exponentiation
+x, -x, ~x # unary plus, unary minus, and bitwise NOT
*, /, //, % # multiplication, division, floor division, modulus
+, - # addition, subtraction
<<, >> # left shift, right shift
& # bitwise AND
^ # bitwise XOR
| # bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in # comparisions, identity and memb
ership
not # logical NOT
and # logical AND
or # logical OR

Short Circuit Evaluation


It means that python stops evaluating an expression as soon as the result is
determined. This is commonly seen with the logical operators and and or

a = False
b = True

if a and b: # since a is false, python skips evaluating b


print("This won't be print")

Lazy Evaluation
It refers to delaying the computation of a value or expression until it is actually
needed. It is commonly used in constructs like iterators, generators, and
comprehensions.

Python Unit 1 Notes 12


gen = (x**2 for x in range(5))
# computes elements on demand
print(next(gen)) # Output: 0
print(next(gen)) # Output: 1
print(next(gen)) # Output: 4
print(next(gen)) # Output: 9
print(next(gen)) # Output: 16

Short Circuit Evaluation Lazy Evaluation

Delays computation until value is


Stops evaluating logical expressions early.
needed.

Logical operators like and and or Generators, comprehensions, iterators

Avoid unnecessary computation in Saves memory and avoids pre


conditions computation

Taking input from the user

The input() function is used to receive input from the user in python.

name = input("Enter your name: ")


age = int(input("Enter Age: ")) # input with type conversion

Output on the console

the print() function is used to display data to the standard output(console). It


supports multiple arguments, formatting and separators.

print(f"Hello, {name}!")
print(f"Age: {age}")

Command Line Arguments


It allows users to pass information to a python script when it is executed.
These arguments can be used to control the behavior of the program
dynamically, without modifying the code.

sys.argv

Python Unit 1 Notes 13


The first element, sys.argv[0] is the name of the script.

Rest elements are the arguments that are provided in the command
line

import sys

file = sys.argv[0]
print(f"Filename: {file}")
first_arg = sys.argv[1]
print(f"First argument: {first_arg}")

Control Flow
Conditional Statements

If

a = 33
b = 200
if b > a:
print("b is greater than a") # here indentation is necessary else give
error

If-else

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

If-elif-else

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

Python Unit 1 Notes 14


else:
print("a is greater than b")

Short hand If

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

Short hand If-else or Ternary Operator

print("a") if a > b else print("b")

Nested If

if x > 10:
if x > 20:
# code
else:
# code

Pass Statement

If statement cannot be empty, but if you for some reason have an if


statement with no content, put in the pass statement to avoid getting an
error.

if b > a:
pass

Loops

While

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

Python Unit 1 Notes 15


--------------------
# while-else: with the else statement we can run a block of code once
when the condition is no longer is true

i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6") # this will run after the while loop b
ecome false

For
It is used for iterating over a sequence (that is either list, a tuple, a
dictionary, a set or a string). It doesn’t require an indexing variable to set
beforehand.

# looping through list


fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
--------------------
# looping through string
for x in "Hello":
print(x)
--------------------
# for-else: with the else statement we can run a block of code once w
hen the loop is finished
for x in range(6):
print(x)
else:
print"Loop Completed")
--------------------
# range(start,end,step) function: It returns a sequence of numbers, sta
rting from 0 by default, and increments by 1 by default, and ends at a s

Python Unit 1 Notes 16


pecified number.
for x in range(6):
print(x) # 0 1 2 3 4 5

for x in range(2,6):
print(x) # 2 3 4 5

for x in range(2,30,3):
print(x) # 2 5 8 11 14 17 20 23 26 29
--------------------
# Nested for loop
for x in range(3):
for y in range(3):
print(x,y)

Break

# break statement can stop the loop before it has lloped through all th
e items
for x in range(6):
if x == 4:
break
print(x)
# output: 0 1 2 3

Continue

# continue statement can stop the current iteration of the loop, and co
ntinue with the next iteration
for x in range(6):
if x == 4:
continue
print(x)
# output: 0 1 2 3 5

Python Unit 1 Notes 17


Functions

A function is reusable block of code or programming statements designed to


perform a certain task. To define or declare a function, python provides the
keyword def . The function block of code is executed only if the function is
called or invoked.
Declaring and Calling a Function
When we make a function, we call it declaring a function. When we start using
it, we call it calling or invoking a function. Function can be declared with or
without parameters.

# declaring a function
def function_name():
# code
---------------------
# calling a function
function_name()

Types of Functions

1. ?Built-in Functions: Python provides several built-in functions that can be


used directly.

print("Hello") # Hello
print(len([1,2,3])) # 3
print(type(42)) # <class 'int'>

2. User-defined Functions: These are the functions created by the user using
the def keyword.

def greet(name):
print("Hello, " + name)

greet("Mohammad") # Hello, Mohammad

Python Unit 1 Notes 18


3. Lambda Functions: These are small, one-line functions using the
lambda keyword.

square = lambda x: x ** 2
print(square(5)) # 25

4. Recursive Functions: These are functions that call themselves.

def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)

print(factorial(5)) # 120

5. High-Order Functions: Functions that take other functions as arguments or


return functions.

def square(x):
return x ** 2

numbers = [1,2,3,4]
squared_num = list(map(square, numbers))
print(squared_num) # 1 4 9 16

6. Inner Functions(Nested Functions): Functions defined inside other


functions.

def outer():
def inner():
return "Hello from inner function!"
return inner()

print(outer()) # Hello from inner function!

Python Unit 1 Notes 19


Arguments

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.

def my_func(name): # here name variable is parameter


print(name)

my_func("Mohammad") # the value "mohammad" that is passed inside the


function is arg.
my_function("Abdullah") # same as above

💡 A parameter is the variable listed inside the parentheses in the


function definition.

Formal Arguments: When a function is defined it may have some


parameters with the parentheses. These parameters, which receive the
values sent from the function call, are called formal arguments.

def sum(a, b):


c = a + b # a and b are formal arguments
print(c)

Actual Arguments: The parameters which we use in the function call or the
parameters which we use to send the values/data during the function call
are called actual arguments.

x = 10
y = 20
sum(x,y) # x and y are actual arguments

Python Unit 1 Notes 20


No of arguments: By default, a function must be called with the correct
number of arguments. Meaning that if your function expects 2 arguments,
you have to call a function with 2 arguments, not more, and not less.

def display(firstname, lastname):


print("The firstname is: " + firstname)
print("The lastname is: " + lastname)

display("Mohammad", "Abdullah")

Arbitrary Arguments: If you don’t know how many arguments that will be
passed into your function, add a * before a parameter name in the
function definition. This way the function will receive a tuple of arguments,
and can access the items accordingly.

def display(*names):
print("The first name is: " + names[0])
print("The last name is: " + names[1])

display("Mohammad", "Abdullah")

Keyword Arguments: You can also send arguments with the key=value
syntax. This way the order of the arguments does not matter.

def display(firstname, lastname):


print("The firstname is: " + firstname)
print("The lastname is: " + lastname)

display(lastname="Abdullah", firstname="Mohammad")

Arbitrary Keyword Arguments: If you don’t know how many keyword


arguments that will be passed into your function, add two asterisk **
before the parameter name in the function definition. This way the function
will receive a dictionary of arguments, and can access the items
accordingly.

Python Unit 1 Notes 21


def display(**names):
print("The firstname is: " + names["fname"])
print("The lastname is: " + names["lname"])

display(lname="Abdullah", fname="Mohammad")

Default Parameter Value: If we call a function without argument, it uses the


default value.

def display(name="Mohammad"):
print(name)

display() # Mohammad
display("Abdullah") # Abdullah

Passing a List as an Argument: You can send any data types of arguments
to a function (string, number, list, dictionary) and it will be treated as the
same data type inside the function.

def display(fruits):
for x in fruits:
print(x)

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

display(fruits_name)

Return Values

To let the function return a value, use the return statement.

def sum(a,b):
return a+b

print(sum(10,20)) # 30

Python Unit 1 Notes 22


Function Scope

A function defined at the module level is in global scope of that module.

Nested functions have their local scope and can access names from their
enclosing scopes.

Function Lifetime

A function object is created when its definition is executed and remains in


memory as long as there are references to it.

Function defined at the module level persist for the life of the module.

For nested functions, the lifetime can extend beyond the execution of the
enclosing function if they are returned or stored somewhere.

Decorators
Decorators are design pattern that allows you to modify or enhance the
behavior of functions or methods without permanently modifying their source
code. They wrap a function, adding extra functionality before or after the
original function runs. A decorator is essentially a function that takes another
function as an argument, adds some functionality, and returns a new
function(modified version of the original).

def make_pretty(func): # decorator


def inner():
print("I got decorated")
func()
return inner

@make_pretty # using decorator to enhance the functionality


def ordinary():
print("I am ordinary")

ordinary()
# I got decorated
# I am ordinary
---------------------------------

Python Unit 1 Notes 23


def smart_divide(func): # decorator
def inner(a,b):
if b == 0:
print("Whoops! cannot divide")
return

return func(a,b)
return inner

@smart_divide # using decorator to enhance the functionality


def divide(a,b):
print(a/b)

divide(2,5) # 0.4
divide(2,0) # whoops! cannot divide

Iterators
Iterators are methods that iterate collections like lists, tuples, etc. Using an
iterator method, we can loop through an object and return its elements. A
python iterator object must implement two special methods, iter() and next() ,
collectively called the iterator protocol.

# define a list
list = [1,2,3]

# creating iterator using iter()


iterator = iter(list)

# retreiving element of the iterator using next()


print(next(iterator)) # prints 1
print(next(iterator)) # print 2
print(next(iterator)) # print 3
print(next(iterator)) # StopIteration Exception Error

Generators

Python Unit 1 Notes 24


In python, a generator is a function that returns an iterator that produces a
sequence of values when iterated over. Generators are useful when we want
to produce a large sequence of values, but we don’t want to store all of them
in memory at once.

We define a generator function using the def keyword, but instead of the
return statement we use the yield statement. Here, the yeild keyword is

used to produce a value from the generator. When the generator function
is called, it doesn’t execute the function body immediately. Instead, it
returns a generator object that can be iterated over to produce the values.

def generator_name(arg):
# statements
yield something
--------------------------
def calc(x,y):
yield x + y
yield x - y
yield x * y
yield x / y

result = calc(20,10)
print(next(result)) # 30
print(next(result)) #
print(next(result))
print(next(result))

Modules
A module is simply a python file with .py extension that contains variables,
functions, classes and runnable code. It allows you to break your code into
separate parts, making it easier to manage, maintain, and reuse across
different projects.

Importing Modules

Python Unit 1 Notes 25


# greetings.py
def display():
print"Hello!"

# main.py
import greetings # import the whole module
greetings.display() # Hello!

from greetings import display # import the specific component


display() # Hello!

import greetings as gr # import with an alias


gr.display() # Hello!

Variables in Module

# person.py
person1 = {
"name": "Mohammad",
"age": 24
}

# main.py
import person

age = person.person1["age"]
print(age) # 24

Math Module
The built-in math module provides access to mathematical functions and
constants.

import math
print(math.pi) # 3.14159....
print(math.sqrt(16)) # 4.0

Python Unit 1 Notes 26


print(math.gcd(5,15)) # 5
print(math.ceil(1.2334)) # 2 Rounds a number up to the nearest integer
print(math.factorial(5)) # 120
print(math.pow(2,4)) # 16 Returns the value of x to the power of y

Random Module
The
module includes functions that generate random numbers and perform
random

random operations.

import random
print(random.randint(1,10)) # random integer between 1 and 10
print(random.random()) # random float between 0.0 and 1.0
names = ["Alice","Bob","Charlie"]
print(random.choice(names)) # randomly select an element from the list

Package
A package is a way of organizing related modules into a directory hierarchy. A
package is essentially a folder that contains one or more modules along with a
special __init__.py file(which can be empty or contain initialization code) to
indicate to python that the folder should be treated as a package.

# suppose you have the following directory structure:


mypackage/
__init__.py
module1.py
module2.py

# import a module from the package


import mypackage.module1

# import specific functions/classes from the module


from mypackage.module2 import some_function

Composition

Python Unit 1 Notes 27


Composition in python is an object oriented programming principle where a
class is built using one or more objects from other classes, rather than
inheriting from them. Instead of saying that a class is a type of another
class(inheritance), you say that it has a component that is an instance of the
another class.
Imagine you’re designing a simple simulation of a car. Instead of having Car
inherit from Engine, you would compose Car with an instance of an Engine:

class Engine:
def __init__(self, horsepower):
self.horsepower = horsepower

def start(self):
print("Engine starts with", self.horsepower, "horsepower.")

class Car:
def __init__(self, make, model, engine):
self.make = make
self.model = model
# Composition: Car has an Engine
self.engine = engine

def start(self):
print(f"Starting the {self.make} {self.model}...")
self.engine.start()

# Create an Engine object


my_engine = Engine(horsepower=150)

# Compose a Car with the Engine


my_car = Car(make="Toyota", model="Corolla", engine=my_engine)

# Using the composed object


my_car.start()

Python Unit 1 Notes 28


Composition allows classes to be built from other classes through a “has-
a” relationship.

It promotes encapsulation and decoupling by allowing separate classes to


handle different functionalities.

Flexibility is increased because objects can be swapped or modified at


runtime.

Python Unit 1 Notes 29

You might also like