Python Content Manual
Python Content Manual
Recap
Till now we have gone through an experiential learning around Artificial Intelligence in which
we got to know about so many new concepts like what is Artificial Intelligence, Machine
Learning, Deep learning, Rule-based approach, learning based approach, neural networks,
etc. Now, it is time to move ahead in this journey towards AI Readiness and work around the
concepts we are introduced to through hands-on learning sessions.
But before we start getting our hands dirty, let us recall what has been done so far. Here is a
quiz through which you can challenge yourself and see how well do you remember things.
Quiz Time!
1. Which stage is missing in AI Project Cycle?
10
3. What will be the output for this program?
11
7. Google Deep Mind AI is based on reinforcement learning.
12. Problem statement template does not talk about goal of the project?
14. Which of the following is commonly used for image processing in python?
12
15. Box plots help in finding out_______?
16. The AI domain which can be used to predict the Air Quality Index is?
13
What you Know?
Ever wondered how do people create such programs? Write your thoughts below.
14
To develop a program, the very first step that comes into the picture is to specify the
task which the machine needs to do. Once the task or the main objective of the
program is finalized, the task is broken into smaller tasks which altogether contribute
towards achieving the main goal. To make sure that the flow of the process is
proper, algorithms and flowcharts are used which help us into developing a stepwise
framework to achieve the main goal.
What is an Algorithm?
To write a logical step-by-step method to solve the identified problem is called
algorithm, in other words, an algorithm is a procedure for solving problems. In order
to solve a mathematical or computer problem, this is the first step of the procedure.
An algorithm includes calculations, reasoning and data processing. Algorithms can
be presented by natural languages, pseudocode and flowcharts, etc.
Activity
Goal: To give a glimpse of how to write a step by step algorithm for any
problem/process in a bidirectional manner.
15
• Take a pan and boil approx. 200 ml of water.
Step 1
• Stir constantly and cook in the open pan till the water is
Step 3 soaked by the noodles.
• Serve Hot.
Step 4
Can you think of other ways to make instant noodles? Write them down.
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
Challenge Time
Before we jump into challenging ourselves, let us go through some ground rules for
this activity:
16
Write algorithms for the challenges given.
Level
1
Making Tea/Coffee/Hot chocolate
Level
2
Make Chapati/Rice
Level
3
Make Samosa/Masala Dosa
Now, exchange your attempts with your friend and see what procedure have they
followed for the same tasks.
17
Yes! Write the differences below. No! How are they so similar?
Re-look at your own algorithms now. Do you wish to make any changes to it? Is
there a need to add/subtract step(s) in it? Take your time and make the necessary
changes if required.
1. How to divide a task into several sub-tasks and the advantage of doing so.
2. There can be multiple approaches in terms of the number of sub-tasks or the
methods used in sub-tasks to solve a problem and the one which is the
simplest and the most efficient should be chosen above all.
What is a flowchart?
A flowchart is the graphical or pictorial representation of an algorithm with the help of
different symbols, shapes and arrows in order to demonstrate a process or a
program. While computers work with numbers at ease, humans need visual
representations to understand the information well and communicate it effectively.
Thus, flowcharts are used to break a process into smaller parts and elaborate it
using visual representations.
Several standard graphics are applied in a flowchart:
18
Terminal Box Input / Output Process / Decision Connector /
(Start / End) Instruction Arrow
Now that we have the definitions of algorithm and flowchart, how do we use a
flowchart to represent an algorithm? Let us take a look at given examples and see
how they work.
Algorithm:
Step 1: Initialize X as 0,
Step 2: Increment X by 1,
Step 3: Print X,
Step 4: If X is less than 20 then go back to step 2.
Flowchart:
19
Example 2: Convert Temperature from Fahrenheit (℉) to Celsius (℃)
ALGORITHM FLOWCHART
Step 3: Print C
Challenge time!
Let us practice what we have learnt so far. Write algorithms and draw flowcharts for
the tasks given below.
TASK 1: How to check whether the input number is prime or not?
TASK 2: How does a traffic signal work?
TASK 3: How to make an ATM transaction?
TASK 4: How to check if a light bulb is working or not?
TASK 5: How to win a Rock, Paper, Scissors Game – To know more about this game, go to
https://www.wikihow.com/Play-Rock,-Paper,-Scissors
20
Chapter 2: Introduction to Python
In the previous section, you learnt about the different methodologies for programming. A
programming language is a formal language that specifies a set of instructions that can be
used to produce various kinds of output.
In simple Words, a programming language is a vocabulary and set of grammatical rules for
instructing a computer to perform specific tasks. Though there are many different
programming languages such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python, etc.
we will study Python in this course.
What is a program?
A computer program is a collection of instructions that perform a specific task when
executed by a computer. It is usually written by a computer program in a programming
language.
Before getting into understanding more about Python, we need to first understand what is
Python and why we need to use Python?
What is Python?
21
Why Python for AI?
Artificial intelligence is the trending technology of the future. You can see so many
applications around you. If you as an individual can also develop an AI application, you will
require to know a programming language. There are various programming languages like
Lisp, Prolog, C++, Java and Python, which can be used for developing applications of AI.
Out of these, Python gains a maximum popularity because of the following reasons:
Applications of Python
Python is used for a large number of applications. Some of them are mentioned below:
22
Web and
Internet
Developme
nt
Desktop Business
GUI Applications
Applications
Application of
Python
Database
Access
To write and run Python program, we need to have Python interpreter installed in our
computer.
23
Run in the Integrated Development Environment (IDE)
When we install Python, an IDE named IDLE is also installed. We can use it to run Python
on our computer.
IDLE (GUI integrated) is the standard, most popular Python development environment. IDLE
is an acronym of Integrated Development Environment. It lets one edit, run, browse and
debug Python Programs from a single interface. This environment makes it easy to write
programs.
Python shell can be used in two ways, viz., interactive mode and script mode. Where
Interactive Mode, as the name suggests, allows us to interact with OS; script mode lets us
create and edit Python source file.
Interactive Mode
You can see the above example, Python IDLE Shell account has >>> as Python prompt,
where simple mathematical expressions and single line Python commands can be written
and can be executed simply by pressing enter.
The first expression 3+10 written on the first Python prompt shows 13 as output in the next
line.
The second expression 2+4*10 written on the second Python prompt shows 42 as output in
the next line.
The third statement print("Hello Learner") written on the third Python prompt shows Hello
Learner as output in the next line.
The third statement print("Result:", 40+5*100) written on the fourth Python prompt shows
Result: as output in the next line.
29
Try Yourself
Script Mode
In script mode, we type Python program in a file and then use the interpreter to execute the
content from the file. Working in interactive mode is convenient for beginners and for testing
small pieces of code, as we can test them immediately. But for coding more than few lines,
we should always save our code so that we may modify and reuse the code.
Note: Result produced by Interpreter in both the modes, viz., Interactive and script mode is
exactly the same.
In shell Mode,
Click File >> New File
To write a Python script/program, we need to open a new file - File >> New File, type a
sequence of Python statements for solving a problem, save it with a meaningful name - File
>> Save, and finally Run the program to view the output of the program.
30
Now, type your first Python Program
Code Explanation:
Line 1 in the above code starting with # is a comment line, which means the line is non-
executable and it is only for the programmer’s reference.
Hello
Line 4 will display Learner and will allow the next output to get displayed in the same line
Hello
Learner Sam
50 times 300 is 15000
31
Python Statement and Comments
In this section we will learn about Python statements, why indentation is important and how
to use comments in programming.
Python Statement
Instructions written in the source code for execution are called statements. There are
different types of statements in the Python programming language like Assignment
statement, Conditional statement, Looping statements etc. These help the user to get the
required output. For example, n = 50 is an assignment statement.
Multi-line statement
However, Statements in Python can be extended to one or more lines using parentheses (),
braces {}, square brackets [], semi-colon (;), continuation character slash (\). When we need
to do long calculations and cannot fit these statements into one line, we can make use of
these characters.
Examples:
Type of Multi-line Usage
Statement
Using Continuation s = 1 + 2 + 3 + \
Character (/) 4 + 5 + 6 + \
7 + 8 + 9
Using Parentheses () n = (1 * 2 * 3 + 4 – 5)
Python Comments
A comment is text that doesn't affect the outcome of a code, it is just a piece of text to let
someone know what you have done in a program or what is being done in a block of code.
32
Python Keywords and Identifiers
In this section, we will learn about keywords (reserved words in Python) and identifiers
(names given to variables, functions, etc.).
Keywords
33
The list of all the keywords is given below.
34
Note:
Python is a case-sensitive language. This means, Variable and variable are not the same.
Always name identifiers that make sense.
While, c = 10 is valid. Writing count = 10 would make more sense and it would be easier to
figure out what it does even when you look at your code after a long gap.
x = 42
y = 42
35
These declarations make sure that the program reserves memory for two variables with the
names x and y. The variable names stand for the memory location. It's like the two
shoeboxes, which you can see in the picture. These shoeboxes are labelled with x and y and
the corresponding values are stored in the shoeboxes. Like the two shoeboxes, the memory
is empty as well at the beginning.
Note:
Assignment operator is used in Python to assign values to variables. For example, a = 5 is a simple
assignment operator that assigns the value 5 on the right to the variable a on the left.
Examples on Variables:
36
print(c)
Constants:
Non technically, you can think of constant as a shoe box with a fixed size of shoe kept inside
which cannot be changed after that.
In Python, constants are usually declared and assigned on a module. Here, the module
means a new file containing variables, functions etc. which is imported to the main file.
Inside the module, constants are written in all capital letters and underscores separating the
words.
• Create a info.py
NAME = "Ajay"
AGE = 24
• Create a main.py
import info
print(info.NAME)
print(info.AGE)
Ajay
24
37
In the above program, we create a constant.py module file. Then, we assign the constant
value to PI and GRAVITY. After that, we create a main.py file and import the constant
module. Finally, we print the constant value.
Note: In reality, we don't use constants in Python. The global or constants module is used
throughout the Python programs.
Use camelCase
Create a name that Use capital letters
notation to declare a
makes sense. where possible to
variable. It starts with
Suppose, vowel makes declare a constant. For
lowercase letter. For
more sense than v. example: PI
example: myName
Datatypes
Every value in Python has a datatype. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.
There are various data types in Python. Some of the important types are mentioned below in
the image
38
1) Python Numbers
Number data type stores Numerical Values. These are of three different types:
Integers are the whole numbers consisting of + or – sign with decimal digits like 100000, -99,
0, 17. While writing a large integer value, don’t use commas to separate digits. Also, integers
should not have leading zeros.
Floating Point:
Numbers with fractions or decimal point are called floating point numbers.
A floating-point number will consist of sign (+,-) sequence of decimals digits and a dot such
as 0.0, -21.9, 0.98333328, 15.2963. These numbers can also be used to represent a
number in engineering/ scientific notation.
2) None
This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None.
3) Sequence
a) Strings
b) Lists
c) Tuples
String
Lists
List is also a sequence of values of any type. Values in the list are called elements / items.
These are indexed/ordered. List is enclosed in square brackets.
Example:
39
dob = [19,"January",1990]
Tuples:
Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable. Tuples are enclosed in ().
Example:
t = (5,'program',2.5)
4) Sets
Example:
>>> a = {1,2,2,3,3,3}
>>> a
{1,2,3}
5) Mapping
Dictionaries
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key: value. Key and value can be of any type.
Example
>>> d = {1:'Ajay','key':2}
>>> type(d)
<class 'dict'>
40
Python Operators I
Operators are special symbols which represent computation. They are applied on
operand(s), which can be values or variables. Same operators can behave differently on
different data types. Operators when applied on operands form an expression. Operators are
categorized as Arithmetic, Relational, Logical and Assignment. Value and variables when
used with operator are known as operands.
Arithmetic Operators
a = "Hello World!"
print(a)
Hello World!
print(15 + 35) 50
x = 1.3 x =
print("x = /n", x) 1.3
m = 6 I have 6 apples
print(" I have %d apples",m)
User input
In all the examples till now, we have been using the calculations on known values
(constants). Now let us learn to take user’s input in the program. In python, input() function is
used for the same purpose.
Syntax Meaning
<String Variable>=input(<String>) For string input
<integer Variable>=int(input(<String>)) For integer input
<float Variable>=float(input(<String>)) For float (Real no.) input
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion. Python has two types of type conversion.
42
Example:
principle_amount = 2000
roi = 4.5
time = 10
43
Example Sample Output Explanation
Code
a = 10 File "cbse2.py", line 3, in The output shows an
b = "Hello" <module> error which says that
print(a+b) print(a+b) we cannot add integer
TypeError: unsupported and string variable
operand type(s) for +: types using implicit
'int' and 'str' conversion
Try It Yourself:
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.
This type of conversion is also called typecasting because the user casts (changes) the data
type of the objects.
44
Syntax:
(required_datatype)(expression)
Typecasting can be done by assigning the required data type function to the expression.
Example: Adding of string and an integer using explicit conversion
Birth_day = 10
Birth_month = "July"
Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))
In above program,
45
Example Code Sample Output Explanation
a = 20 20 Apples Writing str(a) will
b = "Apples" convert integer a
print(str(a)+ b) into a string and
then will add to
the string b.
Try it yourself:
1) Take a Boolean value “False” and a float number “15.6” and perform the AND
operation on both
2) Take a string “ Zero” and a Boolean value “ True” and try adding both by using the
Bool() function.
3) Take a string “Morning “ and the float value “90.4” and try and add both of them by
using the float() function.
Perform the above mentioned Try it Yourself in the lab and write down the observations to
be discussed later in the class.
Note:
There is no difference in single or double quoted string. Both representations can be used
interchangeably. However, if either single or double quote is a part of the string itself, then
the string must be placed in double or single quotes respectively.
46
Python Operators II
Comparison operators
Operator Meaning Expression Result
> Greater Than 20 > 10 True
15 > 25 False
< Less Than 20 < 45 True
20 < 10 False
== Equal To 5 == 5 True
5 == 6 False
!= Not Equal to 67 != 45 True
35 != 35 False
Comparison operators are used to compare values. It either returns True or False according
to the condition.
Logical operators
Operator Meaning Expression Result
And And operator True and True True
True and False False
Or Or operator True or False True
False or False False
Not Not Operator not False True
not True False
47
Assignment operators
Let’s Practice
INPUT
L=int(input("Length"))
B=int(input("Breadth"))
PROCESS
Area=L*B
Perimeter=2*(L+B)
OUTPUT
print("Area:",Area)
print("Perimeter:",Perimeter
)
Python Code Sample Output
# To calculate Area and Length:50
# Perimeter of a rectangle Breadth:20
L=int(input("Length")) Area:100
B=int(input("Breadth")) Perimeter:140
Area=L*B
Perimeter=2*(L+B)
print("Area:",Area)
print("Perimeter:",Perimeter)
48
Try writing your code Sample Output
# To calculate Area of a triangle Base:20
# with Base and Height Height:10
_________________ #Input Base Area:100
_________________ #Input Height
_________________ #Calculate Area
_________________ #Display Area
49