Python
Python
Fantastic notes
Python Notes
Created by GPA HOSTELER
BINODPC
24
Files
Files
What is a file?
File is a named location on disk to store related information. It is used to
permanently store data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when
computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tiedwith the file are freed.
1. Open a file
2. Read or write (perform operation)
3. Close the file
File Handling
The key function for working with files in Python is the open() function.
exist
"a" - Append - Opens a file for appending, creates the file if it does not exis
"w" - Write - Opens a file for writing, truncating (remove) the file first.
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text
mode
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt","r")
Note: Make sure the file exists, or else you will get an error.
Assume we have the following file, located in the same folder as Python:
demofile.txt
Example
f = open("demofile.txt", "r")
print(f..read())
Read Only Parts of the File
By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
Example
Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))
Read Lines
You can return one line by using the readline()method:
Example
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline()two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Run example »
By looping through the lines of the file, you can read the whole file, line by
line:
Example
Loop through the file line by line:
f = open("demofile.txt", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Run example »
Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.
Write to an Existing File
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.cose()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.cose()
f = open("demofile3.txt", "r")
print(f.read())
Note: the "w" method will overwrite the entire file.
Create a New File
To create a new file in Python, use the open() method, with one of the
following parameters:
"x" - Create - will create a file, returns an error if the file exist "a" - Append
- will create a file if the specified file does not exist"w" - Write - will create a
file if the specified file does not exist
Example
Create a file called "myfile.txt":
f = open("myfile.txt", "x")
Result: a new empty file is created!
Example
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before
you try to delete it:
Example
Check if file exists, then delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The filedoes not exist")
Delete Folder
To delete an entire folder, use the os.rmdir() method:
Example
Remove the folder "myfolder":
import os
os.rmdir("myfolder")
There are various methods available for this purpose. We can use
the read(size) method to read in size number of data. If size parameter is
not specified, it reads and returns up to the end of the file.
>>> f.readlines()
[ 'This is my first file\n', 'This file\n', 'contains three lines\n']
Errors are problems in a program that causes the program to stop its execution. On
the other hand, exceptions are raised when some internal events change the program’s
normal flow.
Table of Content
• Syntax Errors in Python
• Python Logical Errors (Exception)
• Common Builtin Exceptions
• Error Handling
Exception: matlab ek error jo program chalate waqt hoti hai. Python mein, jab error
aati hai to program crash nahi hota balki aap use handle kar sakte ho try aur except
blocks ka use karke, taaki aap decide kar sako ki error hone par kya karna hai.
When the proper syntax of the language is not followed then a syntax error is thrown.
Example: It returns a syntax error message because after the if statement a colon: is
missing. We can fix this by writing the correct syntax.
Python3
# initialize the amount variable
amount = 10000
Output:
1. No Syntax Error: The code runs successfully without any syntax errors.
2. Unexpected Output: The program produces output that is different from
what is expected.
3. Difficult to Detect: Logical errors can be subtle and are often harder to
identify and fix compared to syntax errors because the program appears to
run correctly.
4. Varied Causes: They can arise from incorrect assumptions, faulty logic,
improper use of operators, or incorrect sequence of instructions.
Example of a Logical Error
Consider a simple example where we want to compute the average of a list of
numbers:
Python
numbers = [10, 20, 30, 40, 50]
total = 0
Exception Description
Error Handling
When an error and an exception are raised then we handle that with the help of the
Handling method.
Handling Exceptions with Try/Except/Finally
We can handle errors by the Try/Except/Finally method. we write unsafe code in the
try, fall back code in except and final code in finally block.
Python
# put unsafe operation in try block
try:
print("code start")
we will see the difference between Python’s Module, Package, and Library. We
will also see some examples of each to things more clear.
Examples of modules
1. Datetime
2. Regex
3. Random etc.
Example: Save the code in a file called demo_module.py
• Python3
def myModule(name):
Import module named demo_module and call the myModule function inside it.
• Python3
import demo_module
demo_module.myModule("Math")
Output:
This is My Module : Math
Examples of Packages:
1. Numpy
2. Pandas
Example:
Student(Package)
| __init__.py (Constructor)
| details.py (Module)
| marks.py (Module)
| collegeDetails.py (Module)
The library is having a collection of related functionality of codes that allows you
to perform many tasks without writing your code. It is a reusable chunk of code
that we can use by importing it into our program, we can just use it by
importing that library and calling the method of that library with a period(.).
However, it is often assumed that while a package is a collection of modules, a
library is a collection of packages.
Examples of Libraries:
1. Matplotlib
2. Pytorch
3. Pygame
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
4. Seaborn etc.
Example:
Importing pandas library and call read_csv method using an alias of pandas i.e.
pd.
• Python3
import pandas as pd
df = pd.read_csv("file_name.csv")
What is NumPy?
Features of NumPy
NumPy has various features which make them popular over lists.
Some of these important features include:
Numpy can be installed for Mac and Linux users via the following pip command:
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Arrays in NumPy
Size of array: 6
Array stores elements of type: int64
NumPy Array Creation
There are various ways of Numpy array creation in Python. They are as follows:
1. Create NumPy Array with List and Tuple
You can create an array from a regular Python list or tuple using the array()
function. The type of the resulting array is deduced from the type of the elements
in the sequences. Let’s see this implementation:
Python
import numpy as np
Output:
An array initialized with all zeros:
[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]
An array initialized with all 6s.Array type is complex:
[[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]
[6.+0.j 6.+0.j 6.+0.j]]
A random array:
[[0.15471821 0.47506745]
[0.03637972 0.15772238]]
3. Create Using arange() Function
arange(): This function returns evenly spaced values within a given
interval. Step size is specified.
Python
# Create a sequence of integers
# from 0 to 30 with steps of 5
f = np.arange(0, 30, 5)
print ("A sequential array with steps of 5:\n", f)
Output:
A sequential array with steps of 5:
[ 0 5 10 15 20 25]
newarr = arr.reshape(2, 2, 3)
# An exemplar array
arr = np.array([[-1, 2, 0, 4],
[4, -0.5, 6, 0],
[2.6, 0, 7, 8],
[3, -7, 4, 2.0]])
# Slicing array
temp = arr[:2, ::2]
print ("Array with first 2 rows and alternate"
"columns(0 and 2):\n", temp)
a = np.array([1, 2, 5, 3])
# transpose of array
a = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]])
import numpy as np
a = np.array([[1, 2],
[3, 4]])
b = np.array([[4, 3],
[2, 1]])
# add arrays
print ("Array sum:\n", a + b)
# matrix multiplication
print ("Matrix multiplication:\n", a.dot(b))
Output:
Array sum:
[[5 5]
[5 5]]
Array multiplication:
[[4 6]
[6 4]]
Matrix multiplication:
[[ 8 5]
[20 13]]
Also Read: Numpy Binary Operations
NymPy’s ufuncs
NumPy provides familiar mathematical functions such as sin, cos, exp, etc. These
functions also operate elementwise on an array, producing an array as output.
Note: All the operations we did above using overloaded operators can be done
using ufuncs like np.add, np.subtract, np.multiply, np.divide, np.sum, etc.
Panda
To create Series with any of the methods make sure to import pandas library.
Creating an empty Series: Series() function of Pandas is used to create a series.
A basic series, which can be created is an Empty Series.
• Python3
# import pandas as pd
import pandas as pd
ser = pd.Series()
print(ser)
Output :
Series([], dtype: float64)
By default, the data type of Series is float.
Creating a series from array: In order to create a series from NumPy array, we
have to import numpy module and have to use array() function.
• Python3
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
ser = pd.Series(data)
print(ser)
Output:
By default, the index of the series starts from 0 till the length of series -1.
Creating a series from array with an index: In order to create a series by
explicitly proving index instead of the default, we have to provide a list of elements
to the index parameter with the same number of elements as it is an array.
• Python3
# import pandas as pd
import pandas as pd
# import numpy as np
import numpy as np
# simple array
# providing an index
print(ser)
Output:
Creating a series from Lists: In order to create a series from list, we have to first
create a list after that we can create a series from list.
• Python3
import pandas as pd
# a simple list
ser = pd.Series(list)
print(ser)
Output :
Creating a series from Dictionary: In order to create a series from the dictionary,
we have to first create a dictionary after that we can make a series using dictionary.
Dictionary keys are used to construct indexes of Series.
• Python3
import pandas as pd
# a simple dictionary
'for': 20,
'geeks': 30}
ser = pd.Series(dict)
print(ser)
Output:
Creating a series from Scalar value: In order to create a series from scalar value,
an index must be provided. The scalar value will be repeated to match the length of
the index.
• Python3
import pandas as pd
import numpy as np
print(ser)
Output:
Creating a series using NumPy functions : In order to create a series using numpy
function, we can use different function of numpy
like numpy.linspace(), numpy.random.radn().
• Python3
import pandas as pd
import numpy as np
print(ser1)
print(& quot
\n" , ser2)
Output:
• Python3
# code
import pandas as pd
ser=pd.Series(range(10))
print(ser)
Output:
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
8 8
9 9
dtype: int64
Creating a Series using for loop and list comprehension:
• Python3
import pandas as pd
print(ser)
Output:
a 1
b 4
c 7
d 10
e 13
f 16
g 19
dtype: int64
Creating a Series using mathematical expressions:
• Python3
import pandas as pd
import numpy as np
ser=np.arange(10,15)
serobj=pd.Series(data=ser*5,index=ser)
print(serobj)
Output:
10 50
11 55
12 60
13 65
14 70
dtype: int32
Function
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
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
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
can understand how to write a function in Python. In this way we can create
Python function definition by using def keyword.
Python
# 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.
Python
# A simple Python function
def fun():
print("Welcome to GFG")
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
Output:
The addition of 5 and 15 results 20.
Note: The following examples are defined using syntax 1, try to convert them in
syntax 2 for practice.
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Python
# some more functions
def is_prime(n):
if n in [2, 3]:
return True
if (n == 1) or (n % 2 == 0):
return False
r=3
while r * r <= n:
if n % r == 0:
return False
r += 2
return True
print(is_prime(78), is_prime(79))
Output:
False True
Arguments are the values passed inside the parenthesis of the function. A function
can have any number of arguments separated by a comma.
In this example, we will create a simple function in Python to check whether the
number passed as an argument to the function is even or odd.
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
Default Arguments
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
Positional Arguments
We used the Position argument during the function call so that the first argument
(or value) is assigned to name and the second argument (or value) is assigned to
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
age. By changing the position, or if you forget the order of the positions, the values
can be used in the wrong places, as shown in the Case-2 example below, where
27 is assigned to the name and Suraj is assigned to the age.
Python
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
to
GeeksforGeeks
Example 2: Variable length keyword arguments
Python
# Python program to illustrate
# *kwargs for variable number of keyword arguments
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
Output:
first == Geeks
mid == for
last == Geeks
Docstring
The first string after the function is called the Document string or Docstring in
short. This is used to describe the functionality of the function. The use of
docstring in functions is optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.
Syntax: print(function_name.__doc__)
Example: Adding Docstring to the function
Python
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""
if (x % 2 == 0):
print("even")
else:
print("odd")
def f1():
s = 'I love GeeksforGeeks'
def f2():
print(s)
f2()
# Driver's code
f1()
Output:
I love GeeksforGeeks
print(cube(7))
print(cube_v2(7))
Output:
343
343
Recursion in Python refers to when a function calls itself. There are many
instances when you have to build a recursive function to solve Mathematical and
Recursive Problems.
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
print(factorial(4))
Output
24
Here we have created a recursive function to calculate the factorial of the number.
You can see the end statement for this function is when n is equal to 0.
The function return statement is used to exit from a function and go back to the
function caller and return the specified value or data item to the caller. The syntax
for the return statement is:
return [expression_list]
The return statement can consist of a variable, an expression, or a constant which
is returned at the end of the function execution. If none of the above is present
with the return statement a None object is returned.
Example: Python Function Return Statement
Python
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2
print(square_value(2))
print(square_value(-4))
Output:
4
16
One important thing to note is, in Python every variable name is a reference. When
we pass a variable to a function Python, a new reference to the object is created.
Parameter passing in Python is the same as reference passing in Java.
Python
# Here x is a new reference to same list lst
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
def myFun(x):
x[0] = 20
Output:
10
Exercise: Try to guess the output of the following code.
Python
def swap(x, y):
temp = x
x=y
y = temp
# Driver code
x=2
y=3
swap(x, y)
print(x)
print(y)
Output:
2
3
Quick Links
• Quiz on Python Functions
• Difference between Method and Function in Python
• First Class functions in Python
• Recent articles on Python Functions.
FAQs- Python Functions
What is function in Python?
Python function is a block of code, that runs only when it is called. It is
programmed to return the specific task. You can pass values in functions called
parameters. It helps in performing repetitive tasks.
Array
Output
The new created array is : 1 2 3
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Now we will see how to use array in Python 3.8 with example.
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.
3.2, 3.3] is created and printed before and after appending the double 4.4 to the
array.
Python
import array as arr
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Output
Array before insertion : 1 2 3
Output
Access element is: 1
print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")
print("\r")
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")
Output
The new created array is : 1 2 3 1 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. Slice operation is performed on array with the use of colon(:). To print
elements from beginning to a range use [:Index], to print elements from end use
[:-Index], to print elements from specific Index till the end use [Index:], to print
elements within a range, use [Start Index:End Index] and to print whole List with
the use of slicing operation, use [:]. Further, to print whole array in reverse order,
use [::-1].
This code employs slicing to extract elements or subarrays from an array. It starts
with an initial array of integers and creates an array from the list. The code slices
the array to extract elements from index 3 to 8, from index 5 to the end, and the
entire array and In below code Python print array as The sliced arrays are then
printed to demonstrate the slicing operations.
Python
import array as arr
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)
Output
Initial Array:
1 2 3 4 5 6 7 8 9 10
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.
Example: The code demonstrates how to create array in Python, print its
elements, and find the indices of specific elements. It imports the array module,
creates an array of integers, prints the array using a for loop, and then uses
the index() method to find the indices of the first occurrences of the integers 2 and
1.
Python
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("The new created array is : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))
Output
The new created array is : 1 2 3 1 2 5
In order to update an element in the array we simply reassign a new value to the
desired index we want to update.
Example: This code illustrates the functionality of modifying elements within an
array using indexing. It imports the array module, creates an array of integers, and
prints the initial array. Then, it modifies two elements of the array at specific
indexes and prints the updated array. This serves to demonstrate how indexing
allows for dynamic manipulation of array contents.
Python
import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("Array before updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print()
arr[4] = 8
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
Output
Array before updation : 1 2 3 1 2 5
import array
my_array = array.array('i', [1, 2, 3, 4, 5])
print("Original array:", *my_array)
my_array.reverse()
print("Reversed array:", *my_array)
Output
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
In the article, we will cover the python list extend() and try to understand
the Python list extend().
What is extend element from array?
In Python, an array is used to store multiple values or elements of the same
datatype in a single variable. The extend() function is simply used to attach an
item from iterable to the end of the array. In simpler terms, this method is used to
add an array of values to the end of a given or existing array.
Syntax of list extend()
The syntax of the extend() method:
list.extend(iterable)
Here, all the element of iterable are added to the end of list1
Example 1:
The provided code demonstrates the capability of extending an array to include
additional elements. It imports the array module using an alias, creates an array
of integers, prints the array before extension, extends the array using
the extend() method, and finally prints the extended array. This concisely
illustrates the ability to add elements to an existing array structure
Python
import array as arr
a = arr.array('i', [1, 2, 3,4,5])
print("The before array extend : ", end =" ")
for i in range (0, 5):
print()
a.extend([6,7,8,9,10])
print("\nThe array after extend :",end=" ")
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
for i in range(0,10):
print(a[i],end=" ")
print()
Output
The before array extend : 1 2 3 4 5
Dictionary
A Python dictionary is a data structure that stores the value in key:value pairs.
Example:
Python dictionaries are essential for efficient data mapping and manipulation in
programming. To deepen your understanding of dictionaries and explore
advanced techniques in data handling, consider enrolling in our Complete
Machine Learning & Data Science Program . This course covers everything
from basic dictionary operations to advanced data processing methods,
empowering you to become proficient in Python programming and data analysis.
Python
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
Output:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Python
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dictionary Example
A dictionary can also be created by the built-in function dict(). An empty
dictionary can be created by just placing curly braces{}.
The addition of elements can be done in multiple ways. One value at a time can
be added to a Dictionary by defining value along with the key e.g. Dict[Key] =
‘Value’.
Updating an existing value in a Dictionary can be done by using the built-
in update() method. Nested key values can also be added to an existing
Dictionary.
Note- While adding a value, if the key-value already exists, the value gets updated
otherwise a new Key with the value is added to the Dictionary.
Example: Add Items to a Python Dictionary with Different DataTypes
The code starts with an empty dictionary and then adds key-value pairs to it. It
demonstrates adding elements with various data types, updating a key’s value,
and even nesting dictionaries within the main dictionary. The code shows how to
manipulate dictionaries in Python.
Python
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'Geeks'
Dict[2] = 'For'
Dict[3] = 1
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'Welcome'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'Life', '2': 'Geeks'}}
print("\nAdding a Nested Key: ")
print(Dict)
Output:
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1}
Dictionary after adding 3 elements:
{0: 'Geeks', 2: 'For', 3: 1, 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'Geeks', 2: 'Welcome', 3: 1, 'Value_set': (2, 3, 4), 5:
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
To access the items of a dictionary refer to its key name. Key can be used inside
square brackets.
Access a Value in Python Dictionary
The code demonstrates how to access elements in a dictionary using keys. It
accesses and prints the values associated with the keys ‘name’ and 1, showcasing
that keys can be of different data types (string and integer).
Python
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using key:")
print(Dict[1])
Output:
Accessing a element using key:
For
Accessing a element using key:
Geeks
There is also a method called get() that will also help in accessing the element
from a dictionary. This method accepts key as argument and returns the value.
Complexities for Accessing elements in a Dictionary:
• Time complexity: O(1)
• Space complexity: O(1)
The code demonstrates accessing a dictionary element using the get() method
To access the value of any key in the nested dictionary, use indexing [] syntax.
Dict = {'Dict1': {1: 'Geeks'},
'Dict2': {'Name': 'For'}}
print(Dict['Dict1'])
print(Dict['Dict1'][1])
print(Dict['Dict2']['Name'])
Output:
{1: 'Geeks'}
Geeks
For
The items of the dictionary can be deleted by using the del keyword as given
below.
print("Dictionary =")
print(Dict)
del(Dict[1])
print("Data after deletion Dictionary=")
print(Dict)
Output
Dictionary Methods
Method Description
Method Description
Method Description
List
In Python, a list is a collection data type that is ordered, mutable, and allows duplicate
elements. Lists are one of the most commonly used data structures and provide a
versatile way to work with sequences of elements. Here is a detailed explanation of
lists in Python:
Creating a List
You can create a list by placing elements inside square brackets [], separated by
commas.
You can access elements in a list using indexing. Python uses zero-based indexing,
meaning the first element has an index of 0
You can retrieve a subset of a list by using slicing. Slicing is done using the colon :
operator.
You can add elements to a list using methods like append(), insert(), and extend().
You can remove elements from a list using methods like remove(), pop(), and del.
List comprehensions provide a concise way to create lists. They consist of brackets
containing an expression followed by a for clause.
python
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Copy code
# Creating a list of squares from 0 to 9
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Common List Methods
Lists are powerful and versatile, making them a fundamental part of Python
programming.
List Array
List Array
Nested lists can be of variable size Nested arrays has to be of same size.
Example:
Example:
import array
my_list = [1, 2, 3, 4]
arr = array.array(‘i’, [1, 2, 3])
• Python3
count = 0
count = count+1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
See this for an example where a while loop is used for iterators. As mentioned in
the article, it is not recommended to use a while loop for iterators in python.
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is a “for in”
loop which is similar to for each loop in other languages.
• Python3
print("List Iteration")
for i in l:
print(i)
print("\nTuple Iteration")
for i in t:
print(i)
print("\nString Iteration")
s = "Geeks"
for i in s :
print(i)
print("\nDictionary Iteration")
d = dict()
d['xyz'] = 123
d['abc'] = 345
for i in d :
Output:
List Iteration
geeks
for
geeks
Tuple Iteration
geeks
for
geeks
String Iteration
G
e
e
k
s
Dictionary Iteration
xyz 123
abc 345
Time complexity: O(n), where n is the number of elements in the iterable (list,
tuple, string, or dictionary).
Auxiliary space: O(1), as the space used by the program does not depend on the
size of the iterable.
We can use a for-in loop for user-defined iterators. See this for example.
Python programming language allows using one loop inside another loop. The
following section shows a few examples to illustrate the concept.
The syntax for a nested for loop statement in Python programming language is as
follows:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in Python programming language is
as follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other
type of loop. For example, a for loop can be inside a while loop or vice versa.
• Python3
for j in range(i):
print()
Output:
1
22
333
4444
Python Loop Control Statements
Loop control statements change execution from their normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.
Python Continue
• Python3
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
continue
Output:
Current Letter : g
Current Letter : t
Current Letter : m
Python Break
• Python3
# or 's'
break
Output:
Current Letter : e
Python Pass
We use pass statements to write empty loops. Pass is also used for empty control
statements, functions, and classes.
• Python3
# An empty loop
pass
Output:
Last Letter : s
• Python If Statement
• Python If Else Statement
• Python Nested If Statement
• Python Elif
• Ternary Statement | Short Hand If Else Statement
Python If Statement
if condition:
# Statements to execute if
# condition is true
As we know, Python uses indentation to identify a block. So the block under the
Python if statements will be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.
Example of Python if Statement
As the condition present in the if statements in Python is false. So, the block below
the if statement is executed.
Python
# python program to illustrate If statement
i = 10
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
Python If Else Statement
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But if we want to do something
else if the condition is false, we can use the else statement with the if statement
Python to execute a block of code when the Python if condition is false.
Flowchart of If Else Statement
Let’s look at the flow of code in an if else Python statement.
The block of code following the else if in Python, the statement is executed as the
condition present in the if statement is false after calling the statement which is not
in the block(without spaces).
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Python
# python program to illustrate else if in Python statement
#!/usr/bin/python
i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")
Output:
iisgreaterthan15
i'minelseBlock
i'm not in if and not in else Block
If Else in Python using List Comprehension
# Initializing list
List = [367, 111, 562, 945, 6726, 873]
Yes, Python allows us to nest if statements within if statements. i.e., we can place
an if statement inside another if statement.
Flowchart of Python Nested if Statement
if(condition1):
#Executeswhencondition1istrue
if(condition2):
#Executeswhencondition2istrue
#ifBlockisendhere
# if Block is end here
In this example, we are showing nested if conditions in the code, All the If condition
in Python will be executed one by one.
Python
# python program to illustrate nested If statement
i = 10
if (i == 10):
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")
Output:
i is smaller than 15
i is smaller than 12 too
Python Elif
Here, a user can decide among multiple options. The if statements are executed
from the top down.
As soon as one of the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final “else” statement will be executed.
Flowchart of Elif Statement in Python
Let’s look at the flow of control in if-elif-else ladder:
if(condition):
statement
elif(condition):
statement
.
.
else:
statement
Example of Python if-elif-else ladder
In the example, we are showing single if in Python, multiple elif conditions, and
single else condition.
Python
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python
i = 25
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Output:
i is not present
Whenever there is only a single statement to be executed inside the if block then
shorthand if can be used. The statement can be put on the same line as the if
statement.
Example of Python If shorthand
In the given example, we have a condition that if the number is less than 15, then
further code will be executed.
if condition: statement
Python
# Python program to illustrate short hand if
i = 10
if i < 15: print("i is less than 15")
Output
i is less than 15
Example of Short Hand If Else Statements
This can be used to write the if-else statements in a single line where only one
statement is needed in both the if and else blocks.
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
The if-else statement in Python is used to control the flow of the program based on
a condition. It has the following syntax:
if..condition:
#Execute..this..block..if..conditions..True
else:
# Execute this block if condition is False
For example:
x=10
if..x>5:
print("x..is..greater..than..5")
else:
print("x is not greater than 5")
A single if condition can have at most one else statement. However, you can have
multiple elif (else if) statements to check additional conditions if needed:
x=10
if..x>15:
print("x..is..greater..than..15")
elif..x>5:
print("x..is..greater..than..5..but..not..greater..than..15")
else:
print("x is 5 or less")
In Python, control statements are used to alter the flow of execution based on
specific conditions or looping requirements. The main types of control statements
are:
• Conditional statements: if, else, elif
• Looping statements: for, while
• Control flow statements: break, continue, pass, return
What are the two types of control statements?
The two primary types of control statements in Python are:
• Conditional statements: Used to execute code based on certain conditions
(if, else, elif).
• Looping statements: Used to execute code repeatedly until a condition is met
(for, while).
Are control statements and conditional statements the same?
No, control statements and conditional statements are not exactly the same.
• Conditional statements (if, else, elif) specifically deal with checking
conditions and executing code based on whether those conditions
are True or False.
• Control statements encompass a broader category that includes both
conditional statements (if, else, elif) and looping statements (for, while), as
well as other statements (break, continue, pass, return) that control the flow of
execution in a program.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
6. Identity Operators and Membership Operators
Multiplication: multiplies
* x*y
two operands
second
Division Operators
Float division
The quotient returned by this operator is always a float number, no matter if two
numbers are integers. For example:
Example: The code performs division operations and prints the results. It
demonstrates that both integer and floating-point divisions return accurate results.
For example, ’10/2′ results in ‘5.0’, and ‘-10/2’ results in ‘-5.0’.
Python
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output:
1.0
5.0
-5.0
10.0
The quotient returned by this operator is dependent on the argument being passed.
If any of the numbers is float, it returns output in float. It is also known as Floor
division because, if any number is negative, then the output will be floored. For
example:
Example: The code demonstrates integer (floor) division operations using the // in
Python operators. It provides results as follows: ’10//3′ equals ‘3’, ‘-
5//2’ equals ‘-3’, ‘5.0//2′ equals ‘2.0’, and ‘-5.0//2’ equals ‘-3.0’. Integer division
returns the largest integer less than or equal to the division result.
Pythons
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output:
3
-3
2.0
-3.0
1. P – Parentheses
2. E – Exponentiation
3. M – Multiplication (Multiplication and division have the same precedence)
4. D – Division
5. A – Addition (Addition and subtraction have the same precedence)
6. S – Subtraction
The modulus of Python operators helps us extract the last digit/s of a number. For
example:
• x % 10 -> yields the last digit
• x % 100 -> yield last two digits
Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and
Power
Here is an example showing how different Arithmetic Operators in Python work:
Example: The code performs basic arithmetic operations with the values
of ‘a’ and ‘b’. It adds (‘+’), subtracts (‘-‘), multiplies (‘*’), computes the
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
remainder (‘%’), and raises a to the power of ‘b (**)’. The results of these
operations are printed.
Python
a=9
b=4
add = a + b
sub = a - b
mul = a * b
mod = a % b
p = a ** b
print(add)
print(sub)
print(mul)
print(mod)
print(p)
Output:
13
5
36
1
6561
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
False
True
False
True
Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.
Operator Description Syntax
print(not a)
Output
False
True
False
Python Bitwise operators act on bits and perform bit-by-bit operations. These are
used to operate on binary numbers.
Operator Description Syntax
| Bitwise OR x|y
~ Bitwise NOT ~x
Example: The code demonstrates various bitwise operations with the values
of ‘a’ and ‘b’. It performs bitwise AND (&), OR (|), NOT (~), XOR (^), right
shift (>>), and left shift (<<) operations and prints the results. These operations
manipulate the binary representations of the numbers.
Python
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
The Python Bitwise AND (&) operator takes two equal-length bit patterns as
parameters. The two-bit integers are compared. If the bits in the compared positions
of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 .
Take Bitwise and of both X & y
Note: Here, (111)2 represent binary number.
Python
a = 10
b=4
The Python Bitwise OR (|) Operator takes two equivalent length bit designs as
boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not,
it is 1.
Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 .
Take Bitwise OR of both X, Y
Python
a = 10
b=4
The Python Bitwise XOR (^) Operator also known as the exclusive OR operator,
is used to perform the XOR operation on two operands. XOR stands for “exclusive
or”, and it returns true if and only if exactly one of the operands is true. In the
Python
a = 10
b=4
The preceding three bitwise operators are binary operators, necessitating two
operands to function. However, unlike the others, this operator operates with only
one operand.
The Python Bitwise Not (~) Operator works with a single value and returns its
one’s complement. This means it toggles all bits in the value, transforming 0 bits
to 1 and 1 bits to 0, resulting in the one’s complement of the binary number.
Example: Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT
of X.
Python
a = 10
b=4
Output
~a = -11
Bitwise Shift
These operators are used to shift the bits of a number left or right thereby
multiplying or dividing the number by two respectively. They can be used when
we have to multiply or divide a number by two.
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
Python
a = 10
b = -10
Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
Python
a=5
b = -10
Divide(floor) AND:
Divide left operand with
//= right operand and then a//=b a=a//b
assign the value(floor) to
left operand
Exponent AND:
Calculate exponent(raise
**= power) value using a**=b a=a**b
operands and assign
value to left operand
Performs Bitwise OR on
|= operands and assign a|=b a=a|b
value to left 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
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
print(a is not b)
print(a is c)
Output
True
True
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
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):
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Output
x is NOT present in given list
y is present in given list
print(min)
Output:
10
Python
expr = 10 + 20 * 30
print(expr)
name = "Alex"
age = 0
Output
610
Hello! Welcome.
Output
100.0
6
0
512
Fundamental Concepts
What is Python
Here we provided the latest Python 3 version compiler where you can edit and
compile your written code directly with just one click of the RUN Button. So test
yourself with Python’s first exercises.
Python
print("Hello World! I Don't Give a Bug")
Output
Hello World! I Don't Give a Bug
Comments in Python
Comments in Python are the lines in the code that are ignored by the interpreter
during the execution of the program. Also, Comments enhance the readability of the
code and help the programmers to understand the code very carefully.
Python
# sample comment
# This is Python Comment
name = "geeksforgeeks"
print(name)
Output
geeksforgeeks
Keywords in Python
Keywords in Python are reserved words that can not be used as a variable name,
function name, or any other identifier.
Keywords
as finally not
assert for Or
continue if return
del is try
elif in while
Python Variable
Python Variable is containers that store values. Python is not “statically typed”. An
Example of a Variable in Python is a representational name that serves as a pointer
to an object. Once an object is assigned to a variable, it can be referred to by that
name.
• A Python variable name must start with a letter or the underscore character.
• A Python variable name cannot start with a number.
• A Python variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
• Variable in Python names are case-sensitive (name, Name, and NAME are
three different variables).
• The reserved words(keywords) in Python cannot be used to name the variable
in Python.
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Example
Python
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output
45
1456.8
John
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, data types are classes and variables
are instances (objects) of these classes.
Gautam
Example: This code assigns variable ‘x’ different values of various data types in
Python.
CLICK HERE TO JOIN OUR WHATSAPP GROUP
CLICK HERE TO JOIN OUR WHATSAPP GROUP
Python
x = "Hello World" # string
x = 50 # integer
x = 60.5 # float
x = 3j # complex
x = ["geeks", "for", "geeks"] # list
x = ("geeks", "for", "geeks") # tuple
x = {"name": "Gautam", "age":16} # dict
x = {"geeks", "for", "geeks"} # set
x = True # bool