0% found this document useful (0 votes)
9 views39 pages

Unit 1 Introduction To Python

The document introduces Python programming concepts, focusing on problem-solving techniques, algorithm development, and flowcharting. It outlines the steps involved in analyzing problems, coding solutions, and testing for errors, while emphasizing the importance of structured approaches like Problem Analysis Charts and algorithms. Additionally, it discusses the advantages and disadvantages of flowcharts and pseudocode as tools for visualizing and documenting programming logic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views39 pages

Unit 1 Introduction To Python

The document introduces Python programming concepts, focusing on problem-solving techniques, algorithm development, and flowcharting. It outlines the steps involved in analyzing problems, coding solutions, and testing for errors, while emphasizing the importance of structured approaches like Problem Analysis Charts and algorithms. Additionally, it discusses the advantages and disadvantages of flowcharts and pseudocode as tools for visualizing and documenting programming logic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Unit I INTRODUCTION T0 PYTHON 5 Hrs

Problem Solving, Problem Analysis Chart, Developing an 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 T0 PYTHON

Problem Solving, Problem Analysis Chart, Developing an 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.

Problem Solving

problem-solving involves a systematic approach that includes analyzing the problem,


developing algorithms, coding, and testing.

1. Analyzing the Problem:

Understand the problem clearly before attempting to find a solution. This involves
identifying the inputs required and the expected outputs. A thorough analysis helps in
defining the problem accurately.

2. Developing an Algorithm:

Create a step-by-step procedure or algorithm to solve the problem. An algorithm is a


finite set of well-defined instructions that, when followed, lead to the desired
outcome. It can be represented in natural language, pseudocode, or flowcharts.

3. Coding:

Convert the algorithm into a programming language that the computer can
understand. This step involves writing the actual code that implements the algorithm.

4. Testing and Debugging:

After coding, the program must be tested to ensure it meets the requirements and
produces the correct output. This involves checking for syntax errors and logical
errors. Debugging is the process of identifying and fixing these errors.

PROBLEM ANALYSIS CHART (PAC)

A Problem Analysis Chart helps visualize Input → Process → Output.


Format is usually like this:
Input Process Output

Data that is given to the Operations or calculations Final result


program performed produced

1. Check whether a number is Even or Odd

Input Process Output

A number (N) If N % 2 == 0 → Even "Even" or "Odd"


Else → Odd

2. Find the Sum of First N Natural Numbers

Input Process Output

N (limit) Use formula: Sum = N*(N+1)/2 Sum of first N natural numbers

3. Find the Factorial of a Number

Input Process Output

A number (N) Multiply numbers from 1 to N Factorial of N


Factorial = 1×2×3×...×N

4. Check if a Number is Prime

Input Process Output

A number (N) Check if divisible only by 1 and itself "Prime" or "Not Prime"
If factors found → Not Prime

5. Check if a String is Palindrome

Input Process Output

A string (S) Reverse the string "Palindrome" or "Not Palindrome"


If S == reverse(S) → Palindrome
6. Generate Multiplication Table of N

Input Process Output

A number (N) Multiply N × i (for i=1 to 10) Multiplication table of N

7. Calculate Electricity Bill

Input Process Output

Units consumed If ≤100 → units×1.5 Total bill amount


If 101–200 → (100×1.5) + (units–100)×2.5
If >200 → (100×1.5)+(100×2.5)+(units–200)×4

8. Find Largest of Three Numbers

Input Process Output

Three numbers (a, b, c) Compare values Largest number


If a>b and a>c → Largest=a
Else if b>c → Largest=b
Else → Largest=c

Advantages of a Problem Analysis Chart :

Problem Analysis Chart has numerous advantages, particularly in the context of designing
and developing computer programs.

The key benefits include,

• Enhanced Problem Comprehension: It facilitates a systematic breakdown of the


problem into key components such as inputs, outputs, processing steps, and potential
solution strategies, thereby promoting a deeper understanding of the problem.
• Early Identification of Requirements: The chart clearly outlines the data required
(inputs) and the expected results (outputs), ensuring that all necessary elements are
identified before the implementation phase begins.
• Structured Planning and Organization: It aids in organizing the problem-solving
process in a logical and structured manner, serving as a blueprint for the actual
program development.
• Development of Analytical Thinking: By encouraging a step-by-step approach to
problem-solving, the chart supports the development of critical and analytical
thinking skills, which are essential in programming.
• Reduction of Programming Errors: A well-constructed problem analysis chart
minimizes the risk of logical errors and omissions by clarifying the entire process
prior to coding.
• Simplified Testing and Debugging: It provides a reference point that can be used to
trace and verify the correctness of the program during testing and debugging stages.
• Support for Teaching and Documentation: The chart is a valuable pedagogical tool,
making it easier for educators to explain programming concepts. It also enhances the
quality of project documentation by clearly presenting the problem-solving approach.
• Exploration of Multiple Solution Approaches: By including alternative methods for
solving the problem, the chart encourages creativity and flexibility in program design.

ALGORITHM

An algorithm is an ordered sequence of well-defined, finite, and unambiguous sequence of


instructions designed to complete a specific task.

• It is a step by step procedure for solving any problem.

• An algorithm is an English-like representation of the logical procedure used to address the


problem.

• For a particular task, multiple algorithms may exist, they differ by their time complexity
and space requirements.

• The programmer chooses the most appropriate algorithm based on the efficiency and
suitability for the task at hand.

• An algorithm can be implemented using various programming languages and methods,


depending on the application's requirements.

• An algorithm is independent of any specific programming language

Why Do We Need an Algorithm?

• A programmer writes a program to instruct the computer to do certain tasks as desired.

• The computer then follows the steps written in the program code. Therefore, the
programmer first prepares a roadmap of the program to be written, before actually writing the
code.

• Without a roadmap, the programmer may not be able to clearly visualise the instructions to
be written and may end up developing a program which may not work as expected.
• Such a roadmap is nothing but the algorithm which is the building block of a computer
program.

• Writing an algorithm is mostly considered as a first step to programming. Once we have an


algorithm to solve a problem, we can write the computer program for giving instructions to
the computer in high level language.

• If the algorithm is correct, computer will run the program correctly, every time.

• So, the purpose of using an algorithm is to increase the reliability, accuracy and efficiency
of obtaining solutions.

Characteristics of a Good Algorithm

1. Input – It should clearly state the required inputs.

2. Output – It should specify the expected result.

3. Definiteness – Each step must be clear and unambiguous.

4. Finiteness – It must terminate after a finite number of steps.

5. Effectiveness – Steps must be simple and basic, executable in practice.

6. Generality – It should work for a set of inputs, not just one case.

Structure of an Algorithm

Most algorithms are written in this structure:

1. Start

2. Input (data required)

3. Process (steps or calculations)

4. Output (result)

5. Stop

Example 1: Find the Sum of First N Natural Numbers

Problem: Calculate sum = 1 + 2 + 3 + … + N

Algorithm (Step by Step):

1. Start

2. Read number N (limit)

3. Initialize Sum = 0
4. Repeat steps 5 and 6 for i = 1 to N

5. Add i to Sum → Sum = Sum + i

6. Go to next i

7. Print Sum

8. Stop

Example 2: Check Even or Odd

Problem: Check whether a number is even or odd

Algorithm:

1. Start

2. Input number N

3. If N % 2 == 0 then
Print "Even"
Else
Print "Odd"

4. Stop

Example 3: Factorial of a Number

Problem: Factorial of N (N! = 1 × 2 × … × N)

Algorithm:

1. Start

2. Input number N

3. Set Fact = 1

4. Repeat steps 5 and 6 for i = 1 to N

5. Multiply Fact = Fact × i

6. Go to next i

7. Print Fact

8. Stop

Building Blocks of an Algorithms

The algorithms can be constructed from basic building blocks.


The building blocks are,

• Statements

• State

• Control flow and

• Functions

Statements / Instructions

• An algorithm is a sequence of instructions to accomplish a task or solve a


problem.
• An instruction describes an action. When the instructions are executed, a process
evolves which accomplishes the intended task or solves the given problem.
• The algorithm consists of finite number of statements. It must be in an ordered
form.
• The time taken to execute all the statements of the algorithm should be finite and
within a reasonable limit.

State

• Computational processes in the real-world have state. As a process evolves, the state
changes.

• In an algorithm the state of a process can be represented by a set of variables. The


state at any point of execution is simply the values of the variables at that point.

• As the values of the variables are changed, the state changes.

• State is a basic and important abstraction. An algorithm starts from the initial state
with some input values. As actions are performed, its state changes. It ends with a
final state.

• During computational process the state is stored in one or more the data structures.

Control Flow

• An algorithm is a sequence of statements. However, after executing a


statement, the next statement to be executed need not be the next statement in
the algorithm.
• The statement to be executed next may depend on the state of the process.
Thus, the order in which the statements are executed may differ from the order
in which they are written in the algorithm.
• This order of execution of statements is known as the control flow.

There are three important control flow statements to alter the control flow depending on the
state.
They are,

• Sequence Control Flow

• Selection Control Flow

• Iteration (Looping) Control Flow

These control flows allow the program to make choices, change direction or repeat actions.

i) Sequence Control Flow

In sequential control flow, a sequence of statements is executed one after


another in the same order as they are written.
The instructions in sequence control flow are executed exactly once.

Example: Algorithm to find the sum of two numbers.


Step 1: Start
Step 2: Read two numbers A and B
Step 3: Calculate sum = A + B
Step 4: Print the sum value
Step 5: Stop.
This algorithm performs the steps in a purely sequential order.

ii) Selection Control Flow


In selection control flow, a condition of the state is tested, and if the
condition is true, one statement is executed; if the condition is false, an
alternative statement is executed.

Example: Algorithm to find the greatest among three numbers.


Step 1:Start.
Step 2: Read the three numbers A, B, C.
Step 3: Compare A and B. If A is the greatest perform step 4 else perform
step 5.
Step 4: Compare A and C. If A is the greatest, print “A is the greatest” else
print “C is the greatest”.
Step 5: Compare B and C. If B is the greatest, print “B is the greatest” else
print “C is the greatest”.
Step 6: Stop.

iii) Iteration (Looping) Control Flow


In iteration control flow a set of statements are repetitively executed based
upon a condition. If a condition evaluates to true, the set of statements
(true block) is executed again and again. As soon as the condition becomes
false, the repetition stops. This is also known as looping statement or
iteration statement.

Example: Algorithm to find the sum of first 100 integers.


1. Start
2. Assign sum = 0, i = 0.
3. Calculate i = i + 1 and sum = sum + i
4. Check whether i>= 100, if no repeat step 3. Otherwise go to next step.
5. Print the value of sum
6. Stop

FUNCTIONS

In some cases, algorithms can become very complex. The variables of an algorithm and
dependencies among the variables may be too many. Then, it is difficult to build algorithms
correctly.

In such situations, we break an algorithm into parts, construct each part separately, and then
integrate the parts to the complete algorithm.

Any complex problem will become simpler if the problem is broken smaller and the smaller
problems are solved.

A function is a block of organized, reusable code that is used to perform a similar task of
some kind.

Functions avoid the repetition of some codes over and over. It helps easy debugging, testing
and understanding of the program.

Functions reduce program size and the program development time.

Functions provide better modularity and high degree of reusability for the problems.

FLOWCHART

A flowchart is a diagrammatic representation of the logic for solving a task.

A flowchart is drawn using boxes of different shapes with lines connecting them to show the
flow of control.

The purpose of drawing a flowchart is to make the logic of the program clearer in a visual
form.

The logic of the program is communicated in a much better way using a flowchart. Since
flowchart is a diagrammatic representation, it forms a common medium of communication.

Flowchart Symbols
A flowchart is drawn using different kinds of symbols. Every symbol used in a flowchart is
for a specific purpose

Symbol Meaning

Oval (Terminator) Start / Stop

Parallelogram Input / Output

Rectangle Process / Calculation

Rules Diamond Decision (Yes/No or True/False) for

Arrow Flow of control

drawing a flowchart

1. The flowchart should be clear, neat and easy to follow.

2. The flowchart must have a logical start and finish.

3. Only one flow line should come out from a process symbol.

4. Only one flow line should enter a decision symbol. However, two or three flow lines may
leave the decision symbol.

5. Only one flow line is used with a terminal symbol.

6. Within standard symbols, write briefly and precisely.

7. Intersection of flow lines should be avoided.

Advantages of flowchart:

1. Communication: - Flowcharts are better way of communicating the logic of a system to all
concerned.

2. Effective analysis: - With the help of flowchart, problem can be analyzed in more
effective way

3. Proper documentation: - Program flowcharts serve as a good program documentation,


which is needed for various purposes.
4. Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis
and program development phase.

5. Proper Debugging: - The flowchart helps in debugging process.

6. Efficient Program Maintenance: - The maintenance of operating program becomes easy


with the help of flowchart. It helps the programmer to put efforts more efficiently on that
part.

Disadvantages of flow chart:

1. Complex logic: - Sometimes, the program logic is quite complicated. In that case,
flowchart becomes complex and clumsy.

2. Alterations and Modifications: - If alterations are required the flowchart may require re-
drawing completely.

3. Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart


becomes a problem.

4. Cost: For large application the time and cost of flowchart drawing becomes costly.

PSEUDOCODE:
o Pseudo code consists of short, readable and formally styled English languages
used for explain an algorithm.
o It does not include details like variable declaration, subroutines.
o It is easier to understand for the programmer or non programmer to understand
the general working of the program, because it is not based on any
programming language.
o It gives us the sketch of the program before actual coding. 
o It is not a machine readable
o Pseudo code can’t be compiled and executed.
o There is no standard syntax for pseudo code.

Guidelines for writing pseudo code:

• Write one statement per line


• Capitalize initial keyword
• Indent to hierarchy
• End multiline structure
• Keep statements language independent

Common keywords used in pseudocode

The following gives common keywords used in pseudocodes.

1. //: This keyword used to represent a comment.


2. BEGIN,END: Begin is the first statement and end is the last statement.

3. INPUT, GET, READ: The keyword is used to inputting data.

4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.

5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.

6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.

7. IF, ELSE, ENDIF: used to make decision.

8. WHILE, ENDWHILE: used for iterative statements.

9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.

PYTHON INTERACTIVE AND SCRIPT MODE

Python has two basic modes: interpreter and interactive modes.

The interactive mode is a command line shell, which gives immediate feedback for each
statement, fed in the active memory. As new lines are fed into the interpreter, the fed program
is evaluated both in part and in whole.

The script mode is the mode where the scripted and finished .py files are run in the Python
interpreter.

Python Interactive Mode Python allows the user to work in an interactive mode.

It is a way of using the Python interpreter by executing Python commands from the
command line with no script. This allows the user to type an expression, and immediately the
expression is executed and the result is printed.

To start an interactive mode, The “>>>” is the prompt used in the Python interactive mode
which indicates that the prompt is waiting for the Python command and produces the output
immediately.

Python Interactive Mode

Example:

>>>5+7

12

>>>print(num)

>>>print(“Hello world !”)

Hello world !
>>>num=10

>>>num=num/2

5.0

Working in the interactive mode is convenient for testing a single line code for instant
execution. But in the interactive mode, we cannot save the statements for future use and we
have to retype the statements to run them again.

Python Interactive Mode

Writing Multiline Code in Python Command Line

To write multiline code in Python interactive mode, hit Enter key for continuation lines, this
prompts by default three dots (…). The continuation lines are needed only in the case of
procedures, branching, loop constructs. When it happens, press a tab for indentation.

Example:

>>>flag=1

>>>if flag:

… print(“WELCOME TO PYTHON.”)

WELCOME TO PYTHON.

>>>

Python Script mode

The Python interpreter is a program that reads and executes Python code, in which Python
statements can be stored in a file. The Python system reads and executes the commands from
the file, rather than from the console. Such a file is termed as Python program. Depending on
the environment, start the interpreter by clicking on an icon, or by typing python on a
command line.

The first three lines contain information about the interpreter and the operating system it is
running on.

The version number is 3.6.0. It begins with 3, if the version is Python 3.

It begins with 2, if the version is Python 2.

The last line >>> is a prompt (chevron) that indicates that the interpreter is ready to enter
code.

If the user types a line of code and hits Enter, the interpreter displays the result:
In the interpreter or script mode, a Python program (script) is written in a file, where file
name has extension “.py”. The Python script is executed by the Python interpreter. By
default, the Python scripts are saved in the Python installation folder. Once the script is
created, it can be executed again and again without retyping. The Scripts are editable.

To execute a script, Type the file name along with the path at the prompt.

For example,

if the name of the file is sum.py, we type

>>>python sum.py

Enter 2 numbers 6 3

The sum is 9

INDENTATION

Indentation in Python refers to the whitespace (spaces or tabs) at the beginning of a line of
code. In contrast to many programming languages that use curly braces or specific keywords
to define code blocks, Python uses indentation to mark the boundaries of its code blocks. This
makes indentation a fundamental and mandatory part of Python's syntax.

The key aspects of indentation in Python Statements with the same level of indentation are
considered part of the same code block.

For example, the statements within an if statement, for loop, while loop, or function
definition are grouped by their shared indentation level.

Indentation is not merely a stylistic choice for readability. It is a strict requirement of the
Python interpreter. Incorrect or inconsistent indentation will result in an Indentation Error.
All lines within a single code block must have the same number of leading spaces or tabs.
Mixing spaces and tabs for indentation within the same file or even the same block is strongly
discouraged and can lead to errors.

The Python community widely recommends using four spaces per indentation level. While
other amounts (e.g., two spaces, eight spaces, or tabs) are technically allowed, four spaces is
the conventional standard for consistency and readability.

Example:

n = int(input('Enter a number: '))

sum=0

i=1

while i<=n:
sum=sum+i*i

i+=1

print('Sum = ',sum)

COMMENTS
Comments are used to explain the code, making it more readable and understandable for
both the programmer and non programmers who might work with the code in the future.

Comment statements are non-executable statements so the python interpreter ignores


comments during program execution.

In Python, a comment starts with # (hash sign).

Everything following the # till the end of that line is treated as a comment and the interpreter
simply ignores it while executing the statement.

They have no effect on the program results.

# swap.py

# Swapping the values of a two variable program

Python does not have a dedicated syntax for multi-line comments like some other languages,
multi-line strings enclosed in triple quotes (''' or """) are often used for this purpose.

''' This is a multi-line comment. swap.py swapping the values of a two variable program '''

ERROR MESSAGES

A programmer can make mistakes while writing a program, and hence, the program may not
execute or may generate wrong output.

The process of identifying and removing such mistakes, also known as bugs or errors, from a
program is called debugging.

Errors occurring in programs can be categorized as:

i) Syntax errors
ii) Logical errors
iii) Runtime errors

Syntax Errors Like other programming languages, Python has its own rules that determine its
syntax. The interpreter interprets the statements only if it is syntactically (as per the rules of
Python) correct. If any syntax error is present, the interpreter shows error message(s) and
stops the execution there.

Example: Parentheses must be in pairs, so the expression (20 + 22) is syntactically correct,
whereas (17 + 35 is not due to absence of right parenthesis.

Such errors need to be removed before the execution of the program.

Logical Errors

A logical error is a bug in the program that causes it to behave incorrectly. A logical error
produces an undesired output but without abrupt termination of the execution of the program.
Since the program interprets successfully even when logical errors are present in it, it is
sometimes difficult to identify these errors.

The only evidence to the existence of logical errors is the wrong output.

While working backwards from the output of the program, one can identify what went wrong.

Example: To find the average of two numbers 10 and 12 and we write the code as 10 + 12/2,
it would run successfully and produce the result 16.

Surely, 16 is not the average of 10 and 12.

The correct code to find the average should have been (10 + 12)/2 to give the correct output
as 11.

Logical errors are also called semantic errors as they occur when the meaning of the program
(its semantics) is not correct.

Runtime Error

A runtime error causes abnormal termination of program while it is executing.

Runtime error is when the statement is correct syntactically, but the interpreter cannot
execute it. Runtime errors do not appear until after the program starts running or executing.

Example: In a statement having division operation in the program, by mistake, if the


denominator entered is zero then it will give a runtime error like “division by zero”.

Variables

A variable in Python is a name that refers to a value stored in memory.

It is created when a value is assigned to it.

Variables are used to store data that can be referenced and manipulated throughout a
program.
Rules for Naming Variables

• Variable names must start with a letter or underscore (_).

• They can contain letters, digits, and underscores.

• They cannot start with a digit.

• They cannot be Python reserved words (keywords).

• Variable names are case-sensitive (age and Age are different).

Example: Creating and Using Variables

# Assigning values to variables

name = "Alice"

age = 20

height = 5.4

# Printing values

print(name)

print(age)

print(height)

# Output:

# Alice

# 20

# 5.4

Keywords

⮚ Keywords are reserved words they have a predefined meanings in Python


⮚ Python has 33 keywords

Example

import keyword

print(keyword.kwlist)
Statements

⮚ Statement is a unit of code that has an effect, like creating a variable or displaying a
value

>>> n=7

>>> print(n)

⮚ Here the first line is an assignment statement the gives a value to n


⮚ The second line is a print statement that displays the value of n

Expressions

⮚ An expression is a combination of values, variables and operators


⮚ Example

>>> 42

>>>42
>>>a=2

>>>a+3+2

>>>7
>>>z=("hi"+"friend")

>>>print(z)
>>>hifriend

INPUT AND OUTPUT

⮚ Input is the data entered by user in the program


⮚ In python, input function is available for input

Output

⮚ Output can be displayed to the user using Print statement

Operators in Python

⮚ Operators are the constructs which can manipulate the value of operands
⮚ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called
operator
⮚ Types of operators
o Arithmetic Operators
o Comparison Operators
o Logical Operators
o Assignment Operator
o Membership Operator
o Identity Operator
o Bitwise Operator

Arithmetic Operators

They are used to perform mathematical operations like addition, subtraction, multiplication etc.
Operator Name Expression Example Output
+ Addition x+y 15+4 19
- Subtraction x-y 15-4 11
* Multiplication x*y 15*4 60
/ Division x/y 15/4 3.75
% Modulus x%y 15%4 3
** Exponentiation x**y 15**4 50625
// Floor Division x//y 40//20 3

Example Program

a=int(input("Enter the value of a:\n"))

b=int(input("Enter the value of b:\n"))

c=a+b

print("Result of addition", c)

c=a-b

print("Result of subtraction", c)

c=a*b

print("Result of Multiplication", c)

c=a/b

print("Result of Division", c)

c=a%b

print("Result of Modulus", c)

c=a**b

print("Result of Exponent", c)

c=a//b

print("Result of Floor Division", c)

Output
Comparison Operators

⮚ Comparison operators are also called as Relational Operators


⮚ They are used to compare values and return True or False condition

Operator Name Expression Example Output


> Greater than x>y 54>18 True
< Less than x<y 54<18 False
== Equal to x==y 54==18 False
!= Not equal to x!=y 54!=18 True
>= Greater than or x>=y 54>=18 True
equal to
<= Less than or x <=y 54<=18 False
equal to

Example Program

x=54

y=18

print('x>y is',x>y)

print('x<y is',x<y)

print('x==y is',x==y)

print('x!=y is',x!=y)

print('x>=y is',x>=y)

print('x<=y is',x<=y)

Output
Logical Operators

⮚ Logical operators supported in python are and, or and not

Operator Name Example Explanation

and Logical x and y True if both the operands are


AND true

or Logical OR x or y True if either of the operand is


true

not Logical NOT x not y True if Operand is false

Example Program

x='true'

y='false'

print(' x and y is', x and y)

print('x or y is', x or y)

print('not x is', not x)

Output

Assignment Operators
● Assignment operators are used in Python to assign values to variables. a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.

Operator Name Example Equivalent to

== Equal to X=10 X=10

+= Plus Equal to X+=10 X=X+10

-= Minus Equal to X-=10 X=X-10

/= Division Equal to X/=10 X=X/10

%= Modulus Equal to X%=10 X=X%10

//= Floor equal to X//=10 X=X//10

**= Exponent Equal to X**=10 X=X**10

= Equal to X=10 X=10

Example Program

x=12

y=15

x+=y

print("x+=y:",x)

x-=y

print("x-=y:",x)

x*=y

print("x*=y:",x)

x/=y

print("x/=y:",x)
x%=y

print("x%=y:",x)

x**=y

print("x**=y",x)

x//=y

print("x//=y",x)

Output

x+=y: 27

x-=y: 12

x*=y: 180

x/=y: 12.0

x%=y: 12.0

x**=y 1.5407021574586368e+16

x//=y 1027134771639091.0

Membership Operators

⮚ Membership Operators are used to test whether a value or variable is found in a


sequence (list, sting, tuple, dictionary and set)
⮚ in and not in are two membership operators

Operator Example Explanation

in x in y True if the value or variable found in sequence

not in x not in y True if the value or variable not found in


sequence

Example Program

x="Python Program"

print('y' in x)
print('p' in x)

print('hello' not in x)

print('n' not in x)

Output

Identity Operators

⮚ Identity Operators compare the memory location of two objects


⮚ The two identity operators are is and is not

Example Program

x1 = 5

y 1= 5

x2 = 'Hello'

y2 = 'Hello'

print(x1 is not y1)

print(x2 is y2)
Bitwise Operators

⮚ Bitwise operations manipulate on bits


⮚ Here numbers are represented with bits, a series of zeros and ones

Operator Name Example Explanation

& Bitwise AND X&Y Both operands are true result is true

| Bitwise OR X|Y True if either of the operand is true

` Bitwise NOT `x It complements the bits

^ Bitwise XOR X^Y Result is true if either of the operands


are true

>> Bitwise right shift X>>2 Operands are shifted right by number of
times specified

<< Bitwise left shift X<<2 Operands are shifted left by number of
times specified
Operator Precedence

Operator Description

** Exponentiation (raise to the power)

Complement, unary plus and minus (method


~+-
names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators


is is not Identity operators

in not in Membership operators

not or and Logical operators

⮚ The acronym PEMDAS ( Parentheses, Exponentiation, Multiplication ,Division,


Addition ,Subtraction) is a useful way to remember the rules:
o Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are evaluated
first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8.
o Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and
2*3**2 is 18, not 36.
o Multiplication and Division have higher precedence than Addition and
Subtraction. So 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5
o Operators with the same precedence are evaluated from left to right (except
exponentiation)

BUILT IN FUNCTIONS

Built-in functions are the functions that are always available in Python without needing to
import any module.

They help perform common tasks such as input/output, type conversion, mathematical
operations, and more.

Common Built-in Functions

print()

Displays output on the screen

print("Hello World")

input()

Accepts user input from the keyboard

name=input("Enter your name: ")

type()
Returns the type of a variable or value

type(123) #

len()

Returns the number of items in an object

len("Python") # 6

max()

Returns the largest item from iterable or arguments

max(4, 9, 2) # 9

min()

Returns the smallest item from iterable or arguments

min(4, 9, 2) # 2

sum()

Returns the sum of all items in an iterable

sum([1,2,3]) # 6

round()

Rounds a number to the nearest integer or given decimal place round(3.14159, 2) # 3.14

abs()

Returns the absolute value of a number

abs(-10) # 10

Example Program using Built-in Functions

# Using some built-in functions

name = input("Enter your name: ")

print("Hello", name)

numbers = [10, 20, 30, 40]

print("Total elements:", len(numbers))

print("Maximum:", max(numbers))

print("Minimum:", min(numbers))
print("Sum:", sum(numbers))

print("Rounded value of 3.1456 is", round(3.1456, 2))

# Sample Output:

# Enter your name: Alice

# Hello Alice

# Total elements: 4

# Maximum: 40

# Minimum: 10

• Python provides many built-in functions to simplify common tasks.

• They do not need any import statement to use.

Importing from packages:

• A package is a collection of related modules (Python files containing code such as


functions, classes, and variables).

• Packages help organize and reuse code.

• Common built-in packages include math, random, os, and datetime.

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))


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