Chapter-1
Chapter-1
Features of Python:
Interpretation: Unlike C and C++, there are no distinct compilation and execution steps. Launch
the application straight from the source code. In order to run the source code, Python internally
transforms it into bytecodes, which are then translated into the native language of the machine.
There is no need to be concerned with loading and linking libraries, etc.
Independent of Platform: Python applications can be created and run on a variety of operating
systems. Linux, Windows, Macintosh, Solaris, and many other operating systems can all utilise
Python.
Redistributable, Open Source, and Free
Advanced Language: Low-level aspects like controlling the program's memory usage are not
necessary while using Python.
Easy: Easy to learn and more similar to the English language. More focus on the problem-solving
approach rather than the syntax.
Embedded: Python can be used in C/C++ programs to provide users with scripting capabilities.
Strong: Outstanding handling characteristics. Built-in memory management strategies
Comprehensive Library Assistance: The scope of the Python Standard Library is enormous.
Regular expressions, documentation creation, unit testing, threading, databases, web browsers,
CGI, email, XML, HTML, WAV files, cryptography, graphical user interfaces, and many more
tasks may be accomplished using Python, which is known for its "batteries included" concept.
In addition to the standard library, there are additional excellent libraries, such the Python
Imaging Library, which is a remarkably straightforward image processing toolkit.
Python vs JAVA
Python Java
Brief: Say a lot in a few words. Verbose: More words are included.
Topic-2: Variables:
Python variables are value-storing containers.
"Statically typed" is not how Python works.
It is not necessary to declare variables or their types before using them.
As soon as we give a variable a value, it is created.
A Python variable is a name assigned to a location in memory.
It is a program's fundamental storage unit.
A representational name that acts as a pointer to an object is an example of a variable in Python.
An object can be called by that name once it has been assigned to a variable.
Python variable rules:
o A letter or the underscore character must appear at the beginning of a Python variable name.
o No number can appear at the beginning of the name of a Python variable.
o Alpha-numeric characters and underscores (A-z, 0-9, and _) are the only characters allowed in a
Python variable name.
o Python variable names are case-sensitive; for example, name, Name, and NAME are all distinct
variables.
o Python variables cannot be named using the reserved terms (keywords).
a = b = c = 10
a, b, c = 1, 20.2, "GeeksforGeeks"
a = 20
b = 30
print(a+b) #supported
a = "Parul"
b = "University"
print(a+b) #supported
a = 20
b = "Parul"
print(a+b) #unsupported
Topic-3: Datatypes:
Note: Python will give an error if True and False are not capitalised "T" and "F."
Python statements that offer a control flow option based on a condition are known as conditional
statements. It indicates that the Python program's control flow will be determined by the condition's
result.
If Conditional Statement: The if statement is used if the condition is true and the block's simple code is
to be executed. When the aforementioned condition is met, the block's code executes; otherwise, it does
not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Example:
num = 10
if num > 5:
print("The number is greater than 5.")
Output:
The number is greater than 5.
If else Conditional Statement: When the if condition is false, the extra block of code is combined into
an else statement and executed in a conditional if statement.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example:
num = 3
if num % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Output:
The number is odd.
Nested if..else Conditional Statement: An if-else expression inside another if statement is called nested
if..else. Or, to put it simply, a nested if statement is a statement that has an outer if statement and an inner
if-else statement. One if/else if statement can be used inside another if/else if statement.
Example:
num = 15
if num > 10:
if num % 5 == 0:
print("The number is greater than 10 and divisible by 5.")
else:
print("The number is greater than 10 but not divisible by 5.")
else:
print("The number is 10 or less.")
Output:
The number is greater than 10 and divisible by 5.
If-elif-else Conditional Statement: The top-down approach is used to execute the if statements. The
statement linked to that if is performed and the remainder of the ladder is omitted as soon as one of the
conditions governing the if is true. The last "else" phrase will be run if none of the conditions are met.
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
Output:
Grade: B
Ternary Expression Conditional Statement: After determining whether a condition is true or false, the
Python ternary expression returns the appropriate value based on the outcome. When we need to assign a
value to a variable based on a straightforward condition and wish to write more compact code, the ternary
expression comes in handy. It just requires one line of code.
Syntax:
[on_true] if [expression] else [on_false]
expression: conditional_expression | lambda_expr
Example:
age = 18
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)
Output:
Status: Adult
Topic-5: Loops:
While loop:
A while loop in Python is used to repeatedly run a block of statements until a specified condition is met.
The line that appears right after the program's loop is run when the condition is changed to false.
Syntax:
while expression:
statement(s)
Example:
count = 0
while count < 5:
print("Count is:", count)
count += 1
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Else statement with While Loop: The else clause is only used when your while condition is false. It will
not be run if you exit the loop or raise an exception.
Syntax:
while condition:
# execute these statements
else:
# execute these statements
Example:
count = 0
while count < 3:
print("Count is:", count)
count += 1
else:
print("Condition is false, exiting loop.")
Output:
Count is: 0
Count is: 1
Count is: 2
Condition is false, exiting loop.
For Loop: For sequential traversal, for loops are employed. For instance, navigating through a list, text,
array, etc. The "for in" loop in Python is comparable to the foreach loop in other programming languages.
Syntax:
for iterator_var in sequence:
statements(s)
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("Fruit:", fruit)
Output:
Fruit: apple
Fruit: banana
Fruit: cherry
else Statement with for Loop: Like with a while loop, we can likewise combine an else statement with
a for loop. However, since the for loop lacks a condition that would cause the execution to end, the
otherwise block will be run as soon as the for loop is finished.
Example:
numbers = [1, 2, 3]
for num in numbers:
print("Number:", num)
else:
print("All numbers processed.")
Output:
Number: 1
Number: 2
Number: 3
All numbers processed.
Nested Loop: The Python programming language enables the usage of nested loops, which are loops
inside loops.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Example:
for i in range(1, 4): # Outer loop
for j in range(1, 3): # Inner loop
print(f"Outer: {i}, Inner: {j}")
Output:
Outer: 1, Inner: 1
Outer: 1, Inner: 2
Outer: 2, Inner: 1
Outer: 2, Inner: 2
Outer: 3, Inner: 1
Outer: 3, Inner: 2
while expression:
while expression:
statement(s)
statement(s)
Loop Control Statements: Loop control statements alter the order in which things are executed. All
automatic objects produced within a scope are deleted when execution exits it. The following control
statements are supported by Python.
1. Continue Statement: Python's continue statement puts the loop's control back at the start.
Example:
for i in range(5):
if i == 2:
continue
print("Number:", i)
Output:
Number: 0
Number: 1
Number: 3
Number: 4
Example:
for i in range(5):
if i == 3:
break
print("Number:", i)
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
3. Pass Statement: To create empty loops in Python, we utilise the pass statement. Empty control
statements, functions, and classes can also be passed.
Example:
for i in range(5):
if i == 2:
pass # Placeholder, does nothing
print("Number:", i)
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Part-2: Lists,Sets,Tuples,Dictionaries:
P A R U L U N I V E R S I T Y
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
-16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example:
s = "ParulUniversity"
# Accesses first character: 'P'
print(s[0])
In Python, characters from the back of the string can be accessed using negative address references; for
example, -1 denotes the last character, -2 the second-to-last, and so forth.
Example:
s = "ParulUniversity"
String slicing:
By providing the start and end indexes, slicing allows you to retrieve a piece of a string. String[start:end]
is the syntax for slicing, where start is the starting index and end is the stopping index (excluded).
Example:
s = "ParulUniversity"
# Reverse a string
print(s[::-1])
Immutable nature:
Python strings cannot be changed. This implies that once they are produced, they cannot be altered. If
string manipulation is required, we can construct new strings based on the original by using techniques
like formatting, slicing, and concatenation.
Example:
s = "ParulUniversity"
Delete string:
Since strings are immutable in Python, it is not feasible to remove individual characters from a string. On
the other hand, the del keyword allows us to remove a whole string variable.
Example:
s = "PU"
Update string:
Since strings are immutable, updating a portion of them requires creating a new string.
Example:
s = "ParulUniversity"
Example:
s = " ParulUniversity "
print(len(s))
2. upper() and lower(): The upper() methods change all characters to capital letters. All characters are
changed to lowercase using the lower() technique.
Example:
s = "Hello"
print(s.upper()) # output: HELLO
print(s.lower()) # output: hello
3.strip() and replace(): strip() eliminates the string's leading and trailing whitespace, while replace(old,
new) swaps out every instance of a given substring for another.
Example:
s = " Pu "
# Removes spaces from both ends
print(s.strip())
s = "Python is good"
# Replaces 'good' with 'awesome'
print(s.replace("good", "awesome"))
Example:
s1 = "Parul"
s2 = "University"
s3 = s1 + " " + s2
print(s3)
Output:
Parul University
s = "Parul "
print(s * 3)
Output:
Parul Parul Parul
String formatting:
There are multiple ways to add variables inside strings in Python.
1. f-strings: f-strings are the most popular and straightforward method for formatting strings.
Example:
name = "Aarti"
age = 21
print(f"Name: {name}, Age: {age}")
Output:
Name: Aarti, Age: 21
Example:
s = "My name is {} and I am {} years old.".format("Aarti", 21)
print(s)
Output:
My name is Aarti and I am 21 years old.
Output:
True
False
Topic-2: Lists:
An ordered collection of items can be stored in a list, a built-in data structure in Python.
Lists can have their contents altered after they have been constructed because they are mutable.
Numerous data kinds, such as texts, floats, integers, and even other lists, can be stored in them.
In Python, we can use the list() constructor or square brackets [] to create a list.
By providing the list() method with an iterable (such as a string, tuple, or another list), we can
also generate a list.
The multiplication operator can be used to generate a list with repeated members.
Example:
# List of integers
a = [1, 2, 3, 4, 5]
# List of strings
b = ['apple', 'banana', 'mango']
# From a tuple
d = list((1, 2, 3, 'apple', 5.5))
print(a)
print(b)
print(c)
print(d)
Adding elements:
The following techniques allow us to add items to a list:
append(): Appends an element to the list's end.
extend(): Appends a number of items to the list's end.
insert(): Inserts a component at a given location.
Example:
# Initialize an empty list
a = []
# Inserting 3 at index 0
a.insert(0, 3)
print("After insert(0, 3):", a)
Update elements:
By utilising its index to access an element, we can modify its value.
Example:
a = [1, 2, 3, 4, 5]
# Change the second element
a[1] = 15
print(a)
Remove elements:
We can use the following to eliminate items from a list:
remove(): Eliminates an element's initial occurrence.
pop(): Eliminates the element at a given index, or the final element in the absence of an index.
An element at a certain index is deleted using the del command.
Example:
a = [1, 2, 3, 4, 5]
# Removes the first occurrence of 3
a.remove(3)
print("After remove(3):", a)
# Removes the element at index 1 (2)
popped_val = a.pop(1)
print("Popped element:", popped_val)
print("After pop(1):", a)
# Deletes the first element (10)
del a[0]
print("After del a[0]:", a)
Output:
After remove(3): [1, 2, 4, 5]
Popped element: 2
After pop(1): [1, 4, 5]
After del a[0]: [4, 5]
Iteration:
Using a for loop or other iteration techniques, we can quickly iterate the lists.
When we want to perform an operation on each item or retrieve particular items based on
predetermined criteria, iterating across lists is helpful.
Example:
a = ['apple', 'banana', 'mango']
# Iterating over the list
for item in a:
print(item)
Example:
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
# Access element at row 2, column 3
print(matrix[1][2])
Topic-3: Sets:
In Python programming, an unordered collection data type with no duplicate elements that is
iterable is called a set.
Individual items within a set must be immutable and cannot be altered directly, even if sets are
changeable, meaning you can add or delete elements after they are created.
{ } is used to represent sets, which are values enclosed in curly braces.
Using a set instead of a list offers the main benefit of having a highly optimised way to determine
whether a particular piece is part of the set.
This is predicated on a hash table, a type of data structure.
We cannot use indexes to access items in sets as we do in lists because sets are not ordered.
Example:
# typecasting list to set
myset = set(["A", "B", "C"])
print(myset)
# Adding element to the set
myset.add("D")
print(myset)
Output:
{'C', 'B', 'A'}
{'D', 'C', 'B', 'A'}
Frozen sets:
In Python, frozen sets are immutable objects that only allow operators and methods that yield a
result without changing the frozen set or sets they are applied to.
Python's frozenset() method can be used for this.
Although a set's components can be changed at any moment, the frozen set's components don't
change once it is created.
It returns an empty frozenset if no parameters are supplied.
Example:
# Same as {"A", "B","C"}
normal_set = set(["A", "B","C"])
print("Normal Set")
print(normal_set)
# A frozen set
frozen_set = frozenset(["E", "F", "G"])
print("\nFrozen Set")
print(frozen_set)
Topic-4: Tuples:
Example:
t = (5, 50, 500)
print("Value in t[0] = ", t[0])
print("Value in t[1] = ", t[1])
print("Value in t[2] = ", t[2])
Here, we will use the negative index inside [], whereas in the previous approaches, we used the positive
index to access the value in Python.
Example:
t = (5, 50, 500)
print("Value in t[-1] = ", t[-1])
print("Value in t[-2] = ", t[-2])
print("Value in t[-3] = ", t[-3])
Topic-5: Dictionaries:
A data structure that holds values in key: value pairs is called a Python dictionary.
While keys in a dictionary must be immutable and cannot be duplicated, values can be any data
type.
For instance, the information is kept in dictionaries as key-value pairs, which facilitates value
discovery.
Syntax:
dict_var = {key1 : value1, key2 : value2, …..}
Note: Dictionary keys are case-sensitive; various key cases will be handled differently even if they have
the same name.
Example:
d1 = {}
print("Empty Dictionary: ")
print(d1)
Adding elements:
There are several methods for adding items.
By defining the value and the key together, such as Dict[Key] = "Value," one value at a time can
be added to a dictionary.
Example: Include Items of Various DataTypes in a Python Dictionary
Layering dictionaries inside the main dictionary, adding components with different data types,
and changing the value of a key.
The program demonstrates how to work with dictionaries in Python.
Example:
d = {}
print("Empty Dictionary: ")
print(d)
d[0] = 'Parul'
d[2] = 'University'
d[3] = 1
print("\nDictionary after adding 3 elements: ")
print(d)
d['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(d)
d[2] = 'Welcome'
print("\nUpdated key value: ")
print(d)
d[5] = {'Nested': {'1': 'Life', '2': 'Journey'}}
print("\nAdding a Nested Key: ")
print(d)
Output:
Empty Dictionary:
{}
Note: If the key-value pair already exists, the value is changed when a value is added; if not, a new key
with the value is added to the dictionary.
Accessing elements:
Use a dictionary's key name to access its contents. Inside square brackets, the key can be utilised.
Example:
d = {1: 'University', 'name': ' Parul ', 3: ‘PU'}
print("Accessing a element using key:")
print(d['name'])
print("Accessing a element using key:")
print(d[1])
Accessing an element from a dictionary can also be facilitated via the get() method. This function returns
the value after accepting the key as an input.
Example:
d = {1: 'University', 'name': ' Parul ', 3: ‘PU'}
print("Accessing a element using get:")
print(d.get(3))
Example:
d = {'Dict1': {1: 'University'},
'Dict2': {'Name': 'Parul'}}
print(d['Dict1'])
print(d['Dict1'][1])
print(d['Dict2']['Name'])
Deleting elements:
The del keyword, as shown below, can be used to remove dictionary elements.
Example:
d = {1: 'Parul', 'name': 'University'}
print("Dictionary =")
print(d)
del(d[1])
print("Data after deletion Dictionary=")
print(d)
Output:
Dictionary =
{1: 'Parul', 'name': 'University'}
Data after deletion Dictionary=
{'name': 'University'}