0% found this document useful (0 votes)
56 views

Python Content Manual

Uploaded by

Aarav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Python Content Manual

Uploaded by

Aarav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

Chapter 1: Algorithms and Flowcharts

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?

2. Which one of the following is not an SDG?

10
3. What will be the output for this program?

4. Large Neural Networks are time consuming and computationally expensive.

5. Which one of the following is not an AI application?

6. What is this flowchart for?

11
7. Google Deep Mind AI is based on reinforcement learning.

8. Wikipedia can be an appropriate Data Source for which domain?

9. What is the correct step to reach finish from first?

10. Pixel It is an example of machine learning AI approach.

11. AI can be implemented in which of the following field?

12. Problem statement template does not talk about goal of the project?

13. Snapchat is an example of Natural Language Processing domain?

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?

17. Where is decision tree used?

18. Which process is depicted by these steps?

19. Which of the following is used to plot graphs in python?

20. How was the overall experience of the workshop?

How well did you score in the quiz? _____________________


Analyze your thoughts here:

13
What you Know?

What you Want to Know?

What have you Learned?

How have your Learned?


Introduction
Every machine, whether AI enabled or not, follows a particular path of action. It goes through
exact specific steps which have been programmed into it to accomplish the given task. For
example, a washing machine can wash clothes for us and not do anything else
because it is designed explicitly for this task. It follows the steps programmed into it
and completes the work.
Can you think of possible steps to wash clothes in a washing machine?
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________
___________________________________________________________________

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.

To understand algorithms better, let us take an example of the process of making


instant noodles.

Basic steps to make any instant noodles are:

15
• Take a pan and boil approx. 200 ml of water.
Step 1

• Add noodles and tastemaker to the boiling water.


Step 2

• 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.

Did you notice any difference?

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.

Conclusion: Through this activity, we understood:

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

The graphics above represent different parts of a flowchart. The process in a


flowchart can be expressed through boxes and arrows with different sizes and
colors. In a flowchart, we can easily highlight a certain element and the relationships
between each part. Let us take a look as to how can we use flowcharts to represent
algorithms.

How to Use Flowcharts to Represent Algorithms

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.

Example 1: Print 1 to 20:

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 1: Read temperature in


Fahrenheit

Step 2: Calculate temperature with


formula C=5/9*(F-32)

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

Test Your Knowledge


Q1) What is an algorithm?
Q2) What is a flowchart?
Q3) List down all the standard graphics for making a flowchart.

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

Software Games and


Developme 3D
nt Graphics

Database
Access

Getting started with Python


Python is a cross-platform programming language, meaning, it runs on multiple platforms
like Windows, MacOS, Linux and has even been ported to the Java and .NET virtual
machines.

To write and run Python program, we need to have Python interpreter installed in our
computer.

Downloading and Setting up Python for use

• Download Python from python.org using link python.org/downloads


• Select appropriate download link as per Operating System [Windows 32
Bit/64 Bit, Apple iOS]
• FOR EXAMPLE, for Windows 64 Bit OS
• Select the following link

Python IDLE installation

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

1. Find the result of (75+85+65)/3 i.e. the average of three marks


2. Find the result of 22/7 * 5 * 5 i.e. the area of circle having radius as 5
3. Find the result of "RAVI"+"Kant"
4. Find the result of "###" * 3

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.

Python Script/Program: Python statements written in a


particular sequence to solve a problem is known as Python
Script/Program.

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.

Line 2 will simply display

Hello

Line 3 will assign a string value "Sam" to a variable Name

Line 4 will display Learner and will allow the next output to get displayed in the same line

Line 5 will display Sam in the same line as Learner

Line 6 will assign an integer 50 to a variable A

Line 7 will assign an integer 300 to a variable B

Line 8 will display 50 times 300 is 15000

So, the complete output of the Python Code will be

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

In Python, end of a statement is marked by a newline character.

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)

Using Square Brackets [] footballer = ['MESSI',


'NEYMAR',
'SUAREZ']
Using braces {} x = {1 + 2 + 3 + 4 + 5 + 6 +
7 + 8 + 9}

Using Semicolons ( ; ) flag = 2; ropes = 3; pole = 4

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.

In Python, we use the hash (#) symbol to start writing a comment.

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

Keywords are the reserved words in Python used by Python interpreter to


recognize the structure of the program.

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.

Multiple words can be separated using an underscore, for example this_is_a_long_variable

Variables and Datatypes


Variables
A variable is a named location used to store data in the memory. It is helpful to think
of variables as a container that holds data which can be changed later throughout
programming. For example,

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:

Task Sample Code Output

Assigning a value to a Website = "xyz.com" xyz.com


variable print(Website)

Changing value of a Website = "xyz.com" xyz.com


variable print(Website) abc.com
Website = "abc.com"
print(Website)
Assigning different values a,b,c=5, 3.2, 5
to different variables "Hello" 3.2
print(a) Hello
print(b)

36
print(c)

Assigning same value to x=y=z= "Same" Same


different variable print(x) Same
print(y) Same
print(z)

Constants:

A constant is a type of variable whose value cannot be changed. It is helpful to think of


constants as containers that hold information which cannot be changed later.

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.

Assigning Value to a constant in Python

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.

Example : Declaring and assigning value to a constant

• Create a info.py

NAME = "Ajay"
AGE = 24

• Create a main.py

import info

print(info.NAME)
print(info.AGE)

• When you run the program the output will be,

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.

Rules and Naming convention for variables and constants

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

Constant and variable


names should have
Never use special
combination of letters
symbols like !, @, #, $,
in lowercase or
%, etc.
uppercase or digits or
an underscore (_).

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:

a) Integer & Long


b) Float / floating point

Integer & Long Integer

Range of an integer in Python can be from -2147483648 to 2147483647, and long


integer has unlimited range subject to available memory.

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.0 x 105 will be represented as -2.0e5


2.0X10-5 will be 2.0E-5

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 sequence is an ordered collection of items, indexed by positive integers. It is a


combination of mutable and non-mutable data types. Three types of sequence data
type available in Python are:

a) Strings
b) Lists
c) Tuples

String

String is an ordered sequence of letters/characters. They are enclosed in single quotes


(‘ ‘) or double (“ “). The quotes are not part of string. They only tell the computer where the
string constant begins and ends. They can have any character or sign, including space in
them.

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

Set is an unordered collection of values, of any type, with no duplicate entry.

Example:

>>> a = {1,2,2,3,3,3}
>>> a
{1,2,3}

5) Mapping

This data type is unordered. Dictionaries fall under Mappings.

Dictionaries

Dictionary is an unordered collection of key-value pairs. It is generally used when we have a


huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to
retrieve the value.

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

Operator Meaning Expression Result


+ Addition 10 + 20 30
- Subtraction 30 - 10 20
* Multiplication 30 * 100 300
/ Division 30 / 10 20.0
1 / 2 0.5
// Integer Division 25 // 10 2
1 // 2 0
% Remainder 25 % 10 5
** Raised to power 3 ** 2 9

Python Input and Output

INPUT PROCESS OUTPUT


Name Age Is Age of Amar
“Amar can goto School”
"Amar" 5 greater than 4?

Python Output Using print() function


We use the print() function to output data to the standard output device (screen).
We can also output data to a file. An example is given below.

a = "Hello World!"
print(a)

The output of the above code will be:

Hello World!

Example Code Sample Output


41
a = 20 30
b = 10
print(a + b)

print(15 + 35) 50

print("My name is Kabir") My name is Kabir

a = "tarun" My name is : tarun


print("My name is :",a)

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.

1. Implicit Type Conversion


2. Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion, Python automatically converts one data type to another data
type. This process doesn't need any user involvement.

42
Example:

# Code to calculate the Simple Interest

principle_amount = 2000
roi = 4.5
time = 10

simple_interest = (principle_amount * roi * time)/100

print("datatype of principle amount : ", type(principle_amount))


print("datatype of rate of interest : ", type(roi))

print("value of simple interest : ", simple_interest)


print("datatype of simple interest : ", type(simple_interest))

When we run the above program, the output will be

datatype of principle amount : <class 'int'>


datatype of rate of interest : <class 'float'>

value of simple interest : 900


datatype of simple interest : <class 'float'>

In the above program,


• We calculate the simple interest by using the variable priniciple_amount and roi with
time divide by 100
• We will look at the data type of all the objects respectively.
• In the output we can see the datatype of principle_amount is an integer, datatype
of roi is a float.
• Also, we can see the simple_interest has float data type because Python always
converts smaller data type to larger data type to avoid the loss of data.

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

c = 'Ram' RamRamRam The output shows that


N = 3 the string is printed
print(c*N) 3 times when we use a
multiply operator with
a string.
x = True 11 The output shows that
y = 10 the boolean value x
print(x + 10) will be converted to
integer and as it is
true will be
considered as 1 and
then give the output.
m = False 23 The output shows that
n = 23 the boolean value m
print(n – m) will be converted to
integer and as it is
false will be
considered as 0 and
then give the output.

Try It Yourself:

1) Take a Boolean value and add a string to it


2) Take a string and float number and try adding both
3) Take a Boolean and a float number and try adding both.

Explicit Type Conversion

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"

print("data type of Birth_day before type casting :", type(Birth_day))


print("data type of Birth_month : ", type(Birth_month))

Birth_day = str(Birth_day)
print("data type of Birth_day after type casting :",type(Birth_day))

Birth_date = Birth_day + Birth_month

print("birth date of the student : ", Birth_day)


print("data type of Birth_date : ", type(Birth_date))

When we run the above program, the output will be

data type of Birth_day before type casting : <class 'int'>


data type of Birth_month : <class 'str'>

data type of Birth_day after type casting : <class 'str'>

birth date of the student : ' 10 July '


data type of Birth_date : <class 'str'>

In above program,

• We add Birth_day and Birth_month variable.


• We converted Birth_day from integer(lower) to string(higher) type using str() function
to perform the addition.
• We got the Birth_date value and data type to be string.

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.

x = 20.3 30 Writing int(x) will


y = 10 convert a float
print(int(x) + y) number to integer
by just considering
the integer part of
the number and then
perform the
operation.
m = False 1 Writing Bool() will
n = 5 convert the integer
print(Bool(n)+ m) value to Boolean.
If it is zero then
it is converted to
False, else to True
for all other
cases.

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

>= Greater than or 45 >= 45 True


Equal to
23 >= 34 False

<= Less than or equal 13 <= 24 True


to
13 <= 12 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

Logical operators are the and, or, not operators.

47
Assignment operators

Assignment operators are used in Python to assign values to variables.

Operator Expression Equivalent to


= X=5 X = 5
+= X +=5 X = X + 5
-= X -= 5 X = X – 5
*= X *= 5 X = X * 5
/= X /= 5 X = X / 5

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

# To calculating average marks English:80


# of 3 subjects Maths :75
_________________ #Input English Marks Science:85
_________________ #Input Maths Marks Total Marks : 240
_________________ #Input Science Marks Average Marks: 80.0
_________________ #Calculate Total Marks
_________________ #Calculate Average Marks
_________________ #Display Total Marks
_________________ #Display Average Marks

# To calculate discounted amount Amount: 5000


# with discount % Discount%:10
_________________ #Input Amount Discount:500
_________________ #Input Discount% Discounted Amt:4500
_________________ #Calculate Discount
_________________ #Calculate Discounted
Amount
_________________ #Display Discount
_________________ #Display Discounted Amount

# To calculate Surface Area and Volume Length:20


# of a Cuboid Breadth:10
_________________ #Input Length Height:15
_________________ #Input Breadth Surface Area:1300
_________________ #Input Height Volume:3000
_________________ #Calculate Surface Area
_________________ #Calculate Volume
_________________ #Display Surface Area
_________________ #Display Volume

Test Your Knowledge


Q1) What are the key features of python ? Mention various applications along with it
Q2) What are the different modes for coding in python?
Q3) What are comments in python ? List down the various types of comments.
Q4) What are the different properties of an identifier ?
Q5) What are the rules for naming of variables and constants
Q6) Explain python input and output with the help of an example.
Q7) What is type conversion ? Explain the types of type conversion with the help of an
example.
Q8) What is a variable? Give example.

49

You might also like