0% found this document useful (0 votes)
7 views25 pages

Python Programming Notes

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data analysis. It features a simple syntax, supports multiple programming paradigms, and includes various built-in data types such as numeric, sequence, boolean, set, and dictionary. Python also provides various operators and control statements to facilitate programming tasks.

Uploaded by

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

Python Programming Notes

Python is a versatile programming language created by Guido van Rossum in 1991, used for web development, software development, and data analysis. It features a simple syntax, supports multiple programming paradigms, and includes various built-in data types such as numeric, sequence, boolean, set, and dictionary. Python also provides various operators and control statements to facilitate programming tasks.

Uploaded by

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

Python Module –I

What is Python?
Python is a popular programming language. It was created by Guido van
Rossum, and released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?


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

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

Key Features of Python


 Python’s simple and readable syntax makes it beginner-friendly.
 Python runs seamlessly on Windows, macOS and Linux.
 Includes libraries for tasks like web development, data analysis and machine
learning.
 Variable types are determined automatically at runtime, simplifying code
writing.
 Supports multiple programming paradigms, including object-oriented,
functional and procedural programming.
 Python is free to use, distribute and modify.

Python Data Types


Python Data types are the classification or categorization of data items. It
represents the kind of value that tells what operations can be performed on a
particular data. Since everything is an object in Python programming, Python data
types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
 Numeric - int, float, complex
 Sequence Type - string, list, tuple
 Mapping Type - dict
 Boolean - bool
 Set Type - set, frozenset
 Binary Types - bytes, bytearray, memoryview

1. Numeric Data Types in Python


The numeric data type in Python represents the data that has a numeric value. A
numeric value can be an integer, a floating number, or even a complex number.
These values are defined as Python int, Python float and Python complex classes
in Python.
 Integers - This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to
how long an integer value can be.
 Float - This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
 Complex Numbers - A complex number is represented by a complex class. It
is specified as (real part) + (imaginary part)j .

a=5
print(type(a))

b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))

Output
<class 'int'>
<class 'float'>
<class 'complex'>

2. Sequence Data Types in Python


The sequence Data Type in Python is the ordered collection of similar or different
Python data types. Sequences allow storing of multiple values in an organized and
efficient fashion. There are several sequence data types of Python:
 Python String
 Python List
 Python Tuple
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python,
there is no character data type Python, a character is a string of length one. It is
represented by str class.
Strings in Python can be created using single quotes, double quotes or even triple
quotes. We can access individual characters of a String using index.

List Data Type


Lists are just like arrays, declared in other languages which is an ordered collection
of data. It is very flexible as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square
brackets.

# Empty list
a = []

# list with int values


a = [1, 2, 3]
print(a)

# list with mixed int and string


b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Access List Items
In order to access the list items refer to the index number. In Python, negative
sequence indexes represent positions from the end of the array. Instead of having to
compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second-last item,

a = ["Geeks", "For", "Geeks"]


print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative indexing")


print(a[-1])
print(a[-3])

Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

Tuple Data Type


Just like a list, a tuple is also an ordered collection of Python objects. The only
difference between a tuple and a list is that tuples are immutable. Tuples cannot be
modified after it is created.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated
by a ‘comma’ with or without the use of parentheses for grouping the data
sequence. Tuples can contain any number of elements and of any datatype (like
strings, integers, lists, etc.).

# initiate empty tuple


tup1 = ()

tup2 = ('Geeks', 'For')


print("\nTuple with the use of String: ", tup2)
Output
Tuple with the use of String: ('Geeks', 'For')

Access Tuple Items


In order to access the tuple items refer to the index number. Use the index operator
[ ] to access an item in a tuple.

tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items


print(tup1[0])
print(tup1[-1])
print(tup1[-3])

Output
1
5
3

3. Boolean Data Type in Python


Python Data type with one of the two built-in values, True or False. Boolean
objects that are equal to True are truthy (true), and those equal to False are falsy
(false). However non-Boolean objects can be evaluated in a Boolean context as
well and determined to be true or false. It is denoted by the class bool.
Example: The first two lines will print the type of the boolean values True and
False, which is <class 'bool'>. The third line will cause an error, because true is
not a valid keyword in Python. Python is case-sensitive, which means it
distinguishes between uppercase and lowercase letters.

print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, Set is an unordered collection of data types that is iterable,
mutable, and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a
sequence by placing the sequence inside curly braces, separated by
a ‘comma’. The type of elements in a set need not be the same, various mixed-up
data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of
values, such as strings , lists , and mixed values

# initializing empty set


s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)

s2 = set(["Geeks", "For", "Geeks"])


print("Set with the use of List: ", s2)

Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}

Access Set Items


Set items cannot be accessed by referring to an index, since sets are unordered the
items have no index. But we can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using the in the keyword.
set1 = set(["Geeks", "For", "Geeks"])
print(set1)

# loop through set


for i in set1:
print(i, end=" ")

# check if item exist in set


print("Geeks" in set1)

Output
{'Geeks', 'For'}
Geeks For True
5. Dictionary Data Type
A dictionary in Python is a collection of data values, used to store data values like
a map, unlike other Python Data Types that hold only a single value as an element,
a Dictionary holds a key: value pair. Key-value is provided in the dictionary to
make it more optimized. Each key-value pair in a Dictionary is separated by a
colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary in Python
Values in a dictionary can be of any datatype and can be duplicated, whereas keys
can’t be repeated and must be immutable. The dictionary can also be created by the
built-in function dict().

0# initialize empty dictionary


d = {}

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}


print(d)

# creating dictionary using dict() constructor


d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Operators in Python
In Python programming, Operators in general are used to perform operations on
values and variables. These are standard symbols used for logical and arithmetic
operations. In this article, we will look into different types of Python operators.

 OPERATORS: These are the special symbols. Eg- + , * , /, etc.


 OPERAND: It is the value on which the operator is applied.

Types of Operators in Python


1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations
like addition, subtraction, multiplication and division.
In Python 3.x the result of division is a floating-point while in Python 2.x
division of 2 integers was an integer. To obtain an integer result in Python 3.x
floored (// integer) is used.

# Variables
a = 15
b=4

# Addition
print("Addition:", a + b)

# Subtraction
print("Subtraction:", a - b)

# Multiplication
print("Multiplication:", a * b)

# Division
print("Division:", a / b)

# Floor Division
print("Floor Division:", a // b)

# Modulus
print("Modulus:", a % b)

Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3

Comparison of Python Operators


In Python Comparison of Relational operators compares the values. It either
returns True or False according to the condition.

a = 13
b = 33

print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)

Output
False
True
False
True
False
True

Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR and Logical
NOT operations. It is used to combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or

a = True
b = False
print(a and b)
print(a or b)
print(not a)

Output
False
True
False

Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit operations. These are
used to operate on binary numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR

a = 10
b=4

print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)

Output
0
14
-11
14
2
40

Assignment Operators in Python


Python Assignment operators are used to assign values to the variables. This
operator is used to assign the value of the right side of the expression to the left
side operand.

a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

Output
10
20
10
100
102400

Identity Operators in Python


In Python, is and is not are the identity operators both are used to check if two
values are located on the same part of the memory. Two variables that are equal
do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical

a = 10
b = 20
c=a

print(a is not b)
print(a is c)

Output
True
True

Membership Operators in Python


In Python, in and not in are the membership operators that are used to test
whether a value or variable is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

x = 24
y = 20
list = [10, 20, 30, 40, 50]

if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")

if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

Output
x is NOT present in given list
y is present in given list

Ternary Operator in Python


in Python, Ternary operators also known as conditional expressions are operators
that evaluate something based on a condition being true or false. It was added to
Python in version 2.5.
It simply allows testing a condition in a single line replacing the multiline if-else
making the code compact.
Syntax : [on_true] if [expression] else [on_false]

a, b = 10, 20
min = a if a < b else b

print(min)

Output
10
Precedence and Associativity of Operators in Python
In Python, Operator precedence and associativity determine the priorities of the
operator.
Operator Precedence in Python
This is used in an expression with more than one operator with different
precedence to determine which operation to perform first.

expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")

Output
610
Hello! Welcome.

Operator Associativity in Python


If an expression contains two or more operators with the same precedence then
Operator Associativity is used to determine. It can either be Left to Right or from
Right to Left.

print(100 / 10 * 10)
print(5 - 2 + 3)
print(5 - (2 + 3))
print(2 ** 3 ** 2)

Output
100.0
6
0
512
Loops and Control Statements (continue,
break and pass) in Python

Python supports two types of loops: for loops and while loops. Alongside
these loops, Python provides control statements like continue, break,
and pass to manage the flow of the loops efficiently. This article will explore
these concepts in detail.
Table of Content
 for Loops
 while Loops
 Control Statements in Loops
o break Statement
o continue Statement
o pass Statement
for Loops
A for loop in Python is used to iterate over a sequence (such as a list, tuple,
string, or range).

# Iterating over a list


a = [1, 2, 3]
for i in a:
print(i)

Output
1
2
3

while Loops
A while loop in Python repeatedly executes a block of code as long as a
given condition is True.

# Using while loop


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

Output
0
1
2
3
4

Control Statements in Loops


Control statements modify the loop's execution flow. Python provides three
primary control statements: continue, break, and pass.

break Statement
The break statement is used to exit the loop prematurely when a certain
condition is met.

# Using break to exit the loop


for i in range(10):
if i == 5:
break
print(i)

Output
0
1
2
3
4

Explanation:
 The loop prints numbers from 0 to 9.
 When i equals 5, the break statement exits the loop.

continue Statement
The continue statement skips the current iteration and proceeds to the next
iteration of the loop.

# Using continue to skip an iteration


for i in range(10):
if i % 2 == 0:
continue
print(i)
Output
1
3
5
7
9

Explanation:
 The loop prints odd numbers from 0 to 9.
 When i is even, the continue statement skips the current iteration.

pass Statement
The pass statement is a null operation; it does nothing when executed. It's
useful as a placeholder for code that you plan to write in the future.

# Using pass as a placeholder


for i in range(5):
if i == 3:
pass
print(i)

Output
0
1
2
3
4
Python Arrays

Lists in Python are the most flexible and commonly used data structure for
sequential storage. They are similar to arrays in other languages but with
several key differences:
 Dynamic Typing: Python lists can hold elements of different types in
the same list. We can have an integer, a string and even other lists all
stored within a single list.
 Dynamic Resizing: Lists are dynamically resized, meaning you can add
or remove elements without declaring the size of the list upfront.
 Built-in Methods: Python lists come with numerous built-in methods
that allow for easy manipulation of the elements within them, including
methods for appending, removing, sorting and reversing elements.

a = [1, "Hello", [3.14, "world"]]


a.append(2) # Add an integer to the end
print(a)

Output
[1, 'Hello', [3.14, 'world'], 2]

NumPy Arrays
NumPy arrays are a part of the NumPy library, which is a powerful tool for
numerical computing in Python. These arrays are designed for high-
performance operations on large volumes of data and support multi-
dimensional arrays and matrices. This makes them ideal for complex
mathematical computations and large-scale data processing.

Key Features:
 Multi-dimensional support: NumPy arrays can handle more than one
dimension, making them suitable for matrix operations and more
complex mathematical constructs.
 Broad broadcasting capabilities: They can perform operations
between arrays of different sizes and shapes, a feature known as
broadcasting.
 Efficient storage and processing: NumPy arrays are stored more
efficiently than Python lists and provide optimized performance for
numerical operations.
import numpy as np

# Creating a NumPy array


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

# Element-wise operations
print(arr * 2)

# Multi-dimensional array
arr2d = np.array([[1, 2], [3, 4]])
print(arr2d * 2)

Output
[2 4 6 8]
[[2 4]
[6 8]]

Python Arrays
In Python, array is a collection of items stored at contiguous memory
locations. The idea is to store multiple items of the same type together.
Unlike Python lists (can store elements of mixed types), arrays must have
all elements of same type. Having only homogeneous elements makes it
memory-efficient.

import array as arr

# creating array of integers


a = arr.array('i', [1, 2, 3])

# accessing First Araay


print(a[0])

# Adding element to array


a.append(5)
print(a)

Output
1
array('i', [1, 2, 3, 5])
Create an Array in Python
Array in Python can be created by importing an array
module. array( data_type , value_list ) is used to create array in Python
with data type and value list specified in its arguments.

import array as arr

# creating array
a = arr.array('i', [1, 2, 3])

# iterating and printing each item


for i in range(0, 3):
print(a[i], end=" ")

Output
1 2 3

Python Array Index

Adding Elements to an Array


Elements can be added to the Python Array by using built-
in insert() function. Insert is used to insert one or more data elements into
an array. Based on the requirement, a new element can be added at the
beginning, end, or any given index of array. append() is also used to add
the value mentioned in its arguments at the end of the Python array.

import array as arr

# Integer array example


a = arr.array('i', [1, 2, 3])
print("Integer Array before insertion:", *a)

a.insert(1, 4) # Insert 4 at index 1


print("Integer Array after insertion:", *a)

Output
Integer Array before insertion: 1 2 3
Integer Array after insertion: 1 4 2 3
.
Accessing Array Items
In order to access the array items refer to the index number. Use the index
operator [ ] to access an item in a array in Python. The index must be an
integer.

import array as arr


a = arr.array('i', [1, 2, 3, 4, 5, 6])

print(a[0])
print(a[3])

b = arr.array('d', [2.5, 3.2, 3.3])


print(b[1])
print(b[2])

Output
1
4
3.2
3.3

Removing Elements from the Array


Elements can be removed from the Python array by using built-
in remove() function. It will raise an Error if element doesn’t exist. Remove()
method only removes the first occurrence of the searched element. To
remove range of elements, we can use an iterator.
pop() function can also be used to remove and return an element from the
array. By default it removes only the last element of the array. To remove
element from a specific position, index of that item is passed as an
argument to pop() method.
import array
arr = array.array('i', [1, 2, 3, 1, 5])

# using remove() method to remove first occurance of 1


arr.remove(1)
print(arr)

# pop() method - remove item at index 2


arr.pop(2)
print(arr)

Output
array('i', [2, 3, 1, 5])
array('i', [2, 3, 5])

Slicing of an Array
In Python array, there are multiple ways to print the whole array with all the
elements, but to print a specific range of elements from the array, we
use Slice operation .

 Elements from beginning to a range use [:Index]


 Elements from end use [:-Index]
 Elements from specific Index till the end use [Index:]
 Elements within a range, use [Start Index:End Index]
 Print complete List, use [:].
 For Reverse list, use [::-1].
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)

Sliced_array = a[3:8]
print(Sliced_array)

Sliced_array = a[5:]
print(Sliced_array)

Sliced_array = a[:]
print(Sliced_array)

Output
array('i', [4, 5, 6, 7, 8])
array('i', [6, 7, 8, 9, 10])
array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Searching Element in an Array


In order to search an element in the array we use a python in-
built index() method. This function returns the index of the first occurrence
of value mentioned in arguments.
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# index of 1st occurrence of 2


print(arr.index(2))

# index of 1st occurrence of 1


print(arr.index(1))

Output
1
0
Updating Elements in an Array
In order to update an element in the array we simply reassign a new value
to the desired index we want to update.
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])

# update item at index 2


arr[2] = 6
print(arr)

# update item at index 4


arr[4] = 8
print(arr)

Output
array('i', [1, 2, 6, 1, 2, 5])
array('i', [1, 2, 6, 1, 8, 5])

Different Operations on Python Arrays


Counting Elements in an Array
We can use count() method to count given item in array.

import array

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


count = arr.count(2)

print("Number of occurrences of 2:", count)

Output
Number of occurrences of 2: 3

Reversing Elements in an Array


In order to reverse elements of an array we need to simply use reverse
method.
import array
arr = array.array('i', [1, 2, 3, 4, 5])

arr.reverse()
print("Reversed array:", *arr)

Output
Reversed array: 5 4 3 2 1

Python Functions


Python Functions is a block of statements that return the specific task.


The idea is to put some commonly or repeatedly done tasks together and
make a function so that instead of writing the same code again and again
for different inputs, we can do the function calls to reuse code contained in
it over and over again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Python Function Declaration


The syntax to declare a function is:

Synta
x of Python Function Declaration

Types of Functions in Python


Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python that
are available to use.
 User-defined function: We can create our own functions based on our
requirements.

Creating a Function in Python


We can define a function in Python, using the def keyword. We can add
any type of functionalities and properties to it as we require. By the
following example, we can understand how to write a function in Python. In
this way we can create Python function definition by using def keyword.

# A simple Python function


def fun():
print("Welcome to GFG")

Calling a Function in Python


After creating a function in Python we can call it by using the name of the
functions Python followed by parenthesis containing parameters of that
particular function. Below is the example for calling def function Python.

# A simple Python function


def fun():
print("Welcome to GFG")

# Driver code to call a function


fun()

Output
Welcome to GFG

Python Function with Parameters


If you have experience in C/C++ or Java then you must be thinking about
the return type of the function and data type of arguments. That is possible
in Python as well (specifically for Python 3.5 and above).

Python Function Syntax with Parameters


def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy