Operators and basic constructs in python | PDF | Computer Science | Computer Architecture
0% found this document useful (0 votes)
5 views68 pages

Operators and basic constructs in python

Uploaded by

Bhargavi V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views68 pages

Operators and basic constructs in python

Uploaded by

Bhargavi V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 68

Python Programming

Operators and basic constructs


Python - IDLE
Before we start Python programming, we need to have an interpreter
to interpret and run our programs. There are certain online interpreters
like http://ideone.com/ or http://codepad.org/ , colab that can be used
to run Python programs without installing an interpreter.

Windows: There are many interpreters available freely to run Python


scripts like IDLE (Integrated Development Environment) that comes
bundled with the Python software downloaded
from http://python.org/.

Linux: Python comes preinstalled with popular Linux distros such as


Ubuntu and Fedora. To check which version of Python you’re
running, type “python” in the terminal emulator. The interpreter
should start and print the version number.

macOS: Generally, Python 2.7 comes bundled with macOS. You’ll


have to manually install Python 3 from http://python.org/.
How to install Python on Windows?

Since windows don’t come with Python preinstalled, it needs to be


installed explicitly. Here we will define step by step tutorial on How
to install Python on Windows.
Follow the steps below :
Download Python Latest Version from python.org
First and foremost step is to open a browser and
open https://www.python.org/downloads/windows/
How to install Python on Windows?

 Underneath the Python Releases for Windows find Latest Python 3


Release – Python 3.7.4 (latest stable release as of now is Python 3.7.4).
 On this page move to Files and click on Windows x86-64 executable
installer for 64-bit or Windows x86 executable installer for 32-bit.
How to install Python on Windows?
Run the Python Installer from downloads folder

Make sure to mark Add Python 3.7 to PATH otherwise you


will have to do it explicitly. It will start installing python on
windows.
How to install Python on Windows?
How to install Python on Windows?
After installation is complete click on Close.
Bingo..!! Python is installed. Now go to windows and type IDLE.
Python….
• High-level language; other high-level languages you might
have heard of are C, C++, Perl, and Java.

• There are also low-level languages, sometimes referred to as


“machine languages” or “assembly languages.”

• Computers can only run programs written in low-level


languages.

• So programs written in a high-level language have to be


processed before they can run.
Python….
• Two kinds of program translator to convert from
high-level languages into low-level languages:
– Interpreters

– Compilers.

• An interpreter processes the program by reading it


line by line
Python….
• Compiler translates completely a high level program
to low level it completely before the program starts
running.

• High-level program is called source code

• Translated program is called the object code or the


executable.
Python….
• Python is considered an interpreted language because Python
programs are executed by an interpreter.

• There are two ways to use the interpreter:

interactive mode and script mode.


Python….Interactive mode

In interactive mode, you type Python programs and the interpreter


displays the result:
>>> 1 + 1
2

The shell prompt, >>>, is the prompt the interpreter uses to indicate that
it is ready. If you type 1 + 1, the interpreter replies 2.
Python …. Shell
Python…. Script Mode
• Can also store code in a file and use the interpreter to execute
the contents of the file, which is called a script.

• Python scripts have names that end with .py.

• Interactive mode is convenient for testing small pieces of code


because you can type and execute them immediately.

• But for anything more than a few lines, should save your code
as a script so you can modify and execute it in future.
Python….Script Mode …
File name : first.py
print(4+3)
print(4-3)
print(4>3)
print("hello World")
Operators in Python
Operators in Python
Operators in general are used to perform operations on values and
variables in Python. These are standard symbols used for the
purpose of logical and arithmetic operations.
 Arithmetic operators
 Ternary operator
 Relational operators
 Assignment operators
 Logical operators
 Bitwise operators
 Special operators
Basic Arithmetic operators in Python
Command Name Example Output

+ Addition 4+5 9

- Subtraction 8-5 3

* Multiplication 4*5 20

/ Division 19 / 3 6.3333
// Floor Division 19//3 6

% Remainder (modulo) 19 % 3 1

** Exponent 2 ** 4 16
# Examples of Arithmetic Operator
a=9
b=4

# Addition of numbers
add = a + b

# Subtraction of numbers
sub = a - b

# Multiplication of number
mul = a * b

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number


mod = a % b

# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Order of Operations
1.parentheses ()

2.exponents **

3.multiplication *, division \, and remainder %

4.addition + and subtraction –

5. Assignment operator =
Order of Operations
Operator Operation Precedence
() parentheses 0
** exponentiation 1
* multiplication 2
/ division 2
// int division 2
% remainder 2
+ addition 3
- subtraction 3

21
• The computer scans the expression from left to right,

• first clearing parentheses,

• second, evaluating exponentiations from left to right


in the order they are encountered

• third, evaluating *, /, //, % from left to right in the


order they are encountered,

• fourth, evaluating +, - from left to right in the order


they are encountered

22
Example 1 Order of operations
>>> 1 + 2 * 3

>>> (1 + 2) * 3

• In the first example, the computer calculates 2 * 3 first, then adds 1 to it.
This is because multiplication has the higher priority (at 3) and addition is
below that (at a lowly 4).

• In the second example, the computer calculates 1 + 2 first, then multiplies it


by 3. This is because parentheses have the higher priority (at 1), and
addition comes in later than that.
Example 2 Order of operations
Also remember that the math is calculated from left to right, unless you put in
parentheses. The innermost parentheses are calculated first. Watch these
examples:

>>> 4 - 40 - 3

-39

>>> 4 - (40 - 3)

-33

• In the first example, 4 - 40 is calculated, then - 3 is done.

• In the second example, 40 - 3 is calculated, then it is subtracted from 4.


Ternary Operator

Syntax Eg:
x if y else z >>> a = 2
>>>b = 1 if a>1 else 0
>>>b
1
>>> a = 1
>>>b = 1 if a>1 else 0
>>>b
0
Biggest of two numbers

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

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

c=a if a>b else b

Print(“Biggest number is”,c)


Comparison/Relational Operator
Comparison Operators
Also known as Relational operators, these operators are used in determining the relation
between the operand on either side of the operator.

Operator Syntax Output

If the values of a and b are equal, then the condition becomes


== (a == b)
true.
If values of a and b are not equal, then the condition becomes
!= (a != b)
true.
If values of a and b are not equal, then the condition becomes
<> (a <> b)
true.
If the value of a is greater than the value of b, then the
> (a > b)
condition becomes true.
If the value of a is less than the value of b, then the condition
< (a < b)
becomes true.
If the value of a is greater than or equal to the value of b, then
>= (a >= b)
the condition becomes true.
If the value of b is less than or equal to the value of b, then the
<= (a <= b)
condition becomes true.
# Examples of Relational Operators
a = 13
b = 33

# a > b is False
print(a > b)

# a < b is True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)
Assignment Operator
Comparison Operators
Referred as the name suggests, it is used to declare assignments to the operands; the
following are the types of assignment operators in python.

Operator Description Syntax Output

= Equal to c=a+b assigns a value of a + b into c

+= Add AND c += a is equivalent to c = c + a

-= Subtract AND c -= a is equivalent to c = c – a

*= Multiply AND c *= a is equivalent to c = c * a

/= Divide AND c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a

%= Modulus AND c %= a is equivalent to c = c % a

**= Exponent AND c **= a is equivalent to c = c ** a

//= Floor Division c //= a is equivalent to c = c // a


Logical operators

In Python, Logical operators are used on conditional statements (either

True or False). They perform Logical AND, Logical OR and Logical

NOT operations.

Operator Description Syntax Output

Logical AND: True if both the operands are (2>1)and(5>3) True


and x and y
true (1>4)and(5>3) False

Logical OR: True if either of the operands is (1>4)or(5>3) True


or x or y
true (5<2)or(3>1) False

not Logical NOT: True if operand is false not x


# Python program to demonstrate
# logical and operator
a = 10
b = 12
c =0
if a and b and c:
print("All the numbers have boolean value as True")
else:
print("Atleast one number has boolean value as False")

# Python program to demonstrate


# logical not operator
a = 10
if not a:
print("Boolean value of a is True")

if not (a%3 == 0 or a%5 == 0):


print("10 is not divisible by either 3 or 5")
else:
print("10 is divisible by either 3 or 5")
Bit Operator
Refers to the operators working on a bit, i.e. they treat the operand as a string of bit; for

example, in bitwise operations, 5 will be considered as 0101.

The box below provides the bitwise operators in python.

Operator Description Syntax Output

copies a bit to the result if it exists in both


& Binary AND a&b
operands
| Binary OR a|b copies a bit if it exists in either operand.
copies the bit if it is set in one operand but not
^ Binary XOR a^b
both.
Binary One’s
~ a~b Unary operation of flipping bits
Complement
Binary Left The left operands value is moved left by the
<< a<<b
Shift number of bits specified by the right operand.
Binary Right left operands value is moved right by the
>> a>>b
Shift number of bits specified by the right operand.
Bitwise Operations
• This includes operators that treat integers as
strings of binary bits, and can come in handy if
your Python code must deal with things like
network packets, serial ports, or packed binary
data
>>> x = 1 # 1 decimal is 0001 in bits
>>> x << 2 # Shift left 2 bits: 0100
4
>>>x =8
x>>2
AND operator (&)
Bit 1 Bit2 Resultant
Bit
0 0 0
0 1 0
1 0 0
1 1 1
OR operator (|)
Bit 1 Bit2 Resultant
Bit
0 0 0
0 1 1
1 0 1
1 1 1
Exclusive OR operator (^)
Bit 1 Bit2 Resultant
Bit
0 0 0
0 1 1
1 0 1
1 1 0
Examples of Bitwise operators
a = 10
b = 4
Output:
# Print bitwise AND operation 0
print(a & b) 14
-11
# Print bitwise OR operation 14
print(a | b) 2
40
# Print bitwise NOT operation
print(~a)

# print bitwise XOR operation


print(a ^ b)

# print bitwise right shift operation


print(a >> 2)

# print bitwise left shift operation


print(a << 2)
>>> x | 2 # Bitwise OR (either bit=1): 0011
3
>>> x & 1 # Bitwise AND (both bits=1): 0001
• The last two operations perform a binary OR to
combine bits (0001| 0010 = 0011) and a binary
AND to select common bits (0001&0001 =
0001).
Bit Numbering

• Bit in position ‘0’ is Least Significant Bit (LSB)


• Bit in position ‘7’ Most Significant Bit (MSB)
Uses of bitwise operators
• Left shift operator – for each shift multiplies the
value by 2
• Right shift operator – for each shift divides the value
by 2
• Or operator – Used to set a specific bit
Eg: x | 2 - used to second bit from right of x to 1
>>> x = 1
>>> x | 2
3
• And operator – Used to check if a specific bit is 1
Eg: x & 1 is used to test if bit LSB of x is 1 or 0
x & 2 used to test if second bit from LSB of x is 1 or 0
If second bit from LSB is 1 then x & 2 gives 2 and 0
otherwise
>>> x = 3
>>> x & 2
2
>>> x = 0
>>> x & 2
0
Special operators

Special operators: There are some special type of operators like-

Identity operators-

is and is not are the identity operators both are used to check if two

values are located on the same part of the memory. Two variables that

are equal does not imply that they are identical.is True if the operands

are identical is not True if the operands are not identical


# Examples of Identity
operators
a2 = ‘VIT’
b2 = ‘VIT’ Output:
a3 = [1,2,3] True
b3 = [1,2,3] False

print(a2 is b2)

# Output is False, since


lists are mutable.
print(a3 is b3)
Special operators

Membership operators-

in and not in are the membership operators; used to test whether a


value or variable is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence
Special operators

# Examples of Membership operator


x = ‘VIT Chennai'
y = {3:'a',4:'b'}

Output:
print(‘VIT' in x) True
True
print(‘VIT' not in x) False
True
print(‘Chennai' not in x)
False
print(3 in y)

print('b' in y)
Example Problem

• Little Bob loves chocolate, and he goes to a store


with Rs. N in his pocket. The price of each
chocolate is Rs. C. The store offers a discount: for
every M wrappers he gives to the store, he gets
one chocolate for free. This offer shall be availed
only once. How many chocolates does Bob get to
eat?
PAC

Input Processing Output Solution


Alternatives
Money_In_Hand, Number_Of_Chocol Number_Of_Chocol
Cost_Of_Chocolate, ate = Chocolate got ate
Wrapper_Offer by money +
Chocolate got by
returning wrapper
Pseudocode
• READ Money_In_Hand and Cost_Of_Chocolate

• COMPUTE Number_Of_choc as Money_In_Hand


/Cost_Of_Chocolate

• Number_Of_choc = Number_Of_choc +
(Number_Of_choc /Wrapper_Offer)

• PRINT num_of_chocolates
#Program for calculating number of chocolates
N=int(input("Enter the amount in hand"))
C=int(input("Enter the cost of one chocolate"))
M=int(input("Enter the number of wrappers for
discount"))
a=N//C
b=a//M
T=a+b
print("The number of chocolate BOB gets to eat=",a+b)
Problem 2
ABC company Ltd. is interested to computerize the pay
calculation of their employee in the form of Basic Pay,
Dearness Allowance (DA) and House Rent Allowance
(HRA). DA is 80% of Basic Pay, and HRA is 30% of Basic
pay. They have the deduction in the salary as PF which is
12% of Basic pay.
Input Processing Output Solution
Alternative
Basic Pay Calculate Salary Nothing
Salary
( Basic Pay + (
Basic Pay * 0.8) +
( Basic Pay * 0.3 -
( Basic Pay * 0.12)
Conditional Statements in Python
If – Statements in Python

There come situations in real life when we need to do some


specific task based on some condition evaluation. In such
cases, conditional statements can be used. The following are
the conditional statements provided by Python.
 if
 if..else
 Nested if
 if-elif statements.
if - Statement
if Statement:
If the simple code of block is to be performed if the
condition holds true then, if statement is used. Here if the
condition mentioned is true, then the code of block runs
otherwise not.

Syntax:
if condition:
# Statements to execute if
# condition is true (Indentation)
Example
# if statement example
Output:
if 10 > 5: 10 greater than 5
Program ended

print("10 greater than 5")

print("Program ended")

Indentation(White space) is used to delimit the block of code. As


shown in the above example it is mandatory to use indentation in
Python3 coding.
if..else Statement:
if..else Statement:
It has both true and false blocks. Either true or false block
would be executed based on condition evaluation of if
statement.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example

# if..else statement example

x=3

if x == 4:

print("Yes")

else:

print("No")
IF-else construct

Syntax: Example:

N=int(input(“Enter n:”))
if(condition):
if(N%2==0):
statements
print(N,”is even”)
else:
else:
statements print(N,”is Odd”)
Example
You can also chain if..else statement with more than one condition.
Nested if Statement

Nested if Statement:
if statement can also be checked inside other if statement.
This conditional statement is called nested if statement. This
means that inner if condition will be checked only if outer if
condition is true and by this, we can see multiple conditions
to be satisfied.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example
if-elif Statement

if-elif Statement:

The if-elif statement is shortcut of if..else chain. While

using if-elif statement at the end else block is added

which is performed if none of the above if-elif statement

is true.
Syntax: if-elif Statement
if (condition):
statement
elif (condition):
statement
elif (condition):
statement
..
..
..
else:
statement
Example
Selection pattern

Example 1: Write a program to find the average score of a student

in physics, chemistry and maths which help them to qualify for

a medical education or engineering education. If the average

score is greater than or equal to 98, the candidate is eligible for

scholarship and not eligible for scholarship otherwise

You might also like