0% found this document useful (0 votes)
39 views20 pages

PYTHON

Uploaded by

jhony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views20 pages

PYTHON

Uploaded by

jhony
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Step 3 − Compare with all elements in the Step 5 − Insert the value

sorted sub-list
Step 6 − Repeat until list is sorted
Step 4 − Shift all the elements in the sorted
sub-list that is greater than the value to be
sorted

Assume 44 is a sorted
44 16 83 07 67 21 34 45 10
list of 1 item
16 44 83 07 67 21 34 45 10 inserted 16
16 44 83 07 67 21 34 45 10 inserted 83
07 16 44 83 67 21 34 45 10 inserted 07
07 16 44 67 83 21 34 45 10 inserted 67
07 16 21 44 67 83 34 45 10 inserted 21
07 16 21 34 44 67 83 45 10 inserted 34
07 16 21 34 44 45 67 83 10 inserted 45
07 10 16 21 34 44 45 67 83 inserted 10

At the end of the pass the insertion algorithm will try to check the results of
sort algorithm gives the sorted output in the previously solved sub-problems. The
ascending order as shown below: solutions of overlapped sub-problems are
combined in order to get the better solution.
07 10 16 21 34 44 45 67 83
Steps to do Dynamic programming
4.6. Dynamic programming
• The given problem will be divided into
smaller overlapping sub-problems.
Dynamic programming is an
algorithmic design method that can be • An optimum solution for the given
used when the solution to a problem can problem can be achieved by using result
be viewed as the result of a sequence of of smaller sub-problem.
decisions. Dynamic programming approach
• Dynamic algorithms uses Memoization.
is similar to divide and conquer. The given
problem is divided into smaller and yet
smaller possible sub-problems. Note
Memoization or memoisation
Dynamic programming is used
is an optimization technique used
whenever problems can be divided into
primarily to speed up computer
similar sub-problems. so that their results
programs by storing the results of
can be re-used to complete the process.
previous function calls and returning
Dynamic programming approaches are
the cached result when the same inputs
used to find the solution in optimized way.
occur again.
For every inner sub problem, dynamic

41 Algorithmic Strategies

12th Computer Science_EM Chapter 4.indd 41 21-12-2022 15:55:01


4.6.1 Fibonacci Series – An example Initialize f0=0, f1 =1
Fibonacci series generates the
step-1: Print the initial values of Fibonacci
subsequent number by adding two previous
f0 and f1
numbers. Fibonacci series starts from two
numbers − Fib 0 & Fib 1. The initial values step-2: Calculate fibanocci fib ← f0 + f1
of Fib 0 & Fib 1 can be taken as 0 and 1.
step-3: Assign f0← f1, f1← fib
Fibonacci series satisfies the following
conditions : step-4: Print the next consecutive value of
fibanocci fib
Fibn = Fibn-1 + Fibn-2
step-5: Goto step-2 and repeat until the
Hence, a Fibonacci series for the n value 8 specified number of terms generated
can look like this
For example if we generate fibobnacci series
Fib8 = 0 1 1 2 3 5 8 13 upto 10 digits, the algorithm will generate
the series as shown below:
4.6.2 Fibonacci Iterative Algorithm with
Dynamic programming approach The Fibonacci series is : 0 1 1 2 3 5 8 13 21
The following example shows a 34 55
simple Dynamic programming approach
for the generation of Fibonacci series.

Points to remember:
• An algorithm is a finite set of instructions to accomplish a particular task.
• Algorithm consists of step-step-by instructions that are required to accomplish a task
and helps the programmer to develop the program.
• Program is an expression of algorithm in a programming language.
• Algorithm analysis deals with the execution or running time of various operations
involved.
• Space complexity of an algorithm is the amount of memory required to run to its
completion.
• Big Oh is often used to describe the worst-case of an algorithm.
• Big Omega is used to describe the lower bound which is best way to solve the space
complexity.
• The Time complexity of an algorithm is given by the number of steps taken by the
algorithm to complete the process.
• The efficiency of an algorithm is defined as the number of computational resources
used by the algorithm.

XII Std Computer Science 42

12th Computer Science_EM Chapter 4.indd 42 21-12-2022 15:55:01


Points to remember:
• A way of designing algorithm is called algorithmic strategy.
• A space-time or time-memory tradeoff is a way of solving a problem or calculation in
less time by using more storage space.
• Asymptotic Notations are languages that uses meaningful statements about time and
space complexity.
• Bubble sort is a simple sorting algorithm. It compares each pair of adjacent items and
swaps them if they are in the unsorted order.
• The selection sort improves on the bubble sort by making only one exchange for every
pass through the list.
• Insertion sort is a simple sorting algorithm that builds the final sorted array or list one
item at a time. It always maintains a sorted sublist in the lower positions of the list.
• Dynamic programming is used when the solutions to a problem can be viewed as the
result of a sequence of decisions.

Evaluation

Part - I

Choose the best answer: (1 Marks)


1. The word comes from the name of a Persian mathematician Abu Ja’far Mohammed ibn-i
Musa al Khowarizmi is called?
(A) Flowchart (B) Flow (C) Algorithm (D) Syntax
2. From the following sorting algorithms which algorithm needs the minimum number of
swaps?
(A) Bubble sort (B) Insertion sort (C) Selection sort (D) All the above
3. Two main measures for the efficiency of an algorithm are
(A) Processor and memory (B) Complexity and capacity
(C) Time and space (D) Data and space
4. The algorithm that yields expected output for a valid input in called as
(A) Algorithmic solution (B) Algorithmic outcomes
(C) Algorithmic problem (D) Algorithmic coding

43 Algorithmic Strategies

12th Computer Science_EM Chapter 4.indd 43 21-12-2022 15:55:01


5. Which of the following is used to describe the worst case of an algorithm?
(A) Big A (B) Big S (C) Big W (D) Big O
6. Big Ω is the reverse of
(A) Big O (B) Big θ (C) Big A (D) Big S
7. Binary search is also called as
(A) Linear search (B) Sequential search
(C) Random search (D) Half-interval search
8. The Θ notation in asymptotic evaluation represents
(A) Base case (B) Average case (C) Worst case (D) NULL case
9. If a problem can be broken into subproblems which are reused several times, the problem
possesses which property?
(A) Overlapping subproblems (B) Optimal substructure
(C) Memoization (D) Greedy
10. In dynamic programming, the technique of storing the previously calculated values is
called ?
(A) Saving value property (B) Storing value property
(C) Memoization (D) Mapping

Part - II

Answer the following questions (2 Marks)

1. What is an Algorithm?
2. Write the phases of performance evaluation of an algorithm.
3. What is Insertion sort?
4. What is Sorting?
5. What is searching? Write its types.

Part - III

Answer the following questions (3 Marks)


1. List the characteristics of an algorithm.
2. Discuss about Algorithmic complexity and its types.

XII Std Computer Science 44

12th Computer Science_EM Chapter 4.indd 44 21-12-2022 15:55:01


3. What are the factors that influence time and space complexity.
4. Write a note on Asymptotic notation.
5. What do you understand by Dynamic programming?

Part - IV

Answer the following questions (5 Marks)


1. Explain the characteristics of an algorithm.
2. Discuss about Linear search algorithm.
3. What is Binary search? Discuss with example.
4. Explain the Bubble sort algorithm with example.
5. Explain the concept of Dynamic programming with suitable example.

Reference Books

1. Fundamentals Computer Algorithms, Ellis Horowitz, Sartaj Sahni, Sanguthevar,


Rajasekaran, Second Edition, University press (India) Limited, 2013.
2. Design and Analysis of Algorithms, S. Sridhar, Oxford University Press, 2015

Web References

www.wickipedia.org

CASE STUDY/ STUDENT’S ACTIVITY

1. Create an algorithm for grading systems of your class student’s Quarterly examination
marks by satisfying all necessary conditions.

45 Algorithmic Strategies

12th Computer Science_EM Chapter 4.indd 45 21-12-2022 15:55:01


Why Python in standard XII curriculum?

This is the question that is fretting The above statistical data has
the minds of teachers and students. maintained its grip with Python scoring
The present book is organized in 100 and C++ language stands second
such a way that even a novice reader can nipping at its heels with a 99.7 score.
grasp and work on python programming. Python being popular is used by a number
Testimonies of tech giants like Google, Instagram,
Pinterest, Yahoo, Disney, IBM, Nokia etc.
• "Python has been an important part
1. Python 100.0
of Google since the beginning and
2. C++ 99.7
remains so as the system grows and 3. Java 97.5
evolves. Today dozens of Google 4. C 96.7
engineers use Python, and we're 5. C# 89.4
looking for more people with skills 6. PHP 84.9
in this language." -- Peter Norvig, 7. R 82.8
director of search quality at Google, 8. JavaScript 82.6
Inc. 9. Go 76.4
10. Assembly 74.1
• "Python is fast enough for our
site and allows us to produce Many businesses are advised to choose
maintainable features in record times, Python for the following reasons:-
with a minimum of developers," • Easy syntax and readability
-- Cuong Do, Software Architect, • High level scripting language with
YouTube.com oops
• famous for enormous functions, add-
Python’s popularity has seen on modules, libraries, frameworks and
a steady and unflagging growth over tool-kits.
the recent years. Today, familiarity • Built-in functions supports scientific
with Python is an advantage for every computing.
programmer, as Python has infiltrated With the advent of computers,
every niche and has useful roles to play in there have been significant changes in the
any software solution. way we work in almost all the fields. The
Python has experienced an computerization has helped to improve
productivity and accelerate decision
impressive growth as compared to the
making in every organization. Even for
other languages. The IEEE Spectrum individuals, be it engineers, doctors,
magazine published by the Institute chartered accountants or homemakers, the
of Electrical & Electronics Engineers, style of working has changed drastically.
New York, ranks Python as the top language So as we go, let us accept the change and
for 2018, for the second consecutive year. move towards a brighter day ahead.

12th Std - CS EM Python Interleaf Page.indd 46 22-12-2022 11:18:11


CHAPTER 5
Unit II
PYTHON – VARIABLES AND OPERATORS

Learning Objectives

After studying this lesson, students will be able to:


• Appreciate the use of Graphical User Interface (GUI) and Integrated Development
Environment (IDE) for creating Python programs.
• Work in Interactive & Script mode for programming.
• Create and assign values to variables.
• Understand the concept and usage of different data types in Python.
• Appreciate the importance and usage of different types of operators (Arithmetic, Relational
and Logical)
• Creating Python expression (s) and statement (s).

5.1 Introduction

Python is a general purpose


programming language created by Guido
Van Rossum from CWI (Centrum Wiskunde
& Informatica) which is a National Research
Institute for Mathematics and Computer
Science in Netherlands. The language was
released in I991. Python got its name from a
BBC comedy series from seventies- “Monty
Python’s Flying Circus”. Python supports both
Procedural and Object Oriented programming
approaches.

5.2 Key features of Python


99 It is a general purpose programming language which can be used for both scientific
and non-scientific programming.
99 It is a platform independent programming language.
99 The programs written in Python are easily readable and understandable.

47

12th Computer Science_EM Chapter 5.indd 47 26-12-2022 17:27:28


The version 3.x of Python IDLE (Integrated Development Learning Environment)
is used to develop and run Python code. It can be downloaded from the web resource
www.python.org.

5.3 Programming in Python


In Python, programs can be written in two ways namely Interactive mode and Script
mode. The Interactive mode allows us to write codes in Python command prompt (>>>)
whereas in script mode programs can be written and stored as separate file with the extension
.py and executed. Script mode is used to create and edit python source file.

5.3.1 Interactive mode Programming


In interactive mode Python code can be directly typed and the interpreter displays the
result(s) immediately. The interactive mode can also be used as a simple calculator.

(i) Invoking Python IDLE


The following command can be used to invoke Python IDLE from Window OS.

Start → All Programs → Python 3.x → IDLE (Python 3.x)

(Or)

Click python Icon on the Desktop if available.

Now Python IDLE window appears as shown in the Figure 5.1


Menu Bar Tilte Bar

Python prompt (>>>)

Python IDLE Window


The prompt (>>>) indicates that Interpreter is ready to accept instructions. Therefore,
the prompt on screen means IDLE is working in interactive mode. Now let us try as a simple
calculator by using a simple mathematical expressions.

XII Std Computer Science 48

12th Computer Science_EM Chapter 5.indd 48 26-12-2022 17:27:28


Example 1: Example 2:
>>> 5 + 10 >>>print (“Python Programming Language”)
15 Python Programming Language
>>>x=10
>>> 5 + 50 *10
>>>y=20
505 >>>z=x + y
>>> 5 ** 2 >>>print (“The Sum”, z)
25 The Sum = 30

Python Interactive Window

5.3.2 Script mode Programming


Basically, a script is a text file containing the Python statements. Python Scripts are
reusable code. Once the script is created, it can be executed again and again without retyping.
The Scripts are editable.

(i) Creating Scripts in Python


1. Choose File → New File or press Ctrl + N in Python shell window.

49 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 49 26-12-2022 17:27:28


Figure 5.3 – To create new File
2. An untitled blank script text editor will be displayed on screen as shown in Figure 5.3(a)

Figure 5.3(a) Untitled, blank Python script editor


3. Type the following code in Script editor
a =100

b = 350 a = 100
b = 350
c = a+b
c = a+b
print ("The Sum=", c) print ("The Sum=", c)

Figure 5.4 – Python Sample code

XII Std Computer Science 50

12th Computer Science_EM Chapter 5.indd 50 26-12-2022 17:27:28


(ii) Saving Python Script
(1) Choose File → Save or Press Ctrl + S

Figure 5.5 – To Save the file First time


(2) Now, Save As dialog box appears on the screen as shown in the Figure 5.6
File Location

File Name (demo1)

File Type (Python file (.py))

Figure 5.6 – Save As Dialog Box

51 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 51 26-12-2022 17:27:28


(3) In the Save As dialog box, select the location where you want to save your Python code,
and type the file name in File Name box. Python files are by default saved with extension
.py. Thus, while creating Python scripts using Python Script editor, no need to specify
the file extension.
(4) Finally, click Save button to save your Python script.
(iii) Executing Python Script
(1) Choose Run → Run Module or Press F5

a=100
b=350
c=a+b
print ("The Sum=", c)

Figure 5.7 – To Execute Python Script

(2) If your code has any error, it will be shown in red color in the IDLE window, and Python
describes the type of error occurred. To correct the errors, go back to Script editor, make
corrections, save the file using Ctrl + S or File → Save and execute it again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in
Figure 5.8

Output

Figure 5.8 –Python Script Output Window

XII Std Computer Science 52

12th Computer Science_EM Chapter 5.indd 52 26-12-2022 17:27:28


5.4 Input and Output Functions

A program needs to interact with the user to accomplish the desired task; this can be
achieved using Input-Output functions. The input() function helps to enter data at run time
by the user and the output function print() is used to display the result of the program on the
screen after execution.
5.4.1 The print() function
In Python, the print() function is used to display result on the screen. The syntax for
print() is as follows:
Example
print (“string to be displayed as output ” )
print (variable )
print (“String to be displayed as output ”, variable)
print (“String1 ”, variable, “String 2”, variable, “String 3” ……)

Example
>>> print (“Welcome to Python Programming”)
Welcome to Python Programming
>>> x = 5
>>> y = 6
>>> z = x + y
>>> print (z)
11
>>> print (“The sum = ”, z)
The sum = 11
>>> print (“The sum of ”, x, “ and ”, y, “ is ”, z)
The sum of 5 and 6 is 11

The print ( ) evaluates the expression before printing it on the monitor. The print
() displays an entire statement which is specified within print ( ). Comma ( , ) is used as a
separator in print ( ) to print more than one item.

5.4.2 input() function


In Python, input( ) function is used to accept data as input at run time. The syntax for
input() function is,

Variable = input (“prompt string”)

53 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 53 26-12-2022 17:27:28


Where, prompt string in the syntax is a statement or message to the user, to know what
input can be given.
If a prompt string is used, it is displayed on the monitor; the user can provide expected
data from the input device. The input( ) takes whatever is typed from the keyboard and stores
the entered data in the given variable. If prompt string is not given in input( ) no message is
displayed on the screen, thus, the user will not know what is to be typed as input.

Example 1:input( ) with prompt string

>>> city=input (“Enter Your City: ”)


Enter Your City: Madurai
>>> print (“I am from “, city)
I am from Madurai

Example 2:input( ) without prompt string

>>> city=input()
Rajarajan
>>> print (“I am from”, city)
I am from Rajarajan

Note that in example-2, the input( ) is not having any prompt string, thus the user will
not know what is to be typed as input. If the user inputs irrelevant data as given in the above
example, then the output will be unexpected. So, to make your program more interactive,
provide prompt string with input( ).

The input ( ) accepts all data as string but not as numbers. If a numerical value is
entered, the input values should be explicitly converted into numeric data type. The int( )
function is used to convert string data as integer data explicitly. We will learn about more such
functions in later chapters.
Example 3:
x = int (input(“Enter Number 1: ”))
y = int (input(“Enter Number 2: ”))
print (“The sum = ”, x+y)
Output:
Enter Number 1: 34
Enter Number 2: 56
The sum = 90

XII Std Computer Science 54

12th Computer Science_EM Chapter 5.indd 54 26-12-2022 17:27:28


Example 4: Alternate method for the above program
x,y=int (input("Enter Number 1 :")),int(input("Enter Number 2:"))
print ("X = ",x," Y = ",y)
Output:
Enter Number 1 :30
Enter Number 2:50
X = 30 Y = 50

5.5 Comments in Python


In Python, comments begin with hash symbol (#). The lines that begins with # are
considered as comments and ignored by the Python interpreter. Comments may be single
line or no multi-lines. The multiline comments should be enclosed within a set of ''' '''(triple
quotes) as given below.
# It is Single line Comment
''' It is multiline comment
which contains more than one line '''

5.6 Indentation
Python uses whitespace such as spaces and tabs to define program blocks whereas
other languages like C, C++, java use curly braces { } to indicate blocks of codes for class,
functions or body of the loops and block of selection command. The number of whitespaces
(spaces and tabs) in the indentation is not fixed, but all statements within the block must be
indented with same amount spaces.

5.7 Tokens
Python breaks each logical line into a sequence of elementary lexical components
known as Tokens. The normal token types are
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
Whitespace separation is necessary between tokens.

5.7.1. Identifiers
An Identifier is a name used to identify a variable, function, class, module or object.

55 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 55 26-12-2022 17:27:28


• An identifier must start with an alphabet (A..Z and a..z) or underscore ( _ ).
• Identifiers may contain digits (0 .. 9)
• Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
• Identifiers must not be a python keyword.
• Python does not allow punctuation character such as %,$, @ etc., within identifiers.

Example of valid identifiers


Sum, total_marks, regno, num1
Example of invalid identifiers
12Name, name$, total-mark, continue

5.7.2. Keywords
Keywords are special words used by Python interpreter to recognize the structure of
program. As these words have specific meaning for interpreter, they cannot be used for any
other purpose.
Table 5.1 Python’s Keywords

False class finally is return

None continue for lambda try

True def from nonlocal while

and del global not with

as elif if or yield

assert else import pass

break except in raise

5.7.3 Operators
In computer programming languages operators are special symbols which represent
computations, conditional matching etc. The value of an operator used is called operands.
Operators are categorized as Arithmetic, Relational, Logical, Assignment etc. Value and
variables when used with operator are known as operands.
(i) Arithmetic operators
An arithmetic operator is a mathematical operator that takes two operands and performs
a calculation on them. They are used for simple arithmetic. Most computer languages contain a
set of such operators that can be used within equations to perform different types of sequential
calculations.
XII Std Computer Science 56

12th Computer Science_EM Chapter 5.indd 56 26-12-2022 17:27:28


Python supports the following Arithmetic operators.

Operator - Operation Examples Result

Assume a=100 and b=10. Evaluate the following expressions


+ (Addition) >>> a + b 110
- (Subtraction) >>>a – b 90
* (Multiplication) >>> a*b 1000
/ (Divisioin) >>> a / b 10.0
% (Modulus) >>> a % 30 10
** (Exponent) >>> a ** 2 10000
// (Floor Division) >>> a//30 (Integer Division) 3

Program 5.1 To test Arithmetic Operators:


#Demo Program to test Arithmetic Operators
a=100
b=10
print ("The Sum = ",a+b)
print ("The Difference = ",a-b)
print ("The Product = ",a*b)
print ("The Quotient = ",a/b)
print ("The Remainder = ",a%30)
print ("The Exponent = ",a**2)
print ("The Floor Division =",a//30)
#Program End
Output:
The Sum = 110
The Difference = 90
The Product = 1000
The Quotient = 10.0
The Remainder = 10
The Exponent = 10000
The Floor Division = 3

(ii) Relational or Comparative operators


A Relational operator is also called as Comparative operator which checks the
relationship between two operands. If the relation is true, it returns True; otherwise it returns
False.

57 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 57 26-12-2022 17:27:28


Python supports following relational operators

Operator - Operation Examples Result


Assume the value of a=100 and b=35. Evaluate the following expressions.
== (is Equal) >>> a==b False
> (Greater than) >>> a > b True
< (Less than) >>> a < b False
>= (Greater than or Equal to) >>> a >= b True
<= (Less than or Equal to) >>> a <= b False
!= (Not equal to) >>> a != b True

Coding 5.2 To test Relational Operators:


#Demo Program to test Relational Operators
a=int (input("Enter a Value for A:"))
b=int (input("Enter a Value for B:"))
print ("A = ",a," and B = ",b)
print ("The a==b = ",a==b)
print ("The a > b = ",a>b)
print ("The a < b = ",a<b)
print ("The a >= b = ",a>=b)
print ("The a <= b = ",a<=b)
print ("The a != b = ",a!=b)
#Program End
Output:
Enter a Value for A:35
Enter a Value for B:56
A = 35 and B = 56
The a==b = False
The a > b = False
The a < b = True
The a >= b = False
The a <= b = False
The a != b = True

(iii) Logical operators


In python, Logical operators are used to perform logical operations on the given
relational expressions. There are three logical operators they are and, or and not.

XII Std Computer Science 58

12th Computer Science_EM Chapter 5.indd 58 26-12-2022 17:27:29


Operator Example Result
Assume a = 97 and b = 35, Evaluate the following Logical expressions
or >>> a>b or a==b True
and >>> a>b and a==b False
not >>> not a>b False i.e. Not True

Program 5.3 To test Logical Operators:

Example – Code Example - Result

#Demo Program to test Logical Operators Enter a Value for A:50


a=int (input("Enter a Value for A:")) Enter a Value for B:40
b=int (input("Enter a Value for B:")) A = 50 and b = 40
print ("A = ",a, " and b = ",b) The a > b or a == b = True
print ("The a > b or a == b = ",a>b or a==b) The a > b and a == b = False
print ("The a > b and a == b = ",a>b and a==b) The not a > b = False
print ("The not a > b = ",not a>b)
#Program End

(iv) Assignment operators


In Python, = is a simple assignment operator to assign values to variable. Let a = 5 and
b = 10 assigns the value 5 to a and 10 to b these two assignment statement can also be given
as a,b=5,10 that assigns the value 5 and 10 on the right to the variables a and b respectively.
There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //= are also
available.

Operator Description Example


Assume x=10
>>> x=10
= Assigns right side operands to left variable
>>> b=”Computer”
Added and assign back the result
+= >>> x+=20 # x=x+20
to left operand
Subtracted and assign back the
-= >>> x-=5 # x=x-5
result to left operand
Multiplied and assign back the
*= >>> x*=5 # x=x*5
result to left operand
Divided and assign back the
/= >>> x/=2 # x=x/2
result to left operand

59 Python – Variables and Operators

12th Computer Science_EM Chapter 5.indd 59 26-12-2022 17:27:29


Taken modulus(Remainder) using two
%= operands and assign the result >>> x%=3 # x=x%3
to left operand

Performed exponential (power) calculation on


**= >>> x**=2 # x=x**2
operators and assign value to the left operand

Performed floor division on operators and


//= >>> x//=3
assign value to the left operand

Program 5.4 To test Assignment Operators:

Program Coding Output

#Demo Program to test Assignment Operators Type a Value for X : 10


x=int (input("Type a Value for X : ")) X = 10
print ("X = ",x) The x is = 10
print ("The x is =",x) The x += 20 is = 30
x+=20 The x -= 5 is = 25
print ("The x += 20 is =",x) The x *= 5 is = 125
x-=5 The x /= 2 is = 62.5
print ("The x -= 5 is = ",x) The x %= 3 is = 2.5
x*=5 The x **= 2 is = 6.25
print ("The x *= 5 is = ",x) The x //= 3 is = 2.0
x/=2
print ("The x /= 2 is = ",x)
x%=3
print ("The x %= 3 is = ",x)
x**=2
print ("The x **= 2 is = ",x)
x//=3
print ("The x //= 3 is = ",x)
#Program End

(v) Conditional operator


Ternary operator is also known as conditional operator that evaluate something based
on a condition being true or false. It simply allows testing a condition in a single line replacing
the multiline if-else making the code compact.

XII Std Computer Science 60

12th Computer Science_EM Chapter 5.indd 60 26-12-2022 17:27:29

You might also like