sdfsd1
sdfsd1
Keywords – Keywords are reserved words in Python that the Python interpreter uses to recognise the
program’s structure. The keyword can’t be used as a variable name, function name, or identifier.
Except for True and False, all keywords in Python are written in lower case.
Example of Keywords –
False, class, finally, is, return, None, continue, for lambda, try, True, def, from, nonlocal, while, and,
del, global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, raise etc.
Identifiers – An identifier is a name given to a variable, function, class, module, or other object. The
identification is made up of a series of digits and underscores. The identification should begin with a
letter or an Underscore and then be followed by a digit. A-Z or a-z, an UnderScore (_), and a numeral
are the characters (0-9). Special characters (#, @, $, percent,!) should not be used in identifiers.
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9)
or an underscore _.
2. An identifier cannot start with a digit
3. Keywords cannot be used as identifiers
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier
5. Identifier can be of any length
6. Python is a case-sensitive language.
Example of Identifier
var1
_var1
_1_var
var_1
Variables
A variable is a memory location where you store a value in a programming language. In Python, a
variable is formed when a value is assigned to it. Declaring a variable in Python does not require any
further commands.
Constants
A constant is a kind of variable that has a fixed value. Constants are like containers that carry
information that cannot be modified later.
Declaring and assigning value to a constant
NAME = “Rajesh Kumar”
AGE = 20
Datatype
In Python, each value has a datatype. Data types are basically classes, and variables are instances
(objects) of these classes, because everything in Python programming is an object.
Python has a number of different data types. The following are some of the important datatypes.
1. Numbers
2. Sequences
3. Sets
4. Maps
a. Number Datatype
Numerical Values are stored in the Number data type. There are four categories of number datatype
–
1. Int – Int datatype is used to store the whole number values. Example : x=500
2. Float – Float datatype is used to store decimal number values. Example : x=50.5
3. Complex – Complex numbers are used to store imaginary values. Imaginary values are denoted with
‘j’ at the end of the number. Example : x=10 + 4j
4. Boolean – Boolean is used to check whether the condition is True or False. Example : x = 15 > 6
type(x)
b. Sequence Datatype
A sequence is a collection of elements that are ordered and indexed by positive integers. It’s made up
of both mutable and immutable data types. In Python, there are three types of sequence data types:
1. String – Unicode character values are represented by strings in Python. Because Python does not
have a character data type, a single character is also treated as a string. Single quotes (‘ ‘) or double
quotes (” “) are used to enclose strings.
2. List – A list is a sequence of any form of value. The term “element” or “item” refers to a group of
values. These elements are indexed in the same way as an array is. List is enclosed in square brackets.
Example : dob = [19,”January”,1995]
1. Tuples – A tuple is an immutable or unchanging collection. It is arranged in a logical manner, and the
values can be accessed by utilizing the index values. A tuple can also have duplicate values. Tuples are
enclosed in (). Example : newtuple = (15,20,20,40,60,70)
c. Sets Datatype
A set is a collection of unordered data and does not have any indexes. In Python, we use curly
brackets to declare a set. Set does not have any duplicate values. To declare a set in python we use
the curly brackets.
Example : newset = {10, 20, 30}
d. Mapping
This is an unordered data type. Mappings include dictionaries.
Dictionaries
In Python, Dictionaries are used generally when we have a huge amount of data. A dictionary is just
like any other collection array. A dictionary is a list of strings or numbers that are not in any particular
sequence and can be changed. The keys are used to access objects in a dictionary. Curly brackets are
used to declare a dictionary. Example : d = {1:’Ajay’,’key’:2}
Operators
Operators are symbolic representations of computation. They are used with operands, which can be
either values or variables. On different data types, the same operators can act differently. When
operators are used on operands, they generate an expression.
Operators are categorized as –
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic Operators
Mathematical operations such as addition, subtraction, multiplication, and division are performed
using arithmetic operators.
Operator Meaning Expression Result
+ Addition 20 + 20 40
– Subtraction 30 – 10 20
* Multiplication 10 * 100 1000
/ Division 30 / 10 20
// Integer Division 25 // 10 2
% Remainder 25 % 10 5
** Raised to power 3 ** 2 9
Assignment Operator
When assigning values to variables, assignment operators are used.
Operator Expression Equivalent to
= x=10 x = 10
+= x += 10 x = x + 10
-= x -= 10 x = x – 10
*= x *= 10 x = x * 10
/= x /= 10 x = x / 10
Comparison Operator
The values are compared using comparison operators or relational operators. Depending on the
criteria, it returns True or False.
Operator Meaning Expression Result
> Greater Than 20 > 10 True
20 < 50 False
< Less Than 20 < 10 False
10 < 40 True
== Equal To 5 == 5 True
5 == 6 False
!= Not Equal to 67 != 45 True
35 != 35 False
Logical Operator
Logical operators are used to combine the two or more then two conditional statements –
Operator Meaning Expression Result
And And Operator True and True True
True and False False
Or Or Operator True or False True
False or False False
Not Not Operator Not False True
Not True False
Type Conversion
Type conversion is the process of converting the value of one data type (integer, text, float, etc.) to
another data type. There are two types of type conversion in Python.
1. Implicit Type Conversion
2. Explicit Type Conversion
Implicit Type Conversion
Python automatically changes one data type to another via implicit type conversion. There is no need
for users to participate in this process.
Example :
x=5
y=2.5
z=x/z
In the above example, x is containing integer value, y is containing float value and in the variable z
will automatically contain float value after execution.
Explicit Type Conversion
Users transform the data type of an object to the required data type using Explicit Type Conversion.
To do explicit type conversion, we employ predefined functions such as int(), float(), str(), and so on.
Because the user casts (changes) the data type of the objects, this form of conversion is also known
as typecasting.
Example : Birth_day = str(Birth_day)
Python Input and Output
Python Output Using print() function
To output data to the standard output device, we use the print() method (screen).
Example :
a = “Hello World!”
print(a)
Python User input
In python, input() function is used to take input from the users.
This function allows the user to take input from the keyboard as a string.
a = input(“Enter name”) #if a is “sagar”, the user entered sagar
Flow of Control
There are three control flow statements in Python – if, for and while.
Decision Making Statement
In programming languages, decision-making statements determine the program’s execution flow.
Python has the following decision-making statements:
1. if statement
2. if..else statements
3. if-elif ladder
If Statement
The if statement is used to test a condition: if the condition is true, a set of statements is executed
(called the if-block).
Flow of Control
Syntax -
If test expression:
statement(s)
If…else statement
The if/else statement is a control flow statement that allows you to run a block of code only if a set of
conditions are satisfied.
Syntax -
if test expression:
Body of if
else:
Body of else
if-elif ladder
Elif stands for “else if.” It enables us to check for several expressions at the same time. If the if
condition is False, the next elif block’s condition is checked, and so on. The body of else is executed if
all of the conditions are False.
if test expression:
Body of if
elif test expression:
Body of elif
else: Body of else
Nested if statements
An if…elif…else sentence can be nestled inside another if…elif…else statement. In
computer programming, this is referred to as nesting.
For Loop
The for statement allows you to specify how many times a statement or compound statement should
be repeated. A for statement’s body is executed one or more times until an optional condition is met.
Syntax -
Data Types
Basic Data Types
1. Integers (int):
o Definition: Whole numbers without a decimal point.
o Example: 5, 100, -42
o Usage: Used for counting, indexing, and mathematical operations.
o Range: Integers can be positive, negative, or zero. Python supports very large integers, limited by
available memory.
2. Floating-Point Numbers (float):
o Definition: Numbers that contain a decimal point.
o Example: 3.14, 0.99, -7.5
o Usage: Used for precise measurements, calculations involving fractions, and scientific calculations.
o Precision: Floating-point numbers are approximate and have a limited precision based on the
number of bits used to store them. They are subject to rounding errors.
3. Strings (str):
o Definition: Sequences of characters enclosed in single (') or double quotes (").
o Example: "Hello", 'World', "123"
o Usage: Used for text processing, displaying messages, and handling user input.
4. Booleans (bool):
o Definition: Represents truth values, either True or False.
o Example: True, False
o Usage: Used for conditional statements and logical operations.
5. Complex Numbers (complex)
Definition: Numbers that have both a real and an imaginary part. The imaginary part is indicated by
the letter j or J.
Format: A complex number is written as real_part + imaginary_part * j.
Example: 3 + 4j, -2 - 5j
Examples
Integer:
number = 10
print(type(number)) # Output: <class 'int'>
2. Floating-Point:
pi = 3.14159
print(type(pi)) # Output: <class 'float'>
3. Complex:
z = 2 + 3j
print(type(z)) # Output: <class 'complex'>
Compound Data Types
1. Lists (list):
o Definition: Ordered, mutable collections of items enclosed in square brackets ([]). Items can be of
different types.
o Example: [1, 2, 3, 4], ['apple', 'banana', 'cherry']
o Usage: Used to store multiple items in a single variable and to perform operations on those items.
2. Tuples (tuple):
o Definition: Ordered, immutable collections of items enclosed in parentheses (()). Items can be of
different types.
o Example: (1, 2, 3, 4), ('red', 'green', 'blue')
o Usage: Used to store multiple items in a fixed order where the data shouldn’t change.
3. Dictionaries (dict):
o Definition: Unordered collections of key-value pairs enclosed in curly braces ({}). Keys are unique, and
values can be of any type.
o Example: {'name': 'Alice', 'age': 25, 'city': 'New York'}
o Usage: Used to store and retrieve data efficiently using keys.
4. Sets (set):
o Definition: Unordered collections of unique items enclosed in curly braces ({}).
o Example: {1, 2, 3}, {'apple', 'banana'}
o Usage: Used to store unique items and perform mathematical set operations like union, intersection,
and difference.
Special Data Types
1. NoneType (None):
o Definition: Represents the absence of a value or a null value.
o Example: None
o Usage: Used to signify that a variable has no value or to represent missing or undefined data.
In Python, None is a special constant that represents the absence of a value or a null value. It’s a
unique data type, NoneType, and is used in various scenarios to indicate that something is undefined
or missing.
Mapping(dictionary)
In Python, a dictionary is a built-in data structure that allows you to store and manage data in key-
value pairs. It’s a type of mapping where each key is associated with a value, making it easy to look
up data based on a unique identifier.
Dictionaries (dict):
o Definition: Collections of key-value pairs where the data can be modified after creation.
o Operations: You can add, update, or remove key-value pairs.
o Example:
student = {"name": "Alice", "age": 18}
student["age"] = 19 # Updates the value
student["grade"] = "A" # Adds a new key-value pair
3. Sets (set):
o Definition: Unordered collections of unique elements that can be modified.
o Operations: You can add or remove elements from a set.
o Example:
numbers = {1, 2, 3}
numbers.add(4) # Adds a new element
numbers.remove(2) # Removes an element
Immutable Data Types
Immutable data types are those whose values cannot be changed after they are created. Any
operation that seems to modify the object actually creates a new object.
Tuples (tuple):
o Definition: Ordered collections of elements, similar to lists but immutable.
o Operations: Any modification creates a new tuple object.
o Example:
coordinates = (10, 20)
new_coordinates = coordinates + (30,) # Creates a new tuple
Expressions and Statements
Expression: An expression is a combination of values, variables, operators, and functions that
evaluates to a single value. Expressions can be as simple as 5 + 3 or as complex as ((2 * 3) + (4 / 2)).
Expressions always return a result.
o Example:
result = 5 * (2 + 3) # 5 * 5 = 25, so the expression evaluates to 25
Statement: A statement is a complete unit of execution that performs an action. Statements include
assignments, loops, conditionals, and function calls. Statements do not return a value but execute an
operation.
o Example:
x = 10 # This is an assignment statement
print(x) # This is a print statement
Precedence of Operators
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated before operators with lower precedence. For
instance, multiplication (*) has higher precedence than addition (+), so in the expression 2 + 3 * 4, the
multiplication is performed first, giving 2 + 12, which results in 14.
Example:
result = 10 + 3 * 2 # The multiplication is done first, so 10 + (3 * 2) = 16
Evaluation of an Expression
When an expression is evaluated, Python performs operations based on operator precedence and
associativity rules. Parentheses can be used to override default precedence and force specific order
of operations.
Example:
value = (8 + 2) * 5 # Parentheses ensure that 8 + 2 is evaluated first, so (10 * 5) = 50
Type Conversion
Type conversion allows you to change the data type of a value. This can be done implicitly by Python
or explicitly by the programmer.
Explicit Conversion: Done using functions like int(), float(), and str() to convert between types.
o Example:
num_str = "123"
num_int = int(num_str) # Converts the string "123" to the integer 123
Implicit Conversion: Python automatically converts types when necessary, such as converting
integers to floats during arithmetic operations involving both types.
o Example:
result = 10 + 2.5 # The integer 10 is implicitly converted to a float, so the result is 12.5
Understanding these concepts helps you write more effective and error-free code by ensuring
expressions are evaluated correctly and data types are managed properly.
Flow of Control
The flow of control refers to the order in which the individual statements, instructions, or function
calls are executed or evaluated in a programming language. In Python, this flow is managed using
different constructs like sequences, conditions, and loops.
Use of Indentation
Python uses indentation (whitespace) to define blocks of code. Unlike some other programming
languages that use braces or keywords, Python’s indentation is crucial for defining the structure and
flow of the program. Proper indentation ensures that code blocks (such as those following
conditional statements or loops) are correctly associated with their control statements.
Example:
if True:
print("This is inside the if block") # Indented block
print("This is outside the if block") # Not indented
Iterative Statement:
Iterative statements allow you to execute a block of code repeatedly based on certain conditions. In
Python, the primary iterative statements are for loops and while loops. Here's how they work:
for Loop
The for loop iterates over a sequence (like a list, tuple, or string) or a range of numbers. It’s useful
when you know in advance how many times you want to repeat a block of code.
Example:
for i in range(5):
print(i) # Prints numbers from 0 to 4
range() Function
The range() function generates a sequence of numbers and is commonly used with for loops. It can
take up to three arguments: start, stop, and step.
Example:
for i in range(2, 10, 2):
print(i) # Prints 2, 4, 6, 8
while Loop
The while loop executes as long as its condition remains true. It’s useful when you don’t know
beforehand how many times you’ll need to repeat the code.
Example:
count = 0
while count < 5:
print(count)
count += 1 # Increment count
break and continue Statements
break: Exits the loop immediately, regardless of the loop condition.
o Example:
for i in range(10):
if i == 5:
break # Exits the loop when i is 5
print(i)
continue: Skips the current iteration and continues with the next iteration of the loop.
o Example:
for i in range(10):
if i % 2 == 0:
continue # Skips even numbers
print(i) # Prints only odd numbers
Nested Loops
Nested loops involve placing one loop inside another. They are useful for working with multi-
dimensional data or generating patterns.
Example:
for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print() # New line after inner loop
Strings
Strings are sequences of characters used to represent text in Python. They are one of the most
commonly used data types and are essential for handling textual data. Here’s a brief overview of
strings and some of their key operations.
Introduction to Strings
A string is a collection of characters enclosed in single quotes ('), double quotes ("), or triple quotes
(''' or """). Strings are immutable, meaning once created, their content cannot be changed.
Example:
message = "Hello, World!"
String Operations
1. Concatenation: Concatenation combines two or more strings into one. This is done using the +
operator.
o Example:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
2. Repetition: Repetition allows you to repeat a string a certain number of times using the * operator.
o Example:
echo = "Hello! " * 3
print(echo) # Output: Hello! Hello! Hello!
4. Slicing: Slicing extracts a part of the string. You use indexing to specify the start and end positions.
The syntax is string[start:end].
o Example:
phrase = "Hello, World!"
slice1 = phrase[0:5] # Extracts 'Hello'
slice2 = phrase[7:] # Extracts 'World!'
print(slice1) # Output: Hello
print(slice2) # Output: World!
o vowels is a string containing all vowel characters.
o For each character in text, check if it is in the vowels string.
o Increment count if a vowel is found.
Functions in Python
A function can be defined as the organized block of reusable code which can be called whenever
required. In other words, Python allows us to divide a large program into the basic building blocks
known as function.
Python provide us various inbuilt functions like range() or print(). Although, the user can able to
create functions which can be called user-defined functions.
Creating Function
In python, a function can be created by using def keyword.
Syntax:
def my_function():
Statements
return statement
The function block is started with the colon (:) and all the same level block statements remain at the
same indentation.
Example:
def sample(): #function definition
print ("Hello world")
Modules in Python
In python module can be defined as a python program file which contains a python code including
python functions, class, or variables. In other words, we can say that our python code file saved with
the extension (.py) is treated as the module.
Modules in Python provides us the flexibility to organize the code in a logical way. To use the
functionality of one module into another, we must have to import the specific module.
Creating Module
Example: demo.py
# Python Module example
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
In the above example we have defined 4 functions sum(), sub(), mul() and div() inside a module
named demo.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python provides two types of
statements as defined below.
1. import statement
2. from-import statement
Python Modules
Python modules are a great way to organize and reuse code across different programs. Think of a
module as a file containing Python code that defines functions, classes, and variables you can use in
your own programs. By importing these modules, you can make use of their functionality without
having to rewrite code.
“Modules” in Python are files that contain Python code. It can contain functions, classes, and
variables, and you can use them in your scripts. It help to reuse code and keep the project organized.
Tuple
A tuple in Python is a collection of elements that is ordered and immutable. Tuples are created using
parentheses () and can also hold elements of different data types.
Example:
my_tuple = (1, 'banana', False)
print(my_tuple)
Advantages:
Immutable – Elements cannot be changed after creation.
Faster access time compared to lists for read-only operations.
Disadvantages:
Cannot be modified once created.
Use Cases and Applications:
Used for fixed collections of elements where immutability is desired.
Returning multiple values from a function.
Set
A set in Python is a collection of unique elements that is unordered and mutable. Sets are created
using curly braces {} or the set() function.
Example:
my_set = {1, 2, 3}
print(my_set)
Advantages:
Contains unique elements only, eliminating duplicates.
Fast membership testing and operations like intersection and union.
Disadvantages:
Not ordered – Elements are not stored in a specific order.
Use Cases and Applications:
Removing duplicates from a list.
Checking for membership or common elements between sets.
Dictionary
You create dictionaries in Python using curly braces {} and colons : to define key-value pairs.
They let you store unordered and mutable collections of data.
Example:
my_dict = {'key1': 'value1', 'key2': 2}
print(my_dict)
Advantages:
Fast lookups based on keys.
Key-value pair structure allows for easy data retrieval.
Disadvantages:
Not ordered – No guarantee on the order of key-value pairs.
Use Cases and Applications:
Storing data with a key for easy retrieval.
Mapping unique identifiers to values for quick access.
Practical Implementation
Lists in Python
Lists are versatile data structures in Python that can hold heterogeneous elements.
Practical Implementation Example:
Let’s create a list of fruits and print each fruit:
numbers = [1, 2, 3]
for num in numbers[:]:
numbers.append(num * 2)
Tuples in Python
Tuples are immutable sequences in Python, typically used to represent fixed collections of items.
Practical Implementation Example:
Creating a tuple of coordinates:
point = (3, 4)
distances = {(0, 0): 0, (1, 1): 1}
distance_to_origin = distances.get(point, -1)
Common Pitfalls and Solutions:
Attempting to modify a tuple will result in an error. If mutability is required, consider using a list.
Sets in Python
Use sets in Python when you need to store unique elements, test for membership, or eliminate
duplicates without caring about order.
Practical Implementation Example:
Creating a set of unique letters in a word:
word = 'hello'
unique_letters = set(word)
print(unique_letters)
Best Practices and Optimization Tips:
Use set operations like intersection, union, and difference for efficient manipulation of data:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection = set1 & set2
Common Pitfalls and Solutions:
Accidentally mutating a set during iteration can lead to unexpected behavior. To prevent this,
operate on a copy of the set.
Dictionaries in Python
Dictionaries are key-value pairs that allow for fast lookups and mappings between items.
Practical Implementation Example:
Creating a dictionary of phone contacts:
Array
An array is defined as a container that stores the collection of items at contiguous memory locations.
The array is an idea of storing multiple items of the same type together and it makes it easier to
calculate the position of each element. It is used to store multiple values in a single variable.
Creating an Array
For creating an array in Python, we need to import the array module.
After importing, the array module we just have to use the array function which is used to create the
arrays in Python.
Syntax
print(myArr)
Explanation
Adding Element to Array
As we all know, arrays are mutable in nature. So we can add an element to the existing array.
We can use 2 different methods to add the elements to the existing array. These methods are:
.append(): This is used to add a single element to the existing array. By using the append
method the element gets added at the end of the existing array.
.extend(): This is used to add an array to the existing array. By using the extend method the
array that we have added to the extend function gets merged at the end of the existing array.
And, finally, we got the updated array where we have the combination of the original and the
new array.
Let's checkout with the help of an example of how these functions are used to add elements at the
end of the array.
Syntax
indOfElement = 2
accessedElement = myArr[indOfElement]