0% found this document useful (0 votes)
21 views52 pages

Python

The document provides an introduction to Python programming, focusing on problem-solving techniques, algorithms, flowcharts, and pseudocode. It outlines the steps involved in problem-solving, including identifying the problem, understanding it, and developing solutions through structured methods like algorithms and flowcharts. Additionally, it discusses the importance of pseudocode in bridging the gap between algorithm design and actual programming implementation.

Uploaded by

dharanultra0409
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)
21 views52 pages

Python

The document provides an introduction to Python programming, focusing on problem-solving techniques, algorithms, flowcharts, and pseudocode. It outlines the steps involved in problem-solving, including identifying the problem, understanding it, and developing solutions through structured methods like algorithms and flowcharts. Additionally, it discusses the importance of pseudocode in bridging the gap between algorithm design and actual programming implementation.

Uploaded by

dharanultra0409
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/ 52

Unit I

Introduction to Python: Problem Solving, Problem Analysis Chart, DevelopingAn Algorithm,


Flowchart and Pseudocode, Interactive and Script Mode, Indentation, Comments, Error messages,
Variables, Reserved Words, Data Types, Arithmetic operators and expressions, Built-in Functions,
Importing from Packages.
Introduction:
 Problem Solving in the process Of identifying a problem, developing Possible Solution paths, and
taking the appropriate Course of action.
 Problem Solving is a process, most strategies provide steps that help you identify the problem and
choose the best solution.
What is Problem?
 A problem is a state of difficulty that need to be resolved.
 When a problem exists then that means there is some uncertainty in the solution While solving a
problem there is a desire to attain some specific goal.
 People make decisions in everyday life. This decision is considered as a solution least important.
Here are some examples of various problems faced in our everyday Life-
1. Which college should I choose for admission?
2. Will I get proper transport to go to my workplace?
Ideal Problem Solving:
Problem solving strategies:
There are two basic types of problem Solving strategies:
1. Algorithmic
2. Heuristic
Algorithmic:
It is a traditional step-by-step guides to Solving problems. It is mainly use for there is a single path to the
correct solution.
Heuristic:
This method are generally wed to identify possible Solutions. A popular heuristic method are IDEAL.
Steps of problem solving:
1. Identify the problem: Identifying the problem is the first step in solving the problem. Problem
identification is very essential before solving any problem
2. Understand the problem: Before solving any problem it is important to understand it. There are
three aspects based on which the problem can be understood.
 Knowledgebase: While solving the problem the knowledgebase can be related to a person or a
machine. If the problem is to be solved for the person then it necessary to know what the person
knows. If the problem is to be solved for the machine then its instruction set must be known.
Along with this the problem solver can make use of his/her own instruction set.
 Subject: Before solving the problem the subject on which the problem is based must be known.
For instance: To solve the problem involving Laplace, it is necessary to know about the Laplace
transform.
 Communication: For understanding the problem, the developer must communicate with the
client
3. Identify the alternative ways to solve the problem: The alternative way to solve the problem must be
known to the developer. These alternatives can be decided by communicating with the customer
4. Select the best way to solve the problem from list of alternative solutions: For selecting the best way
to solve the problem, the merits and demerits of each problem must be analysed. The criteria to evaluate
each problem must be predefined
5. List the instructions using the selected solution: Based on the knowledgebase (created/used in step 2)
the step by step instructions are listed out. Each and every instruction must be understood by the person or
the machine involved in the problem solving process.
6. Evaluate the solution: When the solution is evaluated then – i) Check whether the solution is correct or
not ii) Check whether it satisfies the requirements of the customer or not.
Problem solving with computers:
 Solution: It is the instruction that must be followed to produce the best results. The result may be :
More efficient, faster, or more understandable.
 Results: It is an outcome or the completed computer-assisted answer. It can be in any form such as
printout, updated files, output to monitor, speakers, and so on .
 Programs: Computer programs are set of instructions executed to obtain solution to certain problem.
These programs are written in some specific programming language.
 Basically computers can deal with the problems having algorithmic solutions. That means a problem
for which an algorithm can be created such problem can be solved using computer.
 The field of computer that deals with solving the heuristic problems is called artificial intelligence.
 Artificial intelligence is based on knowledge base and the result in it are displayed in a language that
a human speaks. Still lot of research and development is required in this field.
 Hence human can deal with the problems that are based on heuristic solutions and computers can
deal with the problems that are based on algorithmic solutions.
Problem Analysis Charts:
 A Problem Analysis Chart (PAC) is a structured tool used to break down a problem into key
components
 It helps to systematically understand the problem, identify necessary data, and develop a structured
approach to solve it
 In the context of algorithms and flowcharts, PACs serve as the initial step in problem-solving by
organising information that will be used to visualise and implement the solution.
PACs for Different Geometries:
 The PAC breaks the problem into smaller parts
 It helps us to bring a logical sequence to our thought process and help us arrive at better solutions
Developing an algorithm
Definition of Algorithm:
An algorithm is a finite set of instructions for performing particular task. The instructions are nothing but the
statements in simple Language.
Example: Let us take a very simple example of an algorithm which adds the two numbers store the result in
a third variable.
Step 1: Start.
Step 2: Read the first number in variable ‘a’
Step 3: Read the second number in variable ‘b’
Step 4: Perform the addition of both the numbers and store the result in variablec
Step 5: Print the value of ‘c’ as a result of addition.
Step 6: Stop.
Characteristics of Algorithm
1. Each algorithm is supplied with zero or more inputs.
2. Each algorithm must produce at least one output
3. Each algorithm should have definiteness i.e. each instruction must be clear unambiguous.
4. Each algorithm should have finiteness i.e. if we trace out the instructions of algorithm, then for all
cases the algorithm will terminate after finite number steps.
Each algorithm should have effectiveness i.e. every instruction must be sufficiently basic that it can in
principal be carried out by a person using only pencil and paper. Moreover each instruction of an algorithm
must also be feasible.
Example 1:Find the area of a circle of radius r.
Solution:
Inputs to the algorithm:
Radius r of the Circle.
Expected output:Area of the Circle
Algorithm:
Step 1: Start
Step 2: Read input the Radius r of the Circle
Step 3: Area<-PI*r*r // calculation of area
Step 4: Print Area
Step 5: Stop
Example 2: An algorithm to calculate even numbers between 0 and 99.
Solution:
Step 1: Start
Step 2: Read n or Initialize n = 99
Step 3: Initialize I = 2
Step 4: If I <= n then goto step 5 else goto step 7
Step 5: If i% * 2 = 0 then goto step 5.1,5.2 else goto step 6
Step 5.1: Print i
Step 5.2: I = I + 1 goto step 4
Step 6: I = I + 1 goto step4
Step 7: Stop
Example 3:Outline the algorithm for displaying the first n odd numbers
Solution:
Step 1: start
Step 2: Read n
Step 3: Initialize i=1
Step 4: If i<=n then goto step 5 else goto step 9
Step 5: if i%2!=0 then goto step 6 else goto step 7
Step 6: Print i
I=i+1
Step 7: i=i+1
Step 8: goto step 4
Step 9: stop
Example 4: Write an algorithm to find the minimum number in a given list of elements
Solution:
Step 1: start
Step 2: Read n numbers and store them in a list.
Step 3: set count =1
Step 4: min list[count]
Step 5: while(not end of the list) then goto step 6 otherwise goto step 8
Step 6: if(list[count]<min)
Min = list[count]
Count=count+1
Step 7: goto step 5
Step 8: if the complete list is scanned then display the value present in the min as the minimum number in
the list
What are Flowcharts?
Flowcharts are the visual representations of an algorithm or a process. Flowcharts use symbols/shapes like
arrows, rectangles, and diamonds to properly explain the sequence of steps involved in the algorithm or
process. Flowcharts have their use cases in various fields such as software development, business process
modeling, and engineering.
Why use Flowcharts?
Flowcharts are used due to the numerous amount of benefits they provide. Below are some of the
important reasons to use flowcharts:
 They provide clarity and simplification to the complex processes and algorithms, which in turn
helps other people to understand them easily.
 Flowcharts provide a universal visual language that can be understood by anyone across different
teams and helps reduce miscommunications.
 They are an optimal solution for documenting standard operating procedures, workflows, or
business processes. This makes it easier to train new employees.
 Flowcharts help in increasing the visualization of the problem being solved which enables more
informed and data-driven choices.
Types of Flowcharts
There are many types of flowcharts , each is designed to represent different kinds of processes and
information. Some common types of flowcharts are:
 Process Flowchart: It represents the sequence of steps in a process. They are frequently used in
business process modeling, manufacturing, and project management
 Swimlane Flowchart: It organizes the process into different lanes, each representing a different
person or department and is used for illustrating how different teams or departments collaborate
within a process
 Workflow Diagram: It represents how tasks, documents, or information move through a system
and is commonly used in office processes or software development
 Data Flow Diagram (DFD) : It focuses on detailing the inputs, processes, and outputs. Used
in system design and analysis to model the flow of data within a system
 Decision Flowchart: It focuses on mapping out decision points within a process and the possible
outcomes of each decision. It is used in decision-making scenarios
Symbols used in Flowchart Designs
1. Terminal/Terminator
The oval symbol indicates Start, Stop and Halt in a program's logic flow. A pause/halt is generally used in
a program logic under some error conditions. Terminal is the first and last symbols in the flowchart.

2. Input/Output
A parallelogram denotes any function of input/output type. Program instructions that take input from input
devices and display output on output devices are indicated with parallelogram in a flowchart.

3. Action/Process
A box represents arithmetic instructions, specific action or operation that occurs as a part of the process.
All arithmetic processes such as adding, subtracting, multiplication and division are indicated by
action/process symbol.

4. Decision
Diamond symbol represents a decision point. Decision based operations such as yes/no question or
true/false are indicated by diamond in flowchart.

5. On-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors
to avoid any confusions. connectors are used to indicate a jump from one part of the flowchart to another
without drawing long or complicated lines. On-Page Connector is represented by a small circle
6. Off-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors
to avoid any confusions. connectors are used to indicate a jump from one part of the flowchart to another
without drawing long or complicated lines. Off-Page Connector is represented by a pentagon.

7. Flow lines
Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the direction
of flow of control and relationship among different symbols of flowchart.

Rules For Creating a Flowchart


A flowchart is a graphical representation of an algorithm. It should follow some rules while creating a
flowchart
 Rule 1: Flowchart opening statement must be ‘start’ keyword.
 Rule 2: Flowchart ending statement must be ‘end’ keyword.
 Rule 3: All symbols in the flowchart must be connected with an arrow line.
 Rule 4: Each decision point should have two or more distinct outcomes.
 Rule 5: Flow should generally move from top to bottom or left to right.
Example of a Flowchart
Draw a flowchart to input two numbers from the user and display the largest of two numbers.

Below is the explanation of the above flowchart:


 Start: The process begins with the Start symbol, indicating the start of the program.
 Input num1: The first number, represented as num1, is entered.
 Input num2: The second number, represented as num2, is entered.
 Decision (num1 > num2): A decision point checks if num1 is greater than num2.
o If True, the process moves to the next step where num1 will be displayed.
o If False, the process moves to display num2.
 Stop: The process ends with the Stop symbol, signaling the conclusion of the program.
Advantages of using a Flowchart
 Flowcharts are a better way of communicating the logic of the system.
 Flowcharts act as a guide for blueprint during program designed.
 Flowcharts help in debugging process.
 With the help of flowcharts programs can be easily analyzed.
 They provide better documentation.
 Flowcharts serve as a good proper documentation.
Disadvantages of using a Flowchart
 It is difficult to draw flowcharts for large and complex programs.
 There is no standard to determine the amount of detail.
 It is very difficult to modify the Flowchart.
 Making a flowchart is costly.
 If changes are done in software, then the flowchart must be redrawn
PseudoCode
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is
intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a high-level
language.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem. Pseudocode is
an intermediate state between algorithm and program that plays supports the transition of the algorithm
into the program.

How to write Pseudocode?


Before writing the pseudocode of any algorithm the following points must be kept in mind.
 Organize the sequence of tasks and write the pseudocode accordingly.
 At first, establishes the main goal or the aim. Example:
This program will print first N numbers of Fibonacci series.
 Use standard programming structures such as if-else, for, while, and cases the way we use them in
programming. Indent the statements if-else, for, while loops as they are indented in a program, it helps
to comprehend the decision control and execution mechanism. It also improves readability to a great
extent. Example:
IF "1"
print response
"I AM CASE 1"
IF "2"
print response
"I AM CASE 2"
 Use appropriate naming conventions. The human tendency follows the approach of following what we
see. If a programmer goes through a pseudo code, his approach will be the same as per that, so the
naming must be simple and distinct.
 Reserved commands or keywords must be represented in capital letters. Example: if you are writing
IF…ELSE statements then make sure IF and ELSE be in capital letters.
 Check whether all the sections of a pseudo code are complete, finite, and clear to understand and
comprehend. Also, explain everything that is going to happen in the actual code.
 Don't write the pseudocode in a programming language. It is necessary that the pseudocode is simple
and easy to understand even for a layman or client, minimizing the use of technical terms.
Good vs Bad ways of writing Pseudocode:
Pseudocode Examples:
1. Binary search Pseudocode:
Binary search is a searching algorithm that works only for sorted search space. It repeatedly divides the
search space into half by using the fact that the search space is sorted and checking if the desired search
result will be found in the left or right half.
Example: Given a sorted array Arr[] and a value X, The task is to find the index at which X is present
in Arr[].
Below is the pseudocode for Binary search.

BinarySearch(ARR, X, LOW, HIGH)


repeat till LOW = HIGH
MID = (LOW + HIGH)/2
if (X == ARR[mid])
return MID

else if (x > ARR[MID])


LOW = MID + 1

else
HIGH = MID – 1

2. Quick sort Pseudocode:


QuickSort is a Divide and Conquer algorithm . It picks an element as a pivot and partitions the given array
around the picked pivot.
Say last element of array is picked as pivot then all elements smaller than pivot element are shifted on the
left side of pivot and elements greater than pivot are shifted towards the right of pivot by swapping, the
same algorithm is repeatedly followed for the left and right side of pivot until the whole array is sorted.
Below is the pseudocode for Quick sort

QUICKSORT(Arr[], LOW, HIGH) {


if (LOW < HIGH) {
PIVOT = PARTITION(Arr, LOW, HIGH);
QUICKSORT(ARR, LOW, PIVOT – 1);
QUICKSORT(ARR, PIVOT + 1, HIGH);
}
}

Difference between Algorithm and Pseudocode


Algorithm Pseudocode

An Algorithm is used to provide a solution to a A Pseudocode is a step-by-step description of an


particular problem in form of a well-defined step- algorithm in code-like structure using plain
based form. English text.

Pseudocode also uses reserved keywords like if-


An algorithm only uses simple English words
else, for, while, etc.

These are fake codes as the word pseudo means


These are a sequence of steps of a solution to a
fake, using code like structure and plain English
problem
text
Algorithm Pseudocode

There are no rules to writing algorithms There are certain rules for writing pseudocode

Algorithms can be considered pseudocode Pseudocode cannot be considered an algorithm

It is difficult to understand and interpret It is easy to understand and interpret

Difference between Flowchart and Pseudocode


Flowchart Pseudocode

A Pseudocode is a step-by-step description of an


A Flowchart is pictorial representation of flow of an
algorithm in code like structure using plain
algorithm.
English text.

A Flowchart uses standard symbols for input, output


Pseudocode uses reserved keywords like if-else,
decisions and start stop statements. Only uses
for, while, etc.
different shapes like box, circle and arrow.

This is a way of visually representing data, these are These are fake codes as the word pseudo means
nothing but the graphical representation of the fake, using code like structure but plain English
algorithm for a better understanding of the code text instead of programming language

Pseudocode is better suited for the purpose of


Flowcharts are good for documentation
understanding

Interactive and Script Mode: As a software engineer diving into Python programming, understanding the
different modes of running Python code is crucial. Python offers both Interactive Mode and Script Mode, each
serving distinct purposes in the development process. Today, we’ll explore what Python Interactive Mode is,
how to use it effectively, when it’s beneficial, and compare it to Script Mode for running Python code saved in
a file.

Interactive Mode

What is Python Interactive Mode? Python Interactive Mode, often referred to as the Python REPL (Read-
Eval-Print Loop), provides an interactive environment for executing Python code line by line. It allows
developers to experiment, test code snippets, and quickly get feedback without the need for a complete script
or program.

How to Use Python Interactive Mode

1- Open a Terminal or Command Prompt:

 To access Python Interactive Mode, open a terminal or command prompt on your machine.

2- Type py or python3 and Press Enter:


 Simply typing py on Windows or python3 on Mac / Linux and pressing Enter will launch the Python
Interactive Mode.

3- Start Entering Python Code:

 Once in the Python Interactive Mode, you can start entering Python code directly. Each line is executed
as soon as you press Enter.

>>> print("Hello, Python Interactive Mode!")


Hello, Python Interactive Mode!

4- Experiment and Explore:

 Use the interactive environment to experiment with code snippets, test functions, and explore Python
features without the need to save a script.

When to Use Python Interactive Mode

1- Quick Prototyping:

 Python Interactive Mode is excellent for quickly prototyping ideas and testing small code snippets. It
provides immediate feedback, allowing you to iterate rapidly.

2- Learning and Exploration:

 For software engineers, Interactive Mode is a valuable learning tool. It allows you to explore Python
syntax, experiment with language features, and see the results in real-time.

3- Debugging and Testing:

 When debugging or testing small portions of code, Interactive Mode allows you to interactively evaluate
expressions and observe variable values.

Python Script Mode

What is Python Script Mode?

Python Script Mode involves running Python code saved in a file with a .py extension. This mode is suitable
for larger programs and scripts where code is organized into a file rather than entered interactively.
How to Use Python Script Mode

1- Create a Python Script File:

 Open your preferred text editor and create a new file with a .py extension. For example, myscript.py.

2- Write Python Code in the Script File:

 Add your Python code to the script file. It can include functions, classes, or any Python code structure.

# myscript.py

def greet(name):
print(f"Hello, {name}!")

greet("Alice")

3- Run the Script from the Terminal:

 Open a terminal, navigate to the directory containing your script, and use the py (Windows)
or python3 (Mac / Linux) command followed by the script filename to run it.

python myscript.py

When to Use Python Script Mode

1- Building Larger Programs:

 For developing more extensive projects, applications, or scripts, Script Mode is the preferred choice. It
allows you to organize code into modular structures and maintainability.

2- Reusability:

 Code written in script files can be reused across multiple executions. This is especially valuable when
creating libraries, modules, or packages.

3- Automation and Reproducibility:

 Script Mode is essential for tasks that require automation or reproducibility. Running a script ensures
consistent execution of a set of instructions.
Interactive Mode vs. Script Mode

Interactive Mode Pros and Cons

Pros:

1. Immediate Feedback: Provides instant feedback for code snippets.

2. Learning Tool: Ideal for exploring Python syntax and features.

3. Quick Prototyping: Facilitates rapid prototyping and experimentation.

Cons:

1. Limited Scope: Not suitable for developing larger programs.

2. Lack of Persistence: Code is not saved for future use.

3. Limited Organization: Code organization is minimal compared to script files.

Script Mode Pros and Cons

Pros:

1. Code Organization: Suitable for developing larger, organized programs.

2. Reusability: Code can be saved and reused across multiple executions.

3. Automation: Essential for tasks requiring automation or reproducibility.

Cons:

1. Slower Feedback: Typically involves writing, saving, and executing code, leading to slower feedback
compared to Interactive Mode.

2. Initial Setup: Requires creating and maintaining script files.

Tips for Software Engineers

1- Start with Interactive Mode:

 When learning Python or experimenting with new concepts, begin with Interactive Mode for its
immediate feedback and learning benefits.

2- Transition to Script Mode for Projects:


 As your projects grow, transition to Script Mode for better code organization, reusability, and
maintainability.

3- Use Both Modes Complementarily:

 Consider using both modes complementarily in your workflow. Use Interactive Mode for quick tests and
exploration, and Script Mode for developing larger projects.

4- Leverage Integrated Development Environments (IDEs):

 Many IDEs, including VS Code, offer a combination of both modes within a single interface. Explore the
features of your chosen IDE to maximize productivity.

Conclusion

Understanding Python Interactive Mode and Script Mode is essential for software engineers navigating the
world of Python programming. Each mode serves distinct purposes, with Interactive Mode offering
immediate feedback for exploration and experimentation, and Script Mode providing organization and
reusability for larger projects. By incorporating both modes into your development workflow, you’ll gain a
comprehensive understanding of Python and enhance your proficiency as a software engineer.
Indentation:
In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of
statements belongs to a specific block. All statements with the same level of indentation are considered
part of the same block. Indentation is achieved using whitespace (spaces or tabs) at the beginning of each
line.
For Example:

if 10 > 5:
print("This is true!")
print("I am tab indentation")

print("I have no indentation")

Output
This is true!
I am tab indentation
I have no indentation
 The first two print statements are indented by 4 spaces, so they belong to the if block.
 The third print statement is not indented, so it is outside the if block.

If we Skip Indentation, Python will throw error.

if 10>5:
print("GeeksforGeeks")
Indentation in Conditional Statements
The lines print(‘GeeksforGeeks…’) and print(‘retype the URL.’) are two separate code blocks. The two
blocks of code in our example if-statement are both indented four spaces. The final print( ‘All set!’) is not
indented, so it does not belong to the else block.
a = 20

if a >= 18:
print('GeeksforGeeks...')
else:
print('retype the URL.')
print('All set !')

Output
GeeksforGeeks...
All set !
Indentation in Loops
To indicate a block of code in Python, we must indent each line of the block by the same whitespace. The
two lines of code in the while loop are both indented four spaces. It is required for indicating what block
of code a statement belongs to.

j=1

while(j<= 5):
print(j)
j=j+1

Output
1
2
3
4
5

Comments:

Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the
program.
 Comments enhance the readability of the code.
 Comment can be used to identify functionality or structure the code-base.
 Comment can help understanding unusual or tricky scenarios handled by the code to prevent accidental
removal or changes.
 Comments can be used to prevent executing any specific part of your code, while making changes or
testing.

# I am single line comment

""" Multi-line comment used


print("Python Comments") """

Comments in Python

In Python, single line comments starts with hashtag symbol #.

# sample comment
name = "geeksforgeeks"
print(name)

Output
geeksforgeeks

Multi-Line Comments

Python does not provide the option for multiline comments. However, there are different ways through
which we can write multiline comments.
Multiline comments using multiple hashtags (#)
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered
as a single-line comment.

# Python program to demonstrate


# multiline comments
print("Multiline comments")

Also Check: Interesting Fact about Python Multi-line Comments


Using String Literals as Comment
Python ignores the string literals that are not assigned to a variable. So, we can use these string literals as
Python Comments.
'Single-line comments using string literals'
""" Python program to demonstrate
multiline comments"""
print("Multiline comments")

Best Practice to Write Comments

These are some of the tips you can follow, to make your comments effective are:
1. Comments should be short and precise.
2. Use comments only when necessary, don't clutter your code with comments.
3. Avoid writing generic or basic comments.
4. Write comments that are self explanatory.
Error messages:
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.
Syntax Errors in Python
Syntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in English.
Python stops and points out the issue before running the program.

Example 1 : In this example, this code returns a syntax error because there is a missing colon (:) after the
if statement. The correct syntax requires a colon to indicate the start of the block of code to be executed if
the condition is true.
a = 10000

if a > 2999
print("Eligible")
Output

Example 2: This code returns a syntax error because parentheses around the condition in an if statement
are not required in Python. While optional, their unnecessary use can lead to incorrect syntax.
if(a<3):
print("gfg")
Output

Syntax
error
Python Logical Errors (Exception)
Logical errors are subtle bugs in the program that allow the code to run, but produce incorrect or
unintended results. These are often harder to detect since the program doesn’t crash, but the output is not
as expected.
Characteristics of Logical Errors
 No Syntax Error: The code runs without issues.
 Unexpected Output: The results produced by the program are not what the programmer intended.
 Difficult to Detect: These errors can be tricky to spot since there’s no obvious problem with the code
itself.
 Causes: Faulty logic, incorrect assumptions, or improper use of operators.

Example:
a = [10, 20, 30, 40, 50]
b=0

for i in a:
b += i

res = b / len(a) - 1
print(res)

Output
29.0
Explanation: Expected output is that the average of a should be 30, but the program outputs 29.0. The
logical error occurs because the formula b/ len(a) - 1 incorrectly subtracts 1, leading to an incorrect result.
The correct formula should be b / len(a).
Common Builtin Exceptions
Some of the common built-in exceptions are other than above mention exceptions are:
Exception Description

IndexError When the wrong index of a list is retrieved.

AssertionError It occurs when the assert statement fails

AttributeError It occurs when an attribute assignment is failed.

ImportError It occurs when an imported module is not found.

KeyError It occurs when the key of the dictionary is not found.

NameError It occurs when the variable is not defined.

MemoryError It occurs when a program runs out of memory.

TypeError It occurs when a function and operation are applied in an incorrect type.

Error Handling
Python provides mechanisms to handle errors and exceptions using the try, except, and finally blocks. This
allows for graceful handling of errors without crashing the program.
Example 1: This example shows how try, except and finally handle errors. try runs risky code, except
catches errors and finally runs always.
try:
print("code start")
print(1 / 0)

except:
print("an error occurs")

finally:
print("GeeksForGeeks")

Output
code start
an error occurs
GeeksForGeeks
Explanation:
 try block runs code, raising an exception if any occurs (e.g., 1 / 0 raises ZeroDivisionError).
 except block catches exceptions, printing "an error occurs" in case of an error.
 finally block always executes, printing "GeeksForGeeks" to signal the end of execution.
Example 2: This example shows how try and except handle custom errors. try checks a condition, raises a
ValueError if it fails and except catches and prints the error message.
try:
a = 1999
if a < 2999:

raise ValueError("please add money")


else:
print("Eligible")

except ValueError as e:
print(e)

Output
please add money
Explanation:
 try block sets a = 1999 raises a ValueError if a < 2999, otherwise prints "Eligible".
 except block catches the ValueError and prints "please add money".

Variables:
In Python, variables are used to store data that can be referenced and manipulated during program
execution. A variable is essentially a name that is assigned to a value. Unlike many other programming
languages, Python variables do not require explicit declaration of type. The type of the variable is inferred
based on the value assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our program.
Example:

# Variable 'x' stores the integer value 10


x=5
# Variable 'name' stores the string "Samantha"
name = "Samantha"
print(x)
print(name)

Output
5
Samantha
In this article, we’ll explore the concept of variables in Python, including their syntax, characteristics and
common operations.
Table of Content
 Rules for Naming Variables
 Assigning Values to Variables
 Multiple Assignments
 Type Casting a Variable
 Getting the Type of Variable
 Object Reference in Python
 Delete a Variable Using del Keyword
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
 Variable names can only contain letters, digits and underscores (_).
 A variable name cannot start with a digit.
 Variable names are case-sensitive (myVar and myvar are different).
 Avoid using Python keywords (e.g., if, else, for) as variable names.

Valid Example:
age = 21
_colour = "lilac"
total_score = 90
Invalid Example:
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen

Assigning Values to Variables

Basic Assignment
Variables in Python are assigned values using the = operator.
x=5
y = 3.14
z = "Hi"

Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold different types of values
during execution.

x = 10
x = "Now a string"

Multiple Assignments
Python allows multiple variables to be assigned values in a single line.

Assigning the Same Value


Python allows assigning the same value to multiple variables in a single line, which can be useful for
initializing variables with the same value.

a = b = c = 100
print(a, b, c)

Output
100 100 100

Assigning Different Values

We can assign different values to multiple variables simultaneously, making the code concise and easier to
read.

x, y, z = 1, 2.5, "Python"
print(x, y, z)
Output
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one data type into another. Python provides
several built-in functions to facilitate casting, including int(), float() and str() among others.
Basic Casting Functions
 int() - Converts compatible values to an integer.
 float() - Transforms values into floating-point numbers.
 str() - Converts any data type into a string.

Examples of Casting:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string

# Display results
print(n)
print(f)
print(s2)

Output
10
5.0
25

Getting the Type of Variable


In Python, we can determine the type of a variable using the type() function. This built-in function returns
the type of the object passed to it.
Example Usage of type()
# Define variables with different data types
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True
# Get and print the type of each variable
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))

Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>

Object Reference in Python

Let us assign a variable x to value 5.


x=5

When x = 5 is executed, Python creates an object to represent the value 5 and makes x reference this
object.
Now, if we assign another variable y to the variable x.
y=x

Explanation:
 Python encounters the first statement, it creates an object for the value 5 and makes x reference it. The
second statement creates y and references the same object as x, not x itself. This is called a Shared
Reference, where multiple variables reference the same object.
Now, if we write
x = 'Geeks'
Python creates a new object for the value "Geeks" and makes x reference this new object.

Explanation:
 The variable y remains unchanged, still referencing the original object 5.
If we now assign a new value to y:
y = "Computer"

 Python creates yet another object for "Computer" and updates y to reference it.
 The original object 5 no longer has any references and becomes eligible for garbage collection.
Key Takeaways:
 Python variables hold references to objects, not the actual objects themselves.
 Reassigning a variable does not affect other variables referencing the same object unless explicitly
updated.
Delete a Variable Using del Keyword
We can remove a variable from the namespace using the del keyword. This effectively deletes the variable
and frees up the memory it was using.
Example:
# Assigning value to variable
x = 10
print(x)

# Removing the variable using del


del x

# Trying to print x after deletion will raise an error


# print(x) # Uncommenting this line will raise NameError: name 'x' is not defined
Explanation:
 del x removes the variable x from memory.
 After deletion, trying to access the variable x results in a NameError, indicating that the variable no
longer exists.
Practical Examples
1. Swapping Two Variables
Using multiple assignments, we can swap the values of two variables without needing a temporary
variable.
a, b = 5, 10
a, b = b, a
print(a, b)
Output
10 5
2. Counting Characters in a String
Assign the results of multiple operations on a string to variables in one line.
word = "Python"
length = len(word)
print("Length of the word:", length)
Output
Length of the word: 6
Reserved words:
Python Keywords are reserved words with fixed meanings that define Python’s syntax. Cannot be used as
names.
Python Identifiers are user-defined names for variables, functions, or classes. Must follow naming rules
(no digits at start, only _ allowed).
Keywords in Python
 Predefined and reserved words with special meanings.
 Used to define the syntax and structure of Python code.
 Cannot be used as identifiers, variables, or function names.
 Written in lowercase, except True and False.
 Python 3.11 has 35 keywords.
 The keyword module provides:
o iskeyword() → checks if a string is a keyword.
o kwlist → returns the list of all keywords.
Rules for Keywords in Python
 Python keywords cannot be used as identifiers.
 All the keywords in Python should be in lowercase except True and False.
List of Python Keywords
Category Keywords

Value Keywords True, False, None


Category Keywords

Operator
and, or, not, is, in
Keywords

Control Flow if, else, elif, for, while, break, continue, pass, try, except, finally, raise, ass
Keywords ert

Function and
def, return, lambda, yield, class
Class

Context
with, as
Management

Import and
import, from
Module

Scope and
global, nonlocal
Namespace

Async
async, await
Programming

Getting List of all Python keywords


We can also get all the keyword names using the below code.
import keyword

print(keyword.kwlist)

Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',...
Identifiers in Python
 User-defined names for variables, functions, classes, modules, etc.
 Can include letters, digits, and underscores (_).
 Case-sensitive → num, Num, and NUM are different identifiers.
 Python provides str.isidentifier() to check if a string is a valid identifier.
Rules for Naming Python Identifiers
 It cannot be a reserved python keyword.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
 var1
 _var1
 _1_var
 var_1
Invalid Identifiers
 !var1
 1var
 1_var
 var#1
 var 1
Python Keywords and Identifiers Examples
Example 1: Example of and, or, not, True, False keywords.
print("example of True, False, and, or, not keywords")

# compare two operands using and operator


print(True and True)

# compare two operands using or operator


print(True or False)

# use of not operator


print(not False)

Output
example of True, False, and, or, not keywords
True
True
True
Example 2: Example of a break, continue keywords and identifier.
# execute for loop
for i in range(1, 11):

# print the value of i


print(i)

# check the value of i is less than 5


# if i lessthan 5 then continue loop
if i < 5:
continue

# if i greater than 5 then break loop


else:
break

Output
1
2
3
4
5
Example 3: example of for, in, if, elif, and else keywords.
# run for loop
for t in range(1, 5):
# print one of t ==1
if t == 1:
print('One')
# print two if t ==2
elif t == 2:
print('Two')
else:
print('else block execute')

Output
One
Two
else block execute
else block execute
Example 4: Example of def, if, and else keywords.
# define GFG() function using def keyword
def GFG():
i=20
# check i is odd or not
# using if and else keyword
if(i % 2 == 0):
print("given number is even")
else:
print("given number is odd")

# call GFG() function


GFG()

Output
given number is even
Example 5: Example of try, except, raise.
def fun(num):
try:
r = 1.0/num
except:
print('Exception raises')
return
return r

print(fun(10))
print(fun(0))

Output
0.1
Exception raises
None
Example 6: Example of a lambda keyword.
# define a anonymous using lambda keyword
# this lambda function increment the value of b
a = lambda b: b+1

# run a for loop


for i in range(1, 6):
print(a(i))

Output
2
3
4
5
6
Example 7: use of return keyword.
# define a function
def fun():
# declare a variable
a=5
# return the value of a
return a
# call fun method and store
# it's return value in a variable
t = fun()
# print the value of t
print(t)

Output
5
Example 8: use of a del keyword.
# create a list
l = ['a', 'b', 'c', 'd', 'e']

# print list before using del keyword


print(l)

del l[2]

# print list after using del keyword


print(l)

Output
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'd', 'e']
Example 9: use of global keyword.
# declare a variable
gvar = 10
# create a function
def fun1():
# print the value of gvar
print(gvar)

# declare fun2()
def fun2():
# declare global value gvar
global gvar
gvar = 100

# call fun1()
fun1()

# call fun2()
fun2()

Output
10
Example 10: example of yield keyword.
def Generator():
for i in range(6):
yield i+1

t = Generator()
for i in t:
print(i)

Output
1
2
3
4
5
6
Example 11: Use of assert keyword.
def sumOfMoney(money):
assert len(money) != 0,"List is empty."
return sum(money)

money = []
print("sum of money:",sumOfMoney(money))
Output:
AssertionError: List is empty.
Example 12: Use of pass keyword
class GFG:
pass
g = GFG
Example 13: Use of finally keyword
def divide(a, b):
try:
c = a/b
print("Inside try block")
except:
print("Inside Exception block")
finally:
print("Inside finally block")
divide(3,2)
divide(3,0)

Output
Inside try block
Inside finally block
Inside Exception block
Inside finally block
Example 14: Use of import keyword
import math
print("factorial of 5 is :", math.factorial(5))

Output
factorial of 5 is : 120
Example 15: Use of is keyword
x = 10
y = 20
z=x
print(x is z)
print(x is y)

Output
True
False
Example 16: Use of from keyword
from math import gcd
print("gcd of 345 and 675 is : ", gcd(345, 675))

Output
gcd of 345 and 675 is : 15
Example 17: Use of async and await keyword
# code
import asyncio

async def factorial(n):


if n == 0:
return 1
return n * await factorial(n - 1)
def main():
result = asyncio.run(factorial(5))
print(result)

if __name__ == "__main__":
main()

Output
120

The async and await keywords make it easy to write asynchronous code in Python. They allow you to
write code that runs concurrently with other tasks, which can improve the performance of your programs.
This program defines two functions: factorial() and main(). The factorial() function is an asynchronous
function, which means it can run concurrently with other tasks. The await keyword is used to suspend the
execution of the factorial() function until it completes. The main() function simply calls the factorial()
function and prints the result.

Data types:
Data types in python are classification or categorization of data items. It represents 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 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

Below code assigns variable 'x' different values of few Python data types - int, float, list, tuple and string.
Each assignment replaces previous value, making 'x' take on data type and value of most recent assignment.
x = 50 # int
x = 60.5 # float
x = "Hello World" # string
x = ["geeks", "for", "geeks"] # list
x = ("geeks", "for", "geeks") # set
1. Numeric Data Types
Python numbers represent 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 int, float and complex classes.
 Integers - value is represented by int class. It contains positive or negative whole numbers (without
fractions or decimals). There is no limit to how long an integer value can be.
 Float - value is represented by float class. It is a real number with a floating-point representation. It is
specified by a decimal point. Optionally, character e or E followed by a positive or negative integer may
be appended to specify scientific notation.
 Complex Numbers - It is represented by a complex class. It is specified as (real part) + (imaginary
part)j. For example - 2+3ja = 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
The sequence Data Type is 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:
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python, there is no character data
type, 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.
s = 'Welcome to the Geeks World'
print(s)

# check data type


print(type(s))

# access string with index


print(s[1])
print(s[2])
print(s[-1])

Output
Welcome to the Geeks World
<class 'str'>
e
l
d
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible
as 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 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 index number. In Python, negative sequence indexes represent
positions from end of the array. Instead of having to compute offset as in List[len(List)-3], it is enough to
just write List[-3]. Negative indexing means beginning from end, -1 refers to last item, -2 refers to second-
last item, etc.
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
Tuple is 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, tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use
of parentheses for grouping data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
# initiate empty tuple
tup1 = ()

tup2 = ('Geeks', 'For')


print("\nTuple with the use of String: ", tup2)

Output
Tuple with the use of String: ('Geeks', 'For')
Note - The creation of a Python tuple without the use of parentheses is known as Tuple Packing.
Access Tuple Items
In order to access 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 Boolean Data type is 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 class bool.
Example: First two lines will print type of the boolean values True and False, which is <class 'bool'>. Third
line will cause an error, because true is not a valid keyword. 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, a Dictionary holds a key: value pair. Key-value is provided in 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().
Note - Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
# 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'}
Accessing Key-value in Dictionary
In order to access items of a dictionary refer to its key name. Key can be used inside square brackets. Using
get() method we can access dictionary elements.
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# Accessing an element using key


print(d['name'])

# Accessing a element using get


print(d.get(3))

Output
For
Geeks

Arithmetic Operators
Python operators are fundamental for performing mathematical calculations. Arithmetic operators are
symbols used to perform mathematical operations on numerical values. Arithmetic operators include
addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Operator Description Syntax

+ Addition: adds two operands x+y

Subtraction: subtracts two


x–y
– operands

Multiplication: multiplies two


x*y
* operands

Division (float): divides the


x/y
/ first operand by the second

Division (floor): divides the


x // y
// first operand by the second

Modulus: returns the remainder


when the first operand is x % y
% divided by the second

Power: Returns first raised to


x ** y
** power second
Addition Operator
In Python, + is the addition operator. It is used to add 2 values.

val1 = 2
val2 = 3

# using the addition operator


res = val1 + val2
print(res)
Output:
5

Subtraction Operator
In Python, - is the subtraction operator. It is used to subtract the second value from the first value.
val1 = 2
val2 = 3
# using the subtraction operator
res = val1 - val2
print(res)
Output:
-1

Multiplication Operator
Python * operator is the multiplication operator. It is used to find the product of 2 values.
val1 = 2
val2 = 3

# using the multiplication operator


res = val1 * val2
print(res)
Output :
6

Division Operator
In Python programming language Division Operators allow us to divide two numbers and return a
quotient, i.e., the first number or number at the left is divided by the second number or number at the right
and returns the quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are integers. For
example:
Example:
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)

Output
1.0
5.0
-5.0
10.0
Integer division( Floor division)
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:
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)

Output
3
-3
2.0
-3.0
Modulus Operator
The % in Python is the modulus operator. It is used to find the remainder when the first operand is
divided by the second.
val1 = 3
val2 = 2

# using the modulus operator


res = val1 % val2
print(res)
Output:
1
Exponentiation Operator
In Python, ** is the exponentiation operator. It is used to raise the first operand to the power of the
second.
val1 = 2
val2 = 3
# using the exponentiation operator
res = val1 ** val2
print(res)
Output:
8
Precedence of Arithmetic Operators in Python
Let us see the precedence and associativity of Python Arithmetic operators.
Operator Description Associativity

** Exponentiation Operator right-to-left

%, *, /, // Modulos, Multiplication, Division, and Floor Division left-to-right

+, - Addition and Subtraction operators left-to-right


Expressions :
An expression is a combination of operators and operands that is interpreted to produce some other value.
In any programming language, an expression is evaluated as per the precedence of its operators. So that if
there is more than one operator in an expression, their precedence decides which operation will be
performed first. We have many different types of expressions in Python. Let's discuss all types along with
some exemplar codes :
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3

print(x)

Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and
sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic
operators in Python:

Operators Syntax Functioning

+ x+y Addition

- x-y Subtraction

* x*y Multiplication

/ x/y Division

// x // y Quotient

% x%y Remainder

** x ** y Exponentiation

Example:
Let's see an exemplar code of arithmetic expressions in Python :
# Arithmetic Expressions
x = 40
y = 12

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
print(div)

Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0

c = a + int(b)
print(c)

Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5

c=a/b
print(c)

Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides
of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared
as per relational operator and produce a boolean output in the end. These expressions are also called
Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37

p = (a + b) >= (c - d)
print(p)

Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it
is not correct, so it will return False. Studying logical expressions, we also come across some logical
operators which can be seen in logical expressions most often. Here are some logical operators in Python:

Operator Syntax Functioning

and P and Q It returns true if both P and Q are true otherwise returns false

or P or Q It returns true if at least one of P and Q is true

not not P It returns true if condition P is false

Example:
Let's have a look at an exemplar code :
P = (10 == 9)
Q = (7 > 5)

# Logical Expressions
R = P and Q
S = P or Q
T = not P

print(R)
print(S)
print(T)

Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit
level.
Example:
# Bitwise Expressions
a = 12

x = a >> 2
y = a << 1

print(x, y)

Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single expression, and
that will be termed as combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12

c = a + (b >> 1)
print(c)

Output
22
But when we combine different types of expressions or use multiple operators in a single expression,
operator precedence comes into play.

Multiple operators in expression (Operator Precedence)

It's a quite simple process to get the result of an expression if there is only one operator in an expression.
But if there is more than one operator in an expression, it may give different results on basis of the order
of operators executed. To sort out these confusions, the operator precedence is defined. Operator
Precedence simply defines the priority of operators that which operator is to be executed first. Here we see
the operator precedence in Python, where the operator higher in the list has more precedence or priority:
Precedence Name Operator

1 Parenthesis ()[]{}

2 Exponentiation **

3 Unary plus or minus, complement -a , +a , ~a

4 Multiply, Divide, Modulo / * // %

5 Addition & Subtraction + -

6 Shift Operators >> <<

7 Bitwise AND &

8 Bitwise XOR ^
Precedence Name Operator

9 Bitwise OR |

10 Comparison Operators >= <= > <

11 Equality Operators == !=

12 Assignment Operators = += -= /= *=

13 Identity and membership operators is, is not, in, not in

14 Logical Operators and, or, not

So, if we have more than one operator in an expression, it is evaluated as per operator precedence. For
example, if we have the expression "10 + 3 * 4". Going without precedence it could have given two
different outputs 22 or 52. But now looking at operator precedence, it must yield 22. Let's discuss this with
the help of a Python program:
# Multi-operator expression

a = 10 + 3 * 4
print(a)

b = (10 + 3) * 4
print(b)

c = 10 + (3 * 4)
print(c)

Output
22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python expression.
Built in Functions:
Python is the most popular programming language created by Guido van Rossum in 1991. It is used for
system scripting, software development, and web development (server-side). Web applications can be
developed on a server using Python. Workflows can be made with Python and other technologies.
Database systems are connectable with Python. Files can also be read and changed by it. Big data
management and advanced mathematical operations can both be done with Python.
The syntax of Python is straightforward and resembles that of English. Python's syntax enables
programmers to create programmes with fewer lines of code than they would be able to with certain other
languages. Python operates on an interpreter system, allowing for the immediate execution of written
code.
Python provides a lot of built-in functions that ease the writing of code. In this article, you will learn
about Python's built-in functions, exploring their various applications and highlighting some of the most
commonly used ones.
Python Built-in Functions List
Here is a comprehensive list of Python built-in functions:
Function Name Description

Python abs() Function Return the absolute value of a number

It takes an asynchronous iterable as an argument and returns an asynchronous


Python aiter() Function iterator for that iterable

Return true if all the elements of a given iterable( List, Dictionary, Tuple, set,
Python all() Function etc) are True else it returns False

Returns true if any of the elements of a given iterable( List, Dictionary,


Python any() Function Tuple, set, etc) are True else it returns False

Python anext() Function used for getting the next item from an asynchronous iterator

Python ascii() Function Returns a string containing a printable representation of an object

Python bin() Function Convert integer to a binary string

Python bool() Function Return or convert a value to a Boolean value i.e., True or False

Python breakpoint() It is used for dropping into the debugger at the call site during runtime for
Function debugging purposes

Python bytearray() Returns a byte array object which is an array of given bytes
Function

Converts an object to an immutable byte-represented object of a given size


Python bytes() Function and data

Python callable() Returns True if the object passed appears to be callable


Function

Returns a string representing a character whose Unicode code point is an


Python chr() Function integer
Function Name Description

Python classmethod() Returns a class method for a given function


Function

Python compile() Returns a Python code object


Function

Python complex() Creates Complex Number


Function

Python delattr() Delete the named attribute from the object


Function

Python dict() Function Creates a Python Dictionary

Python dir() Function Returns a list of the attributes and methods of any object

Python divmod() Takes two numbers and returns a pair of numbers consisting of their quotient
Function and remainder

Python enumerate() Adds a counter to an iterable and returns it in a form of enumerating object
Function

Parses the expression passed to it and runs Python expression(code) within


Python eval() Function the program

Python exec() Function Used for the dynamic execution of the program

Filters the given sequence with the help of a function that tests each element
Python filter() Function in the sequence to be true or not

Python float() Function Return a floating-point number from a number or a string

Python format() Formats a specified value


Function

Python frozenset() Returns immutable frozenset


Function

Python getattr() Access the attribute value of an object


Function Name Description

Function

Python globals() Returns the dictionary of the current global symbol table
Function

Python hasattr() Check if an object has the given named attribute and return true if present
Function

Python hash() Function Encode the data into an unrecognizable value

Python help() Function Display the documentation of modules, functions, classes, keywords, etc

Python hex() Function Convert an integer number into its corresponding hexadecimal form

Python id() Function Return the identity of an object

Python input() Function Take input from the user as a string

Python int() Function Converts a number in a given base to decimal

Python isinstance() Checks if the objects belong to a certain class or not


Function

Python issubclass() Check if a class is a subclass of another class or not


Function

Python iter() Function Convert an iterable to an iterator

Python len() Function Returns the length of the object

Python list() Function Creates a list in Python

Python locals() Function Returns the dictionary of the current local symbol table

Returns a map object(which is an iterator) of the results after applying the


Python map() Function given function to each item of a given iterable
Function Name Description

Python max() Function Returns the largest item in an iterable or the largest of two or more arguments

Python memoryview() Returns memory view of an argument


Function

Returns the smallest item in an iterable or the smallest of two or more


Python min() Function arguments

Python next() Function Receives the next item from the iterator

Python object() Returns a new object


Function

Python oct() Function returns an octal representation of an integer in a string format.

Python open() Function Open a file and return its object

Python ord() Function Returns the Unicode equivalence of the passed argument

Python pow() Function Compute the power of a number

Python print() Function Print output to the console

Python property() Create a property of a class


Function

Python range() Function Generate a sequence of numbers

Python repr() Function Return the printable version of the object

Python reversed() Returns an iterator that accesses the given sequence in the reverse order
Function

Rounds off to the given number of digits and returns the floating-point
Python round() Function number
Function Name Description

Convert any of the iterable to a sequence of iterable elements with distinct


Python set() Function elements

Python setattr() Assign the object attribute its value


Function

Python slice() Function Returns a slice object

Python sorted() Returns a list with the elements in a sorted manner, without modifying the
Function original sequence

Python staticmethod() Converts a message into the static message


Function

Python str() Function Returns the string version of the object

Python sum() Function Sums up the numbers in the list

Python super() Function Returns a temporary object of the superclass

Python tuple() Function Creates a tuple in Python

Python type() Function Returns the type of the object

Returns the __dict__ attribute for a module, class, instance, or any other
Python vars() Function object

Python zip() Function Maps the similar index of multiple containers

Python __import__() Imports the module during runtime


Function

Importing from Packages:


Python packages are a way to organize and structure code by grouping related modules into directories. A
package is essentially a folder that contains an __init__.py file and one or more Python files (modules).
This organization helps manage and reuse code effectively, especially in larger projects. It also allows
functionality to be easily shared and distributed across different applications. Packages act like toolboxes,
storing and organizing tools (functions and classes) for efficient access and reuse.
Key Components of a Python Package
 Module: A single Python file containing reusable code (e.g., math.py).
 Package: A directory containing modules and a special __init__.py file.
 Sub-Packages: Packages nested within other packages for deeper organization.

How to create and access packages in python


1. Create a Directory: Make a directory for your package. This will serve as the root folder.
2. Add Modules: Add Python files (modules) to the directory, each representing specific functionality.
3. Include __init__.py: Add an __init__.py file (can be empty) to the directory to mark it as a package.
4. Add Sub packages (Optional): Create subdirectories with their own __init__.py files for sub
packages.
5. Import Modules: Use dot notation to import, e.g., from mypackage.module1 import greet.

Example :In this example, we are creating a Math Operation Package to organize Python code into a
structured package with two sub-packages: basic (for addition and subtraction) and advanced (for
multiplication and division). Each operation is implemented in separate modules, allowing for modular,
reusable and maintainable code.
math_operations/__init__.py:
This __init__.py file initializes the main package by importing and exposing the calculate function and
operations (add, subtract, multiply, divide) from the respective sub-packages for easier access.
# Initialize the main package
from .calculate import calculate
from .basic import add, subtract
from .advanced import multiply, divide
math_operations/calculator.py:
This calculate file is a simple placeholder that prints "Performing calculation...", serving as a basic
demonstration or utility within the package.
def calculate():
print("Performing calculation...")
math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by importing and exposing the add and subtract
functions from their respective modules (add.py and sub.py). This makes these functions accessible when
the basic sub-package is imported.
# Export functions from the basic sub-package
from .add import add
from .sub import subtract
math_operations/basic/add.py:
def add(a, b):
return a + b
math_operations/basic/sub.py:
def subtract(a, b):
return a - b
In the same way we can create the sub package advanced with multiply and divide modules. Now, let's
take an example of importing the module into a code and using the function:
from math_operations import calculate, add, subtract

# Using the placeholder calculate function


calculate()

# Perform basic operations


print("Addition:", add(5, 3))
print("Subtraction:", subtract(10, 4))
Output:
6
8
Python Packages for Web frameworks
In this segment, we'll explore a diverse array of Python frameworks designed to streamline web
development. From lightweight and flexible options like Flask and Bottle to comprehensive frameworks
like Django and Pyramid, we'll cover the spectrum of tools available to Python developers. Whether you're
building simple web applications or complex, high-performance APIs, there's a framework tailored to your
needs.
 Flask: Flask is a lightweight Python web framework that simplifies building web applications, APIs,
and services with an intuitive interface
 Django: Django is a Python web framework that enables fast, efficient development with features like
URL routing, database management, and authentication
 FastAPI:FastAPI is a high-performance Python framework for building modern APIs quickly, using
type hints and providing automatic interactive documentation
 Pyramid: Pyramid is a lightweight Python web framework offering flexibility and powerful features
for HTTP handling, routing, and templating.
 Tornado:Tornado is an asynchronous Python web framework and networking library, ideal for real-
time applications and APIs with its efficient, non-blocking architecture.
 Falcon:Falcon is a lightweight Python web framework for building fast, minimalist RESTful APIs with
a focus on simplicity and performance.
 CherryPy:CherryPy is a minimalist Python web framework that simplifies HTTP request handling,
allowing developers to focus on application logic without server management complexities
 Bottle: Bottle is a lightweight Python web framework for building small applications and APIs with
minimal effort, ideal for prototyping and simplicity.
 Web2py: Web2py is a free open-source web framework for agile development of secure database-
driven web applications. It's written in Python and offers features like an integrated development
environment (IDE), simplified deployment, and support for multiple database backends.
Python Packages for AI & Machine Learning
In this segment, we'll explore a selection of essential Python packages tailored for AI and machine
learning applications. From performing statistical analysis and visualizing data to delving into advanced
topics like deep learning, natural language processing (NLP), generative AI, and computer vision, these
packages offer a comprehensive toolkit for tackling diverse challenges in the field.
Statistical Analysis
Here, we'll explore key Python libraries for statistical analysis, including NumPy, Pandas, SciPy,
XGBoost, StatsModels, Yellowbrick, Arch, and Dask-ML. From data manipulation to machine learning
and visualization, these tools offer powerful capabilities for analyzing data effectively.
 NumPy
 Pandas
 SciPy
 XGBoost
 StatsModels
 Yellowbrick
 Arch
 Dask-ML
Data Visualization
Here, we'll explore a variety of Python libraries for creating stunning visualizations. From Matplotlib to
Seaborn, Plotly to Bokeh, and Altair to Pygal, we've got you covered. By the end, you'll be equipped to
transform your data into compelling visual narratives.
 Matplotlib
 Seaborn
 Plotly
 Bokeh
 Altair
 Pygal
 Plotnine
 Dash
Deep Learning
Here, we'll explore essential frameworks like TensorFlow, PyTorch, Keras, and more. From Scikit-learn
for supervised learning to Fastai for advanced applications, we'll cover a range of tools to unlock the
potential of deep learning.
 Scikit-learn
 TensorFlow
 torch
 Keras
 Keras-RL
 Lasagne
 Fastai
Natural Processing Language
Here, we'll explore essential NLP tools and libraries in Python, including NLTK, spaCy, FastText,
Transformers, AllenNLP, and TextBlob.
 NLTK
 spaCy
 FastText
 Transformers
 fastText
 AllenNLP
 TextBlob
Genrative AI
In this segment, we'll explore a range of powerful tools and libraries that enable the creation of artificial
intelligence models capable of generating novel content. From the renowned deep learning framework
Keras to the natural language processing library spaCy, we'll cover the essential tools for building
generative AI systems.
 Keras
 spaCy
 generative
 GPy
 Pillow
 ImageIO
 Fastai
Computer Vision
Here, we'll explore essential Python libraries like OpenCV, TensorFlow, and Torch, alongside specialized
tools such as scikit-image and Dlib. From basic image processing to advanced object detection, these
libraries empower you to tackle diverse computer vision tasks with ease.
 OpenCV
 TensorFlow
 torch
 scikit-image
 SimpleCV
 ImageAI
 imageio
 Dlib
 Theano
 Mahotas
Python Packages for GUI Applications
GUI development is crucial for modern software, offering intuitive user interactions. This section explores
Python packages like Tkinter, PyQt5, Kivy, PySide, PySimpleGUI, and PyGTK for building GUI
applications.
 Tkinter:Tkinter is a standard Python GUI toolkit for creating desktop applications with graphical
interfaces, featuring widgets like buttons, labels, and entry fields. It is easy to use, pre-installed in most
Python distributions, and popular for simple desktop apps. Additional Tkinter packages include:
 tk-tools
 tkcalendar
 tkvideoplayer
 tkfilebrowser
 PyQT5:PyQt5 is a Python library for creating desktop applications with graphical user interfaces,
based on the Qt framework, providing a wide range of tools and widgets for powerful, customizable
applications.
 Kivy: Kivy is an open-source Python library for developing multi-touch, cross-platform applications
that run on Android, iOS, Windows, Linux, and macOS, offering tools for building user interfaces and
handling touch events.
 PySide: Python PySide is a set of Python bindings for the Qt application framework. It allows
developers to create graphical user interfaces (GUIs) using Qt tools and libraries within Python code,
enabling cross-platform desktop application development with ease.
 PySimpleGUI:PySimpleGUI is a Python library that simplifies GUI development by providing an
easy-to-use interface for creating cross-platform desktop applications..
 NiceGUI: Nicegui is a Python package that simplifies creating buttons, dialogs, plots, and 3D scenes
with minimal code, ideal for micro web apps, dashboards, robotics, smart home solutions, and
development tasks like machine learning and motor control adjustments.
 PyGTK: PyGTK is a set of Python bindings for the GTK (GIMP Toolkit) library, which is a popular
toolkit for creating graphical user interfaces (GUIs). With PyGTK, developers can create cross-
platform GUI applications in Python using GTK's rich set of widgets and tools.
Python Packages for Web scraping & Automation
In this concise guide, we'll explore a curated selection of powerful Python packages tailored for web
scraping and automation tasks. From parsing HTML with Beautiful Soup to automating browser
interactions with Selenium, we'll cover the essentials you need to embark on your web scraping and
automation journey. Additionally, we'll introduce other handy tools like MechanicalSoup, urllib3, Scrapy,
Requests-HTML, Lxml, pyautogui, schedule, and Watchdog, each offering unique functionalities to
streamline your development process.
 Request: Python Requests is a versatile HTTP library for sending HTTP requests in Python. It
simplifies interaction with web services by providing easy-to-use methods for making GET, POST,
PUT, DELETE, and other HTTP requests, handling headers, parameters, cookies, and more.
 BeautifulSoup: Python BeautifulSoup is a library used for parsing HTML and XML documents. It
allows you to extract useful information from web pages by navigating the HTML structure easily.
 Selenium: Python Selenium is a powerful tool for automating web browsers. It allows you to control
web browsers like Chrome or Firefox programmatically, enabling tasks such as web scraping, testing,
and automating repetitive tasks on websites.
 MechanicalSoup: Python MechanicalSoup is a Python library for automating interaction with
websites. It simplifies tasks like form submission, navigation, and scraping by combining the
capabilities of the Requests and BeautifulSoup libraries.
 urllib3: Python urllib3 is a powerful HTTP client library for Python, allowing you to make HTTP
requests programmatically with ease. It provides features like connection pooling, SSL verification,
and support for various HTTP methods.
 Scrapy: Python Scrapy is a powerful web crawling and web scraping framework used to extract data
from websites. It provides tools for navigating websites and extracting structured data in a flexible and
efficient manner.
 Requests-HTML: Python Requests-HTML is a Python library that combines the power of the
Requests library for making HTTP requests with the flexibility of parsing HTML using CSS selectors.
It simplifies web scraping and makes it easy to extract data from HTML documents.
 Lxml: Python lxml is a powerful library used for processing XML and HTML documents. It provides
efficient parsing, manipulation, and querying capabilities, making it a popular choice for working with
structured data in Python.
 pyautogui: PyAutoGUI is a Python library for automating tasks by controlling the mouse and
keyboard. It enables users to write scripts to simulate mouse clicks, keyboard presses, and other GUI
interactions.
 schedule: Python Schedule is a library that allows you to schedule tasks to be executed at specified
intervals or times. It provides a simple interface to create and manage scheduled jobs within Python
programs.
 Watchdog: Python Watchdog is a library that allows you to monitor filesystem events in Python, such
as file creations, deletions, or modifications. It's useful for automating tasks based on changes in files
or directories, like updating a database when new files are added to a folder.
Python Packages for Game Development
Here, we'll explore the exciting world of game development in Python, leveraging powerful packages and
libraries to bring your gaming ideas to life. Let's dive in and discover the tools that will empower you to
create immersive and entertaining gaming experiences.
 PyGame: PyGame is a set of libraries and tools for creating video games and multimedia applications
using Python. It provides functions for handling graphics, sound, input devices, and more, making it
easier to develop games with Python.
 Panda3D: Python Panda3D is a game development framework that provides tools and libraries for
creating 3D games and simulations using the Python programming language. It offers features for
rendering graphics, handling input, and managing assets, making it suitable for both hobbyists and
professional game developers.
 Pyglet: Pyglet is a Python library used for creating games and multimedia applications. It provides
tools for handling graphics, sound, input devices, and windowing. With Pyglet, developers can build
interactive experiences efficiently in Python.
 Arcade: Python Arcade is a beginner-friendly Python library for creating 2D games. It provides tools
for handling graphics, sound, input devices, and other game-related functionalities, making game
development accessible and fun.
 PyOpenGL: PyOpenGL is a Python binding to OpenGL, a powerful graphics library for rendering 2D
and 3D graphics. It allows Python developers to access OpenGL's functionality for creating interactive
visual applications, games, simulations, and more.
 Cocos2d: Python Cocos2d is a simple and powerful game development framework for Python. It
provides tools and libraries for creating 2D games, making game development more accessible and
efficient for Python developers.

You might also like