PYTHON MODULE 1 COMPLETE Notes KTU
PYTHON MODULE 1 COMPLETE Notes KTU
MODULE 1
SYLLABUS MODULE 1 PART 1
E
Heuristics, Means-Ends Analysis, and Backtracking ( Working backward).
EG
INTRODUCTION
LL
A computer is a very powerful and versatile machine capable of performing various tasks,
yet it has no intelligence or thinking power. A computer performs many tasks exactly in the
same manner as it is told to do. This places responsibility on the user to instruct the
O
computer in a correct and a precise manner, so that the machine is able to perform the
C
required job in a proper manner.
G
In order to instruct a computer correctly, the user must have a clear understanding of the
problem to be solved. The term “problem” refers to a solution where the solution is not
IN
immediately apparent.
R
A problem is defined by four conditions or parameters. They are:-
EE
● Initial situation
● Goal
IN
● Set of resources
● Commitment.
G
If one or more of these components are missing, the problem is not well defined.Problems
EN
1. Well-defined Problems: That have specific goals, clear solutions and known
EA
expected outcomes.
2. Ill-defined Problems: That lack clear goals, solution paths and expected solutions.
M
E
Q2. State any three Well-defined and Ill-defined problems, Justify your answer.
EG
Well-Defined Problems
These problems have clear goals, a defined path to a solution, and specific criteria for
LL
determining when the problem is solved. Let’s explore three examples:
1. Mathematical Equation:
O
■ Problem: Solve the equation 2x+3=7.
C
■ Why it’s Well-Defined: The problem has a clear goal (find the value
G
of x), a specific method (solve for xx using algebraic rules), and a
definite solution (x=2).
IN
2. Crossword Puzzle:
R
■ Problem: Complete a standard crossword puzzle.
EE
■ Why it’s Well-Defined: The crossword has a clear objective (fill in all
the squares with the correct words), a specific set of rules, and a single
IN
correct solution.
3. Recipe Execution:
G
■ Why it’s Well-Defined: The goal (bake a chocolate cake) is clear, the
process is outlined step-by-step in the recipe, and success is
EA
These problems are ambiguous, lack clear criteria for solutions, and often have multiple
possible solutions. Here are three examples:
K
E
Different readers may have different interpretations of what makes the
novel appealing.
EG
3. Resolving Workplace Conflict:
LL
■ Problem: Resolve a conflict between two team members in the
workplace.
O
■ Why it’s Ill-Defined: The problem is complex with no clear solution.
It involves interpersonal dynamics, emotions, and communication
C
styles, and what works in one situation might not work in another.
Multiple solutions may exist, and the "right" one depends on various
G
factors. IN
Summary
R
● Well-Defined Problems are structured, with a clear path and solution.
EE
A problem solving strategy is a plan used to find a solution or overcome a challenge. Each
EN
problem solving strategy includes multiple steps to provide you with helpful guidelines on
how to resolve a problem. Effective problem solving requires you to identify the problem,
select the right process to approach it and develop a plan to resolve the issue.
EA
through a systematic trial and error method, while others might benefit from a more
analytical approach like means-ends analysis. By knowing several strategies, one can
quickly switch tactics when one method does not work, increasing the chances of finding a
successful solution. Having a collection of problem-solving strategies enhances critical
thinking and creativity thereby leading to more innovative and effective solutions. It boosts
confidence and competence in facing various challenges.
Benefits include :-
● Adaptability
● Efficiency
● Improved Outcomes
● Skill Development
Steps Involved in Problem Solving:- Identify the problem, Define the problem, List all the
E
possible solutions, Evaluate options and Implement the solution.
EG
Problem Solving Strategies
LL
1. Trial and Error
O
2. Algorithm
3. Heuristics
C
4. Means-Ends Analysis
5. Backtracking
G
1. Trial and Error
IN
A trial-and-error approach to problem-solving involves trying a number of different
R
solutions and ruling out those that do not work. This approach can be a good option if you
EE
have a very limited number of options available. Using trial and error, one has to try
different solutions until the problem is solved.
IN
Steps :
1. Identify the problem – Start by clearly defining the issue
G
Example
1. In terms of a broken printer for example, one could try checking the ink levels, and
if that doesn’t work, you could check to make sure the paper tray isn’t jammed. Or
M
Although trial and error is not typically one of the most time-efficient strategies, it is a
commonly used one.
2. Algorithm
E
1. Gather ingredients
EG
2. Preheat Oven
3. Mix Ingredients
4. Prepare baking Pan
LL
5. Pour Batter
6. Bake
O
7. Check for Doneness
8. Cool and Serve
C
When you run a search on the Internet, search engines like Google use algorithms to decide
G
which entries will appear first in your list of results. Facebook also uses algorithms to
IN
decide which posts to display on your newsfeed.
R
3. Heuristics
EE
A heuristic is another type of problem solving strategy that allow us to make decisions
quickly without having all the relevant information. It can thought of as mental shortcuts
IN
that are used to solve problems. A “rule of thumb” is an example of a heuristic. Such a rule
saves the person time and energy when making a decision. Different types of heuristics are
G
used in different types of situations, but the impulse to use a heuristic occurs when one of
five conditions is met:-
EN
● When there is access to very little information to use in making the decision
● When an appropriate heuristic happens to come to mind in the same moment
M
For example : For completing a large research project, they typically start by
● students typically brainstorm, develop a thesis or main topic,
● research the chosen topic, organize their information into an outline,
● write a rough draft
● revise and edit the rough draft, develop a final draft, organize the references
list
● proofread their work before turning in the project.
The large task becomes less overwhelming when it is broken down into a series of small
steps.
E
This method involves making a guess, checking if it solves the problem, and refining the
EG
guess based on outcomes. This method is particularly useful when the problem doesn’t
have an obvious solution, and you can try different possibilities until you find the correct
one.
LL
How Guess and Check Works:
O
1. Make an Initial Guess: Start by guessing a possible solution based on what you
C
know.
2. Check the Guess: Determine if your guess solves the problem.
G
3. Refine the Guess: If the guess is incorrect, use the information you gained from
IN
checking to make a better guess.
4. Repeat: Continue guessing, checking, and refining until you find the correct
R
solution.
Example : Find the number that when added to 15, gives 32.
EE
Solution :-
IN
c. Working backwards
M
This is a useful heuristic in which you begin solving the problem by focusing on the end
result.
K
Consider this example: Imagine you need to arrive at an important meeting by 3.00pm. To
plan your day using the working backwards heuristic, you need to start from the end result
and think about the steps needed to get there. You consider that it takes 30 minutes to get to
the meeting location, so you need to leave by 2.30pm. Before that you need an hour to
prepare,so you start getting ready at 1.30pm. If you also want to finish a task that takes an
hour before getting ready, you need to start that by 12.30pm. By working backwards, you
effectively plan your day to ensure you arrive at the meeting on time.
This strategy involves choosing and analyzing a problem at a series of smaller steps to
move closer to the goal.
The Tower of Hanoi is a mathematical puzzle. There are three rods, source(A), Auxiliary
E
(B) and Destination(C). Rod A contains a set of disks stacked to resemble a tower, with the
EG
largest disk at the bottom and the smallest disk at the top. Fig:- 1 Illustrate the initial
configuration of the rods for 3 disks. The objective is to transfer the entire tower of disks in
rod A to rod C maintaining the same order of the disks.
LL
Rules:
O
1. Only one disk can be transferred at a time.
C
2. Each move consists of taking the upper disk from one of the rods and placing it on
the top of another rod i.e. a disk can only be moved if it is the uppermost disk of the
G
rod. IN
3. Never a larger disk is placed on a smaller disk during the transfer.
R
EE
IN
The solution to the puzzle calls for an application of recursive functions and recurrence
EN
relations.
A recursive procedure for the solution of the problem for N number of disks is as follows:
EA
1. Move the top N-1 disks from rod A to rod B using C as an auxiliary rod
2. Move the bottom disk from rod A to rod C
M
3. Move N-1 disks from rod B to rod C using Peg A as an auxiliary rod
K
The minimum number of moves required to solve a Tower of Hanoi puzzle is given by
2^N – 1, where N is the number of disks. i.e., if there are 14 disks, then minimum
number of moves needed = (2^14) - 1 = 16383.
The pictorial representation of the recursive procedure for N=4 disks is shown in Fig 2:-
E
EG
LL
O
C
G
IN
R
Example of Tower of Hanoi for n=3.
EE
IN
G
EN
EA
M
K
E
EG
LL
O
C
G
IN
R
EE
IN
Example 2: Imagine you want to plan a road trip from Trivandrum to Kashmir. Here is how
EN
A. Define the Goal: Your ultimate goal is to drive from Trivandrum to Kashmir.
EA
B. Analyze the Current State: You start in Trivandrum with your car ready to go.
C. Identify the Differences: The primary difference is the distance between Trivandrum
and Kashmir, which is approximately 3,700 kilometers.
M
b. Daily Driving Targets: Break the trip into daily segments, driving 500-600 kms per
day.
c. Route Planning: Choose the most efficient and scenic route, considering highways,
weather conditions, and places you want to visit.
E. Implement the Plan:
a. Day 1: Drive from Trivandrum to Bangalore, Karnataka (approx. 720 km). Refuel
in Madurai, Tamil Nadu. Overnight stay in Bangalore.
b. Day 2: Drive from Bangalore to Hyderabad, Telangana (approx. 570 km). Refuel
in Anantapur, Andhra Pradesh. Overnight stay in Hyderabad.
c. Day 3: Drive from Hyderabad to Nagpur, Maharashtra (approx. 500 km). Refuel in
Adilabad, Telangana. Overnight stay in Nagpur.
d. Day 4: Drive from Nagpur to Jhansi, Uttar Pradesh (approx. 580 km). Refuel in
Sagar, Madhya Pradesh. Overnight stay in Jhansi.
e. Day 5: Drive from Jhansi to Agra, Uttar Pradesh (approx. 290 km). Refuel in
Gwalior, Madhya Pradesh. Overnight stay in Agra. Visit the Taj Mahal.
E
f. Day 6: Drive from Agra to Chandigarh (approx. 450 km). Refuel in Karnal,
EG
Haryana. Overnight stay in Chandigarh.
g. Day 7: Drive from Chandigarh to Jammu (approx. 350 km). Refuel in Pathankot,
Punjab. Overnight stay in Jammu.
LL
h. Day 8: Drive from Jammu to Srinagar, Kashmir (approx. 270 km).
F. Adjust as Needed: Throughout the trip, you may need to make adjustments based on
O
traffic, road conditions, or personal preferences.
C
By breaking down the long journey into smaller segments and addressing each part
systematically, you can effectively plan and complete the road trip. This method ensures
G
that you stay on track and make steady progress toward your final destination, despite the
IN
complexity and distance of the trip.
5. Backtracking
R
Backtracking is a problem solving technique that involves trying different options until the
EE
right solution is found. Backtracking algorithms are problem solving strategies that explore
various options to find the optimal solution. They operate by testing different paths, and if
IN
a path doesn't lead to a solution they backtrack and try another route until they find the
correct one. Backtracking can also be defined as a technique that involves finding a
solution incrementally by trying different options and undoing them if they lead to a dead
G
end.
EN
In the above problem, the Start node is X and destination node is G. We first move through
the route X-A-B but it reaches a dead end, then we backtrack again and select another path
X-A-C, it also encounters a dead end. Try different paths X-D-E,also reach a dead end.
Next we move through X-D-F-G and reach the destination node.
Whenever a dead end is encountered it goes back to the start node and continues searching
for a different route until the solution is discovered or all options have been considered.
Other examples :- Sudoku puzzle, Maze problem, forgetting the PIN to unlock your
E
smartphone etc.
EG
SYLLABUS MODULE - 1 PART - 2
LL
THE PROBLEM-SOLVING PROCESS:- Computer as a model of computation,
Understanding the problem, Formulating a model, Developing an algorithm, Writing
O
the program, Testing the program, and Evaluating the solution.
C
Basic Model of a Computer
G
Computer science is all about solving problems with computers. The problems that we
want to solve can come from any real-world problem or from the abstract world. We need
IN
to have a standard systematic approach to solving problems. Since we will be using
computers to solve problems, it is important to first understand the computer’s information
R
processing model.
EE
The model shown in figure below assumes a single CPU (Central Processing Unit). Many
computers today have multiple CPUs, so it can be imagined the model in the figure can be
duplicated multiple times within the computer.
E
a computer retrieves a program instruction from its memory, determines what actions to
EG
perform, and carries out those actions to produce meaningful output.
LL
1. Fetch the instruction from memory
2. Decode the instruction, and the operation to be performed is thus identified.
O
3. Execute the instruction, performing the operation identified in the decode step by the CPU.
C
4. Store the result in the main memory, or send it to an output device.
G
This cycle is then repeated for the next instruction.
IN
Instruction Execution Cycle
R
EE
IN
G
EN
EA
M
The I/O unit consists of the input unit and output devices. The input devices accept data
from the user, which the CPU processes. The output devices transfer the processed data
(information) to the user. The memory unit is used to store the input data, the instructions
required to process the input, and the output information.
Input devices
E
Input devices allow users to input data into the computer for processing. The data input to a
EG
computer can be in the form of text, audio, video, etc. Input devices are classified into two
categories:
LL
1. Human data entry devices – the user enters data into the computer by typing or
pointing a device to a particular location. Some examples are
O
a. Keyboard – the most common typing device.
C
b. Mouse – the most common pointing device. You move the mouse around on a
G
mouse pad and a small pointer called cursor follows your movements on the
computer screen.
IN
c. Trackball – an alternative to a mouse which has a ball on the top. The cursor on
R
the computer screen moves in the direction in which the ball is moved.
EE
e. Graphics tablet – converts hand-drawn images into a format suitable for computer
processing.
G
2. Source data entry devices –They use special equipment to collect data at the source,
EN
create machine-readable data, and feed them directly into the computer. This category
comprises:
EA
a. Audio input devices – It uses human voice or speech to give input. Microphones
are an example.
M
b. Video input devices – They accept input in the form of video or images. Video
K
c. Optical input devices – They use optical technology (light source) to input the
data into computers. Some common optical input devices are scanners and barcode
readers.
Output devices
An output device takes processed data from the computer and converts them into
information that can be understood by humans. The output could be on paper or can be
audio, video, etc. Output devices are classified as follows:
E
1. Hard copy devices – The output obtained on paper or any surface is called hard copy
output. The hard copy can be stored permanently and is portable. The hard copy output can
EG
be read or used without a computer. Examples in this category include:
LL
a. Printer – prints information on paper. The information could be textual or even
images. Drum printers, laser printers, and inkjet printers are some commonly used
printer types.
O
b. Plotter – used to produce very large drawings on paper using very fine pens.
C
Flatbed plotters and drum plotters are two types of plotters.
G
2. Soft Copy Devices – Generates a soft copy of the output on a visual display (monitor),
IN
audio unit, or video unit. The soft copy can be stored and sent via e-mail to other users. It
also allows corrections to be made. The soft copy output requires a computer to be read or
R
used. This category comprises:
EE
is a screen image projector or data projector that displays information from the
computer onto a large white screen.
G
c. Audio output devices – speakers, headsets, or headphones, are used for audio
EN
The Central Processing Unit (CPU) or the processor, is known as the brain of a computer. It
consists of an Arithmetic Logic Unit (ALU) and a Control Unit (CU). In addition, the CPU
M
also has a set of registers which are temporary storage areas for holding data and
instructions.
K
This unit consists of two sub-units, namely arithmetic and logic units.
II. Registers
Registers are high-speed storage areas within the CPU but have the least storage capacity.
They store data, instructions, addresses, and intermediate results of processing. Some of the
commonly used registers are:
E
a. Accumulator (ACC) – stores the result of arithmetic and logic operations.
EG
b. Instruction Register (IR) – holds the instruction that is currently being executed.
c. Program Counter (PC) – holds the address of the next instruction to be processed.
LL
III. Control Unit
O
This unit manages and coordinates the operations of all parts of the computer. The
C
functions of this unit are:
G
● obtain instructions from the memory, interpret them, and then direct the ALU to
IN
execute those instructions.
● communicate with I/O devices.
R
● decides when to fetch the data and instructions, what operation to perform, where to
EE
Memory unit
IN
Memory is the storage space in a computer where data to be processed and instructions
G
required for processing are stored. The various memories can be organized hierarchically
EN
E
1. Registers – high-speed storage areas within the CPU.
EG
2. Primary memory – main memory of the computer. It is categorized into two:
LL
a. Random Access Memory (RAM) – used for storing data and instructions
during the operation of a computer. Data to be processed is brought to RAM
O
from input devices or secondary memory. It is a volatile memory, because
stored data may get lost if it is not saved. After processing, the results are stored
C
in RAM before being sent to the output device.
G
IN
b. Read Only Memory (ROM) – a non-volatile primary memory. It does not lose
its content when the power is switched off. ROM, as the name implies, has only
R
reading capability and no write capability. After the information is stored in
EE
3. Cache memory – placed between RAM and CPU and stores the data and
G
access device, meaning that the data can be read only in the order in which it is
K
stored.
2. Magnetic disk – a thin plastic or metallic circular plate coated with magnetic oxide
and encased in a protective cover. Hard disk is an example.
3. Optical disk – a flat circular disk coated with reflective plastic material that can be
altered by laser light. CDs and DVDs are examples.
E
Definition: Problem Solving is the sequential process of analyzing information related
EG
to a given situation and generating appropriate response options.
LL
In solving a problem, there are some well-defined steps to be followed. It is noted that the
problem is easily solved by simply getting the input, computing something and producing
the output. We now examine the steps to problem solving within the context of various
O
examples.
C
Steps involved in problem solving
G
1. Understanding the problem
IN
2. Formulating a model
R
3. Developing an algorithm
EE
o It may sound simple, but the first step in solving any problem is to fully
understand it.
M
● INPUT REQUIREMENTS
We need to understand the input we require to solve the problem. For the
given example, input requirement is two numbers whether it can be of any type, like
real number, integer number or whole number.
● OUTPUT REQUIREMENTS
Next we need to understand the output to obtain corresponding to the input
given. if we are giving real numbers as input the output obtained will be real, or if it
is integer then output will be integer.
● PROCESSING CONSIDERATIONS
We also need to understand how to reach the solution from the input given
E
i.e, to understand a path to reach the solution.
EG
Formulating a model
LL
● The next step is to understand the processing part of the problem.
● In the example given, the sum of two numbers is to be computed. A model is thus
O
needed for computing the sum of two numbers. If there is no such “formula”, one
C
must be developed.
● Assuming that the input data is two integer numbers Number1, Number2
G
representing a two numbers
Sum = Number1 + Number2
IN
The main point to understand this step in the problems solving process is that it is all about
figuring out how to make use of the available data to compute an answer.
R
Developing an algorithm
EE
● Next step is to develop a precise plan of what the computer is expected to do.
IN
● Example: - Let’s use a simple math problem to develop an algorithm, a pseudo code
M
● Algorithm
Step 1: Start
Step 2: Input the first number
Step 3: Input the second number
Step 4: Add the two numbers
Step 5: Display the result
Step 6: End
● Pseudo code
1. Start
2. Input Number1
3. Input Number2
4. Sum = Number1 + Number2
5. Output Sum
E
6. End
EG
● Flow chart
LL
O
C
G
IN
R
EE
IN
G
EN
computer can execute. This process is known as writing the program, coding, or
implementing an algorithm.
M
● The next step is to transform the algorithm into a set of instructions that can be
understood by the computer. Writing a program is often called "coding" or
K
“implementing an algorithm”.
● Program in Python
n1 = 21
n2 = 7
sum = n1 + n2
print('Sum =', sum)
● After writing the code, test it with various inputs to ensure it works as expected.
Debug and compile the program to find issues or errors that arise during testing.
● Debugging is the method of finding and fixing errors.
● Compiling is the process of converting a program into instructions that can be
understood by the computer.
Testing the Program
E
● Once a program has been written and compiled, the next critical step is to ensure
EG
that whether the program performs the intended task correctly. Testing the program
involves running it with various inputs to verify its accuracy and reliability.
● Running a program is the process of telling the computer to evaluate the compiled
LL
instructions.
● If the program runs correctly, the expected output should be displayed.
O
● If the program doesn’t run correctly for some inputs then the user has to go back to
the algorithm development step that handles all situations that could arise.
C
o If the output is incorrect, it could be due to the algorithm not being properly
implemented in the program. or
G
o A flaw or a bug in the algorithm itself, which does not account for certain
IN
situations.
Bugs are errors in a program that cause it to produce incorrect or undesirable
R
results.
EE
INPUT REQUIREMENT: get all the grades … possibly by typing them in via the
K
keyboard
● Key Questions:
o What input data/information is available?
o What does the data represent, and in what format?
o Is anything missing from the data?
o Do I have everything needed to solve the problem?
E
OUTPUT REQUIREMENTS: output the answer to either the monitor, or to the printer
EG
● What output is needed, and in what format (text, number, graph)?
● Example: Should the result be a number, a letter grade, or a pie chart
LL
PROCESSING CONSIDERATIONS: Add them all up and compute the average grade.
Understand the processing steps required to achieve the desired output. This understanding
guides the problem-solving process.
O
Formulating a model
C
In the example given, the average of the incoming grades is to be computed. A model (or
G
formula) is thus needed for computing the average of a bunch of numbers. If there is no
IN
such “formula”, one must be developed.
R
· Assuming that the input data is a bunch of integers or real numbers 𝑥1, 𝑥2, ⋯ , 𝑥𝑛
representing a grade percentage, the following computational model may apply:
EE
𝐴𝑣𝑒𝑟𝑎𝑔𝑒1 = (𝑥1 + 𝑥2 + 𝑥3 + ⋯ + 𝑥𝑛 )/𝑛 where the output will be a number from 0 to 100.
IN
·
The challenge facing in the above calculation is Letter grades (e.g., A, B-, C+)
G
o If it is assumed that these newly assigned grade numbers are 𝑦1, 𝑦2, ⋯ , 𝑦𝑛,
then the following computational model may be used:
K
The main point to understand this step in the problems solving process is that it is all about
figuring out how to make use of the available data to compute an answer.
Developing an algorithm:
Algorithm
STEP 1: Start
STEP 2: Read number of students, n
E
STEP 2: Read the marks of n students
EG
STEP 3: Compute average using the formula
STEP 4: Display Average
STEP 5: Stop
LL
Pseudo code
O
1. Start
C
2. Input n
3. Input the marks of n students, x1,x2,x3,…,xn
G
4. Average=(x1+x2+x3+…+xn)/n
5. Output Average
IN
6. End
R
Flow chart
EE
IN
G
EN
EA
M
K
· # Program in Python
n = int("input(Enter number"))
sum = 0
# loop from 1 to n
for num in range(1,n+1,1):
E
sum = sum+num
EG
average=sum/n
print("Average of ",n,"numbers is: ",average)
LL
Test the program: You create a test suite with various types of numbers and check whether
the output obtained is correct or not.
O
EXAMPLE 3 : - A case study - The Discriminant calculator
C
1. Understanding the problem: Here we formally define the problem by specifying
G
the inputs and output. IN
Input: The three coefficients a, b and c of the quadratic equation
Output: The discriminant value D for the quadratic equation
R
EE
STEP 1: Start
STEP 2: Read (a,b,c)
EA
STEP 3: d = b∗b−4∗a∗c
STEP 4: Print (d)
M
STEP 5: Stop
K
E
EG
LL
O
C
G
SYLLABUS MODULE - 1 PART - 3 IN
ESSENTIALS OF PYTHON PROGRAMMING:- Creating and using variables in Python,
Numeric and String data types in Python, Using the math module, Using the Python
R
Standard Library for handling basic I/O - print, input, Python operators and their
EE
precedence.
Essentials of Python Programming
IN
INTRODUCTION
G
PROGRAMMING LANGUAGES
EN
program instructions.
Programming languages fall into three categories:
M
1. Machine language:- is what the computer can understand, but it is difficult for the
K
E
use symbolic names (like ADD, SUB) for operations called mnemonic codes that are
EG
much easier to remember.
Example : If the mnemonic code for addition is ADD, then to add 3 and 6, the assembly
level code will be ADD 3,6.
LL
Machine languages and assembly languages are also called low level languages.
O
3. High-level language:- is easier to understand and use for the programmer but difficult
C
for the computer. The programs written in high-level languages contain English-like
statements as well as programming.
G
Eg:- C, FORTRAN, Pascal, Java, Python etc. that enables a programmer to write programs.
IN
High level language programs are easier to write, read, and understand. They are easily
portable from one computer to another, since they are not machine-dependent.
R
EE
Example : To add 3 and 6, the high level language code will be 3+6.
Here ‘+’ is the operator for addition.
IN
TRANSLATOR SOFTWARE
The computer can understand only machine code (strings of 0’s and 1’s). Thus when the
G
converted to machine code. This conversion is called translation and is performed by the
translator software.
The original program is called source code, and the translated code (object code) is the
EA
target code.
There are three types of translator software as discussed below:
M
machine code.
2. Compiler : is a software that translates programs written in high-level language to
machine code.
3. Interpreter : The interpreter also converts the high-level language program into
machine code. However, the reads the source code line-by-line, converts it into
machine code, executes the line, and then proceeds to the next line.
E
EG
LL
O
C
G
IN
INTRODUCTION TO PYTHON
R
Python is a general purpose, high-level, interpreted programming language developed by
EE
Guido van Rossum in the late 1980s at the National Research Institute for Mathematics
and Computer Science in the Netherlands. Python is one of the most popular and widely
used programming languages used for a set of tasks including Console based, GUI based,
IN
web programming and data analysis. Python is named after the comedy television show
Monty Python's Flying Circus.
G
FEATURES OF PYTHON
EN
EA
M
K
APPLICATIONS OF PYTHON
E
● Software Development
EG
● Scientific and Numeric computations
● Business Applications
● Audio or Video based Applications.
LL
START PROGRAMMING WITH PYTHON
O
There are two major Python versions, those are Python 2 and Python 3. Python 3 is more
C
semantically correct and supports newer features. After successful installation of python
software we can interpret or execute python script / program.
G
Python provides us the two ways to run a python script:
IN
1. Using Interactive interpreter prompt
R
2. Using a script file
EE
Python provides us the feature to execute the python statement one by one at the interactive
prompt. It is preferable in the case where we are concerned about the output of each line of
G
our python program. To open the interactive mode, open the terminal (or command
prompt) and type python3.
EN
The Python shell is an interactive terminal-based environment wherein you can directly
communicate with the Python interpreter. First, you open a terminal and type python3.
Now the shell turns up with a welcome message as shown below.
user@Ubuntu2204LTS:~$ python3
Python 3.10.12 (main, Jul 29 2024, 16:56:48) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information
E
The symbol >>> is called the shell prompt. This symbol prompts you for Python
statements. When you enter a statement in the shell, the Python interpreter processes it and
EG
displays the result, if any, then followed by a new prompt as shown below:
>>> "Welcome to the world of Python programming"
LL
'Welcome to the world of Python programming'
>>>
O
Using Script File
C
Interpreter prompt is good to run the individual statements of the code. However if we
want to execute multiple python statements at a time instead of executing one by one, then
G
we can use script files. We need to write our script into a file which can be executed later.
IN
For this purpose, open an editor like notepad, create a file named filename.py (python used
.py extension) and write the python script in it.
R
EE
IN
G
EN
Running as a script
EA
1. Combine all the statements that you wish to execute into a Python program.
Program is known as a script and should be saved with the “py” extension, for
example sample.py.
M
2. You may use some text editor to create your script. gedit, vim are some of the
K
Example : Suppose you have written a script sample.py to display the message “My first
Python program!”. This is how you run it (The second line below shows the output):
user@Ubuntu2204LTS:~$ python3 First.py
My first Python program!
Comments in Python
● Comments are used in a programming language to describe the program or to hide
E
some part of code from the interpreter.
EG
● Comment is not a part of the program, but it enhances the interactivity of the
program and makes the program readable.
● Python supports two types of comments:
LL
1. Single Line Comment
2. Multi Line Comment
O
C
G
IN
R
EE
IN
G
EN
EA
scripting.
K
Character set
● Alphabets: All capital (A-Z) and small (a-z) alphabets.
● Digits: All digits 0-9.
● Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @ # $
%^`&*()_+–={}[]\
● White Spaces: White spaces like tab space, blank space, newline, and carriage return.
Python tokens
● A token is the smallest individual unit in a python program.
● All statements and instructions in a program are built with tokens.
● The various tokens in python are :
E
EG
LL
O
C
G
1. Keyword (Reserved words)
IN
● Keywords are words that have some special meaning or significance in a
R
programming language.
● They can’t be used as variable names, function names, or for any other random
EE
purpose.
IN
G
EN
EA
M
2. Identifiers
● Identifiers are the names given to any variable, function, class, list, methods, etc. for
K
their identification.
● Python has some rules and regulations to name an identifier.
● Rules to name an identifier:-
■ Python is case-sensitive. So case matters in naming identifiers. And hence
geeks and Geeks are two different identifiers.
■ Identifiers start with a capital letter (A-Z) , a small letter (az) or an
underscore( _ ).
■ It can’t start with any other character.
■ Except for letters and underscore, digits can also be a part of an identifier but
can’t be the first character of it.
■ Any other special characters or whitespaces are strictly prohibited in an
identifier.
■ An identifier can’t be a keyword.
E
EG
LL
O
C
G
IN
Creating and using variables in Python
R
Variable in Python
● A variable is a named memory location in which we can store values for the
EE
EXAMPLE
E
EG
● Python allows us to assign a value to multiple variables and multiple values to
multiple variables in a single statement which is also known as multiple assignment.
LL
EXAMPLE
O
C
G
IN
R
EE
IN
G
3. Literals (Constants)
EN
● Python literals are a data type and can hold any value type, such as strings, numbers,
and more
● The way of using literals depends on its type.
EA
● The various types of literals used in the Python program are as follows:
■ String literals
■ Numeric literals - integer, float, complex
M
■ Boolean literals
■ Literal Collections - list, tuple, set, dictionary
K
E
EG
LL
O
C
G
IN
A. Numeric datatype
R
● The numeric data type in Python represents the data that has a numeric value.
● A numeric value can be an integer, a floating number, or even a complex
EE
number.
● There are three numeric types in Python:
IN
1. int
2. float
G
3. complex
EN
EA
M
K
EXAMPLE
PROGRAM
num1 = 5
print(num1, 'is of type', type(num1))
num2 = 2.0
E
print(num2, 'is of type', type(num2))
EG
num3 = 1 + 2j
print(num3, 'is of type', type(num3))
LL
OUTPUT
O
2.0 is of type <class 'float'>
C
(1+2j) is of type <class 'complex'>
G
Type Conversion in Python IN
● Python provides Explicit type conversion functions to directly convert one data
type to another. It is also called as Type Casting in Python
R
number.
3. str() : This function is used to convert any data type to a string.
G
EXAMPLE
EN
EA
M
K
Escape sequence
The escape sequence is a sequence of characters treated as special when the Python
interpreter encounters it in the string literal. The escape sequence is represented using the
backslash (‘\’) followed by the character.
E
EG
LL
O
C
G
IN
R
EXAMPLE
EE
IN
G
EN
EA
M
K
■ String
■ List
■ Tuple
a. String:- A string is a collection of one or more characters. Strings are represented by
either single, double or triple quotes.
EXAMPLE
E
EG
LL
O
C
G
IN
R
EE
b. List
List is an ordered sequence of some data written using square brackets([]) and commas(,).
IN
List is mutable (means values in the list can be changed during execution time).
G
EXAMPLE
EN
EA
M
K
c. Tuple
The tuple is another data type which is a sequence of data similar to a list. But it is
immutable. That means data in a tuple is write-protected. Data in a tuple is written using
parentheses and commas.
EXAMPLE
E
EG
LL
O
C
G
C. Dictionary
IN
Dictionary is an ordered sequence of data of key-value pair form. Dictionaries are written
R
within curly braces in the form key:value.
EE
PROGRAM
:"New Delhi"}
print(type(capitals))
G
OUTPUT
EN
<class 'dict'>
D. Set
EA
E. Boolean
Boolean data type that has one of two possible values (usually denoted True and False)
which is intended to represent the two truth values of Boolean algebra.
EXAMPLE
E
EG
LL
O
C
G
IN
R
Python.
● It consists of various mathematical constants and functions that can be used after
EN
import math
● Various functions in math module are:-
M
NUMERIC FUNCTIONS
K
1. math.sqrt()
The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
2. math.ceil()
The ceil() function approximates the given number to the smallest integer,
greater than or equal to the given floating point number.
>>>math.ceil(4.5867)
5
3. math.floor()
E
EG
The floor() function returns the largest integer less than or equal to the given
number.
>>>math.floor(4.5687)
LL
4
O
4. math.fabs()
C
Returns the absolute value of x
>>> math.fabs(-5.5)
G
5.5 IN
5. math.pi()
R
>>>x = math.pi
>>>print(x)
IN
3.14…
G
6. math.factorial()
EN
7. math.gcd()
K
E
9. math.pow()
EG
The math.pow() method receives two float arguments, raises the first to the
second and returns the result. In other words, pow(2,3) is equivalent to 2**3.
LL
>>>math.pow(2,4)
16.0
O
C
10. math.log()
Used to calculate the logarithmic value of a with base b
G
>>>print ("The value of log 2 with base 3 is : ")
IN
>>>print (math.log(2,3))
The value of log 2 with base 3 is : 0.6309297535714574
R
EE
the argument.
PROGRAM
G
import math
EN
a = math.pi/6
print ("The value of sine of pi/6 is : ", end="")
print (math.sin(a))
EA
OUTPUT
Using the Python Standard Library for handling basic I/O - input(),
print()
Python offers us several built-in functions that make it easy to create a program quickly.
Two of the most commonly used built-in functions are the input() and print() functions
that are used for frequent input and output operations, respectively.
E
EG
Python Input
To run an application, programmers often need to obtain input in Python from a user. The
LL
simplest way to do this is to use the input() function. The function pauses program
execution to let the user type a line of information from the keyboard. When the user hits
“Enter”, the input is read and returned as a string.
O
Syntax:-
C
input([<prompt>])
where the prompt is an optional string that we wish to display for the user.
G
IN
R
EXAMPLE
EE
Hello, John
EN
By default, the input() function accepts only string arguments. However, we can convert
this to a number by using the int() of float() functions.
EA
EXAMPLE
M
Or
E
EG
For taking multiple inputs from the user in a single line we use the function split().
EXAMPLE
LL
>>>x,y=input(“Enter two numbers: ”).split()
O
>>>print(“No. of boys: ”, x)
>>>print(“No. of girls: ”, y)
C
Enter two numbers: 23 22
No. of boys: 23
G
No. of girls: 22
IN
Python Output
R
EE
Once a program accepts input in Python and processes the data, it needs to present the data
back to the user as output. You can choose to display the data output to the console directly
IN
or show it on a screen.
We use the print() function to display the output data to the (screen).
G
EN
Syntax:-
print(<obj>,...,<obj>)
EA
Using the above syntax, we can pass several objects (<obj>) in the print() function by
separating them with a comma.
M
EXAMPLE
K
>>>print(100)
100
>>>num = 65
>>>print ('The value of the number is', num)
Another Syntax:-
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
EXAMPLE
E
# Passing sep and end parameters
EG
>>>num = 7
>>>print('James Bond ', num, sep = '--> 00', end = '\n\n\n')
>>>a = 2
LL
>>>print('Value of a: ', a, sep = '000', end = '\n')
>>>print('Car', 'Bike', 'Train', 'Plane', sep = ' | ', end = '\n\n')
O
OUTPUT
C
James Bond --> 007
G
IN
R
Value of a: 0002
EE
In Python, operators are special symbols or keywords that carry out operations on values
and python variables. They serve as a basis for expressions, which are used to modify data
EA
and execute computations. Python contains several operators, each with its unique purpose.
Simple answer can be given using the expression 4 + 5 is equal to 9. Here, 4 and 5 are
M
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
E
EG
LL
O
C
G
IN
1. Python Arithmetic Operators
R
EE
+ Addition 10 + 20 = 30
EA
- Subtraction 20 – 10 = 10
M
* Multiplication 10 * 20 = 200
K
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
a = 21
b = 10
# Addition
E
print ("a + b : ", a + b)
EG
# Subtraction
print ("a - b : ", a - b)
LL
# Multiplication
print ("a * b : ", a * b)
# Division
O
print ("a / b : ", a / b)
C
# Modulus
G
print ("a % b : ", a % b)
# Exponent
IN
print ("a ** b : ", a ** b)
# Floor Division
R
This code defines the two variables "a" and "b." It then applies several arithmetic
IN
Output
EN
a + b : 31
a - b : 11
EA
a * b : 210
a / b : 2.1
a%b:1
M
a ** b : 16679880978201
K
a // b : 2
E
EG
>= Greater than or Equal to 4 >= 5 is not true.
LL
Example of Python Comparison Operators
O
a=4
b=5
C
# Equal
G
print ("a == b : ", a == b)
# Not Equal
IN
print ("a != b : ", a != b)
R
# Greater Than
print ("a > b : ", a > b)
EE
# Less Than
print ("a < b : ", a < b)
IN
This code compares the values of python variables 'a' and 'b' and prints if they are equal,
EA
not equal, greater than, less than, more than or equal to, and less than or equal to each
other.
M
Output
K
a == b : False
a != b : True
a > b : False
a < b : True
a >= b : False
a <= b : True
E
Operator Name Example
EG
= Assignment Operator a = 10
LL
+= Addition Assignment a += 5 (Same as a = a + 5)
O
C
*= Multiplication Assignment a *= 5 (Same as a = a * 5)
G
%= Remainder Assignment
IN a %= 5 (Same as a = a % 5)
# Assignment Operator
G
a = 10
# Addition Assignment
EN
a += 5
print ("a += 5 : ", a)
EA
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
M
# Multiplication Assignment
K
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
print ("a /= 5 : ",a)
# Remainder Assignment
a %= 3
print ("a %= 3 : ", a)
# Exponent Assignment
a **= 2
print ("a **= 2 : ", a)
# Floor Division Assignment
a //= 3
E
print ("a //= 3 : ", a)
EG
The Python assignment operators are shown in this code in the Python Editor. It begins
with the value of 'a' equal to 10, and then goes through the steps of addition, subtraction,
LL
multiplication, division, remainder, exponentiation, and floor division, updating 'a' as
necessary and outputting the results.
O
Output
C
a += 5 : 105
G
a -= 5 : 100 IN
a *= 5 : 500
a /= 5 : 100.0
R
a %= 3 : 1.0
EE
a **= 2 : 1.0
a //= 3 : 0.0
IN
<< Binary Left Shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> Binary Right Shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off
E
EG
Example of Python Bitwise Operators
a = 60 # 60 = 0011 1100
LL
b = 13 # 13 = 0000 1101
# Binary AND
c=a&b # 12 = 0000 1100
O
print ("a & b : ", c)
C
# Binary OR
G
c=a|b # 61 = 0011 1101
print ("a | b : ", c)
IN
# Binary XOR
c=a^b # 49 = 0011 0001
R
this code. It displays the results of binary AND, OR, XOR, Ones Complement, Left Shift,
and Right Shift operations.
K
Output
a & b : 12
a | b : 61
a ^ b : 49
~a : -61
a >> 2 : 240
a >> 2 : 15
● Python logical operators are used to compose Boolean expressions and evaluate
their truth values.
E
● They are required for the creation of conditional statements as well as for managing
the flow of execution in programs.
EG
● Python has three basic logical operators: AND, OR, and NOT.
LL
Operator Description Example
and Logical If both of the operands are true then the condition (a and b) is true.
O
AND becomes true.
C
or Logical OR If any of the two operands is non-zero then the (a or b) is true.
G
condition becomes true. IN
not Logical Used to reverse the logical state of its operand Not(a and b) is
NOT false.
R
EE
The code assigns the values 5 and 10 to variables x and y. It determines whether x is larger
than 3 and y is less than 15. If both conditions are met, it writes "Both x and y are within
the specified range."
EA
Output
M
● Python membership operators are used to determine whether or not a certain value
occurs within a sequence.
● They make it simple to determine the membership of elements in various Python
data structures such as lists, tuples, sets, and strings.
● Python has two primary membership operators: the in and not in operators.
E
not in Evaluates to true if it does not find a x not in y, here not in results in
EG
variable in the specified sequence and a 1 if x is not a member of
false otherwise. sequence y.
LL
Example of Python Membership Operators
fruits = ["apple", "banana", "cherry"]
O
print(“banana” in fruits)
C
The code defines a list of fruits and tests to see if the word "banana" appears in the list. If it
is present, “True” is printed on screen.
G
Output
IN
True
R
EE
● Python identity operators are used to compare two objects' memory addresses rather
IN
side of the operator point to the same object if id(x) equals id(y)
and false otherwise
K
y=5
print(x is y)
The code sets the variables x and y to 10 and 5, respectively. Then check whether the both
values are equal using is operator. If correct, True value will be displayed else false value.
Output
False
E
EG
OPERATOR PRECEDENCE
When an expression or statement involves multiple operators then it will be resolve using
LL
the following operator precedence chart :
O
C
G
IN
R
EE
IN
G
EN
EA
M
denote the order in which the various operators are applied. The final result is
1, which is assigned to R.
E
EG
LL
O
C
G
IN
R
EE
IN
G
EN
EA
M
K