0% found this document useful (0 votes)
21 views46 pages

Unit Ii

Uploaded by

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

Unit Ii

Uploaded by

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

PROBLEM SOLVING USING PYTHON

UNIT-II OPERATORS & BRANCHING

 Python Variables
. Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.
. In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.
. Variable names can be agroup of both the letters and digits, but they have to begin
with a letter or an underscore.
. It is recommended to use lowercase letters for the variable name. Rahulandrahul both
are two different variables.

Identifier Naming

Variables are the example of identifiers. An Identifier is used to identify the literals used in the
program. The rules to name an identifier are given below.

o The first character of the variable must bean alphabet or underscore ( _ ).


o All the characters except the first character may be an alphabet of lower-case(a-z), upper-
case (A-Z), underscore, or digit (0-9).
o Identifier name must not contain any white-space, or special character (!, @, #, %, ^, &,
*).
o Identifier name must not be similar to any keyword defined in the language.
o Identifier names are case sensitive; for example, my name, and MyName is not the same.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.

Declaring Variable and Assigning Values

Python does not bind us to declare a variable before using it in the application. It allows us to
create a variable at the required time.

We don't need to declare explicitly variable in Python. When we assign any value to the
variable, that variable is declared automatically.

The equal (=) operator is used to assign value to a variable.

SRINIVASARAO G (PROF)-VITAP 1
PROBLEM SOLVING USING PYTHON

Object References

It is necessary to understand how the Python interpreter works when we declare a variable. The
process of treating variables is somewhat different from many other programming languages.

Python is the highly object-oriented programming language; that's why every data item belongs
to a specific type of class. Consider the following example.

print("John")

Output:

John

The Python object creates an integer object and displays it to the console. In the above print
statement, we have created a string object. Let's check the type of it using the Python built-in
type() function.

1. type("John")

Output:

<class 'str'>

In Python, variables are a symbolic name that is a reference or pointer to an object. The variables
are used to denote objects by that name.

Let's understand the following example

1. a = 50

In the above image, the variable a refers to an integer object.

Suppose we assign the integer value 50 to a new variable b.

a = 50

b=a

SRINIVASARAO G (PROF)-VITAP 2
PROBLEM SOLVING USING PYTHON

The variable b refers to the same object that a points to because Python does not create another

object.

Let's assign the new value to b. Now both variables will refer to the different objects.

a = 50

b =100

Python manages memory efficiently if we assign the same variable to two different values.

Object Identity

In Python, every created object identifies uniquely in Python. Python provides the guaranteed that
no two objects will have the same identifier. The built-in id() function, is used to identify the
object identifier. Consider the following example.

1. a = 50
2. b = a
3. print(id(a))
4. print(id(b))
5. # Reassigned variable a
6. a = 500

SRINIVASARAO G (PROF)-VITAP 3
PROBLEM SOLVING USING PYTHON
7. print(id(a))

SRINIVASARAO G (PROF)-VITAP 3
PROBLEM SOLVING USING PYTHON

Output:

140734982691168
140734982691168
2822056960944

We assigned the b = a, a and b both point to the same object. When we checked by the id()
function it returned the same number. We reassign a to 500; then it referred to the new object
identifier.

Variable Names

We have already discussed how to declare the valid variable. Variable names can be any length
can have uppercase, lowercase (A to Z, a to z), the digit (0-9), and underscore character(_).
Consider the following example of valid variables names

1. name = "Devansh"
2. age = 20
3. marks = 80.50
4. print(name)
5. print(age)
6. print(marks)

Output:

Devansh
20
80.5

Consider the following valid variables name.

1. name = "A"
2. Name = "B"
3. naMe = "C"
4. NAME = "D"
5. n a m_e = "E"

6. _name = "F"
7. name_ = "G"
8. _name_ = "H"

SRINIVASARAO G (PROF)-VITAP 4
PROBLEM SOLVING USING PYTHON

9. na56me = "I"
10. print(name,Name,naMe,NAME,n a m_e, NAME, n a m_e, _name, name , name,
na56me)

Output:

ABCDEDEFGFI

The multi-word keywords can be created by the following method.

o Camel Case - In the camel case, each word or abbreviation in the middle of begins with a
capital letter. There is no intervention of whitespace. For example - nameOfStudent,
valueOfVaraible, etc.

o Pascal Case - It is the same as the Camel Case, but here the first word is also capital.
For example - NameOfStudent, etc.

o Snake Case - In the snake case, Words are separated by the underscore. For
example - name_of_student, etc.

Multiple Assignment

Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.

1. Assigning single value to multiple variables

Eg:

1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)

Output:

50
50
50

SRINIVASARAO G (PROF)-VITAP 5
PROBLEM SOLVING USING PYTHON

2. Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15
2. print a
3. print b
4. print c

Output:

5
10
15
The values will be assigned in the order in which variables appear.

Python Variable Types

There are two types of variables in Python - Local variable and Global variable. Let's understand
the following variables.

Local Variable

Local variables are the variables that declared inside the function and have scope within the
function. Let's understand the following example.

Example -

1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8. # Calling a function
9. add()

SRINIVASARAO G (PROF)-VITAP 6
PROBLEM SOLVING USING PYTHON

Output:

The sum is: 50


Explanation:

In the above code, we declared a function named add() and assigned a few variables within the
function. These variables will be referred to as the local variables which have scope only inside
the function. If we try to use them outside the function, we get a following error.

1. add()
2. # Accessing local variable outside the function
3. print(a)

Output:

The sum is: 50


print(a)
NameError: name 'a' is not defined
We tried to use local variable outside their scope; it threw the NameError.

Global Variables

Global variables can be used throughout the program, and its scope is in the entire program. We
can use global variables inside or outside the function.

A variable declared outside the function is the global variable by default. Python
provides the global keyword to use global variable inside the function. If we don't use the global
keyword, the function treats it as a local variable. Let's understand the following example.

Example -

1. # Declare a variable and initialize it


2. x = 101
3. # Global variable in function
4. def mainFunction():
5. # printing a global variable
6. global x
7. print(x)
8. # modifying a global variable
9. x = 'Welcome To Javatpoint'
10. print(x)
11. mainFunction()

SRINIVASARAO G (PROF)-VITAP 7
PROBLEM SOLVING USING PYTHON

12. print(x)

Output:

101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:

In the above code, we declare a global variable x and assign a value to it. Next, we defined a
function and accessed the declared variable using the global keyword inside the function. Now we
can modify its value. Then, we assigned a new string value to the variable x.

Now, we called the function and proceeded to print x. It printed the as newly assigned value of x.

Delete a variable
We can delete the variable using the del keyword. The syntax is given below.

1. del <variable_name>

In the following example, we create a variable x and assign value to it. We deleted variable x,
and print it, we get the error "variable x is not defined". The variable x will no longer use in
future.

Example -

1. # Assigning a value to x
2. x = 6
3. print(x)
4. # deleting a variable.
5. del x
6. print(x)

Output:

SRINIVASARAO G (PROF)-VITAP 8
PROBLEM SOLVING USING PYTHON
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined

SRINIVASARAO G (PROF)-VITAP 8
PROBLEM SOLVING USING PYTHON

Print Single and Multiple Variables in Python

We can print multiple variables within the single print statement. Below are the example of single
and multiple printing values.

Example - 1 (Printing Single Variable)

1. # printing single value


2. a = 5
3. print(a)
4. print((a))

Output:

5
5
Example - 2 (Printing Multiple Variables)

1. a = 5
2. b = 6
3. # printing multiple variables
4. print(a,b)
5. # separate the variables by the comma
6. Print(1, 2, 3, 4, 5, 6, 7, 8)

Output:

56
12345678

SRINIVASARAO G (PROF)-VITAP 9
PROBLEM SOLVING USING PYTHON

 Python Data Types


Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.

1. a = 5
The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides
us the type() function, which returns the type of the variable passed.
Consider the following example to define the values of different data types and checking its type.

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types

A variable can hold different types of values. For example,a person's name must be stored as a
string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them. The
data types defined in Python are given below.

1. Numbers
2. Sequence Type

3. Boolean
4. Set
5. Dictionary

SRINIVASARAO G (PROF)-VITAP 10
PROBLEM SOLVING USING PYTHON

Numbers

Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data- type. Python provides the type() function to know the data-type of the
variable. Similarly, the isinstance() function is used to check an object belongs to a particular
class.

Python creates Number objects when a number is assigned to a variable. For example;

1. a = 5
2. print("The type of a", type(a))
3. b = 40.5
4. print("The type of b", type(b))
5. c = 1+3j
6. print("The type of c", type(c))
7. print(" c is a complex number", isinstance(1+3j,complex))

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True
Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto
15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x andy denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Type
String

The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

SRINIVASARAO G (PROF)-VITAP 11
PROBLEM SOLVING USING PYTHON

String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the operation
"hello"+" python" returns "hello python".

The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python

Python'.

The following example illustrates the string in Python.

Example - 1

1. str = "string using double quotes"


2. print(str)
3. s = '''''A multiline
4. string'''
5. print(s)

Output:

string using double quotes


A multiline
string

Consider the following example of string handling.

Example - 2

1. str1 = 'hello javatpoint' #stringstr1


2. str2 = ' how are you' #stringstr2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

SRINIVASARAO G (PROF)-VITAP 12
PROBLEM SOLVING USING PYTHON

List

Python Lists are similar to arrays in C. However, the list can contain data of different types. The
items stored in the list are separated with a comma (,) and enclosed within square brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+) and
repetition operator (*) works with the list in the same way as they were working with the strings.

Consider the following example.

1. list1 = [1, "hi", "Python", 2]


2. #Checking type of given list
3.
print(type(list1)) 4.
5. #Printing the list1
6. print
(list1) 7.
8. # List slicing
9. print
(list1[3:]) 10.
11. # List slicing
12. print
(list1[0:2]) 13.
14. # List Concatenation using + operator
15. print (list1 +
list1) 16.
17. # List repetation using * operator
18. print (list1 * 3)

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]

SRINIVASARAO G (PROF)-VITAP 13
PROBLEM SOLVING USING PYTHON

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and enclosed
in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Let's see a simple example of the tuple.

1. tup = ("hi", "Python", 2)


2. # Checking type of tup
3. print (type(tup))
4. #Printing the tuple
5. print (tup)
6. # Tuple slicing
7. print (tup[1:])
8. print (tup[0:1])
9. # Tuple concatenation using + operator
10. print (tup + tup)
11. # Tuple repatation using * operator
12. print (tup * 3)
13. # Adding value to tup. It will throw an error.
14. t[2] = "hi"

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (mostrecent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple'object does not support item assignment

SRINIVASARAO G (PROF)-VITAP 14
PROBLEM SOLVING USING PYTHON

Dictionary

Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash
table where each key stores aspecific value. Key can hold any primitive data type, whereas value
is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.

Consider the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


2. # Printing dictionary
3. print (d)
4. # Accesing value using keys
5. print("1st name is "+d[1])
6. print("2nd name is "+ d[4])
7. print (d.keys())
8. print (d.values())

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

Boolean type provides two built-in values, True and False. These values are used to determine the
given statement true or false. It denotes by the class bool. True can be represented by any non-
zero value or 'T'whereas false can be represented by the 0 or 'F'. Consider the following example.

1. # Python program to check the boolean type


2. print(type(True))
3. print(type(False))
4. print(false)

SRINIVASARAO G (PROF)-VITAP 15
PROBLEM SOLVING USING PYTHON

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify after
creation), and has unique elements. In set, the order of the elements is undefined; it may
return the changed sequence of the element. The set is created by using a built-in function set(),
or asequence of elements is passed in the curly braces and separated by the comma. It can
contain various types of values. Consider the following example.

1. # Creating Empty set


2. set1 = set()
3. set2 = {'James', 2, 3,'Python'}
4. #Printing Set value
5. print(set2)
6. # Adding element to the set
7. set2.add(10)
8. print(set2)
9. #Removing element from the set
10. set2.remove(2)
11. print(set2)

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

SRINIVASARAO G (PROF)-VITAP 16
PROBLEM SOLVING USING PYTHON

 Python Operators
The operator can be defined as a symbol which is responsible for a particular operation between
two operands. Operators are the pillars of a program on which the logic is built in a specific
programming language. Python provides a variety of operators, which are described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators

Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes
+ (addition), - (subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and
exponent (**) operators.
Consider the following table for a detailed explanation of arithmetic operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30

- (Subtraction) It is used to subtract the second operand from the first operand. If the first
operand is less than the second operand, the value results negative. For
example, if a = 20, b = 10 => a - b = 10k

/ (divide) It returns the quotient after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a/b = 2.0

*
It is used to multiply one operand with the other. For example, if a = 20, b = 10
(Multiplication) => a * b = 200

SRINIVASARAO G (PROF)-VITAP 17
PROBLEM SOLVING USING PYTHON

% (reminder) It returns the reminder after dividing the first operand by the second operand.
For example, if a = 20, b = 10 => a%b = 0

** (Exponent) It is an exponent operator represented as it calculates the first operand power to


the second operand.

// (Floor It gives the floor value of the quotient produced by dividing the two operands.
division)

Comparison operator
Comparison operators are used to comparing the value of the two operands and returns Boolean
true or false accordingly. The comparison operators are described in the following table.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes true.

<= If the first operand is less than or equal to the second operand, then the condition
becomes true.

>= If the first operand is greater than or equal to the second operand, then the condition
becomes true.

> If the first operand is greater than the second operand, then the condition becomes true.

< If the first operand is less than the second operand, then the condition becomes true.

Assignment Operators]
The assignment operators are used to assign the value of the right expression to the left
operand. The assignment operators are described in the following table.

Operator Description

SRINIVASARAO G (PROF)-VITAP 18
PROBLEM SOLVING USING PYTHON

= It assigns the value of the right expression to the left operand.

+= It increases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 10, b = 20 => a+ = b will be
equal to a = a+ band therefore, a = 30.

-= It decreases the value of the left operand by the value of the right operand and assigns the
modified value back to left operand. For example, if a = 20, b = 10 => a- = b will be equal
to a = a- band therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assigns
the modified value back to then the left operand. For example, if a = 10, b = 20 =>
a* = bwill be equal to a = a* band therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand and assigns the
reminder back to the left operand. For example, if a = 20, b = 10 => a % = b will be equal
to a = a % band therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=bwill assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=bwill assign 4//3 = 1 to a.

Bitwise Operators
The bitwise operators perform bit by bit operation on the values of the two operands. Consider
the following example.

For example,

1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5. hence, a & b = 0110
6. a | b = 0111

7. a ^ b = 0001
8. ~ a = 1000

SRINIVASARAO G (PROF)-VITAP 19
PROBLEM SOLVING USING PYTHON

Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit will be
1.

^ (binary xor) The resulting bit will be 1 if both the bits are different; otherwise, the resulting bit
will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and viceversa.

<< (left shift) The left operand value is moved left by the number of bits present in the right
operand.
>> (right The left operand is moved right by the number of bits present in the right operand.
shift)

Logical Operators

The logical operators are used primarily in the expression evaluation to make a decision. Python
supports the following logical operators.

Operator Description

and If both the expression are true, then the condition will be true. If a and bare
the two expressions, a → true, b → true => aand b → true.

or If one of the expressions is true, then the condition will be true. If a and bare
the two expressions, a → true, b → false => a orb → true.

not If an expression a is true, then not (a) will be false and viceversa.

SRINIVASARAO G (PROF)-VITAP 20
PROBLEM SOLVING USING PYTHON

Membership Operators
Python membership operators are used to check the membership of value inside a Python data
structure. If the value is present in the data structure, then the resulting value is true otherwise it
returns false.

Operator Description

in It is evaluated to be true if the first operand is found in the second operand (list,
tuple, or dictionary).

not in It is evaluated to be true if the first operand is not found in the second operand (list,
tuple, or dictionary).

Identity Operators
The identity operators are used to decide whether an element certain class or type.

Operator Description

is It is evaluated to be true if the reference present at both sides point to the same object.

is not It is evaluated to be true if the reference present at both sides do not point to the same
object.

SRINIVASARAO G (PROF)-VITAP 21
PROBLEM SOLVING USING PYTHON

 Branching Statements

Python If-else statements

. Decision making is the most important aspect of almost all the programming languages.
. As the name implies, decision making allows us to run a particular block of code for a
particular decision.
. Here, the decisions are made on the validity of the particular conditions.
. Condition checking is the backbone of decision making.

In python, decision making is performed by the following statements.

Statement Description

If Statement The if statement is used to test a specific condition. If the condition is true,a block of code (if-
block) will be executed.

If - The if-else statement is similar to if statement except the fact that, it also provides the block of
else Statement the code for the false case of the condition to be checked. If the condition provided in the if
statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if? else statement inside an outer if statement.
Statement

Indentation in Python
. For the ease of programming and to achieve simplicity, python doesn't allow the
use of parentheses for the block level code.
. In Python, indentation is used to declare a block. If two statements are at the same
indentation level, then they are the part of the same block.
. Generally, four spaces are given to indent the statements which are a typical
amount of indentation in python.
. Indentation is the most used part of the python language since it declares the block of
code. All the statements of one block are intended at the same level indentation. We will
see how the actual indentation takes place in decision making and other stuff in python.

SRINIVASARAO G (PROF)-VITAP 22
PROBLEM SOLVING USING PYTHON

The if statement
. The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block.
. The condition of if statement can be any valid logical expression which can be either
evaluated to true or false.

The syntax of the if-statement is given below.

1. if expression:
2. statement
Example 1
1. num = int(input("enter the number?"))
2. if num%2 == 0:
3. print("Number is even")

Output:

enter the number?10


Number is even

SRINIVASARAO G (PROF)-VITAP 23
PROBLEM SOLVING USING PYTHON

Example 2 : Program to print the largest of the three numbers.


1. a = int(input("Enter a? "));
2. b = int(input("Enter b? "));
3. c = int(input("Enter c? "));
4. if a>band a>c:
5. print("ais largest");
6. if b>aand b>c:
7. print("bis largest");
8. if c>aand c>b:
9. print("c is largest");

Output:

Enter a? 100
Enter b? 120
Enter c? 130
c is largest

The if-else statement


The if-else statement provides an else block combined with the if statement which is executed in
the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.

The syntax of the if-else statement is given below.

1. if condition:
2. #block of statements
3. else:
4. #another block of statements (else-block)

SRINIVASARAO G (PROF)-VITAP 24
PROBLEM SOLVING USING PYTHON

Example 1 : Program to check whether a person is eligible to vote or not.


age = int (input("Enter your age? "))

if age>=18:
print("You are eligible to vote !!");

else:
print("Sorry!you have to wait !!");

Output:

SRINIVASARAO G (PROF)-VITAP 25
PROBLEM SOLVING USING PYTHON

Enter your age? 90


You are eligible to vote !!

Example 2: Program to check whether a number is even or not.

1. num = int(input("enter the number?"))


2. if num%2 == 0:
3. print("Number is even...")
4. else:
5. print("Number is odd...")

Output:

enter the number?10


Number is even

The elif statement


. The elif statement enables us to check multiple conditions and execute the specific
block of statements depending upon the true condition among them.
. We can have any number of elif statements in our program depending upon our need.
. However, using elif is optional.
. The elif statement works like an if-else-if ladder statement in C. It must be succeeded
by an if statement.
The syntax of the elif statement is given below.
1. if expression 1:

2. # block of statements
3. elif expression 2:

4. # block of statements
5. elif expression 3:

6. # block of statements
7. else:

SRINIVASARAO G (PROF)-VITAP 26
PROBLEM SOLVING USING PYTHON

8. # block of statements

Example 1
1. number = int(input("Enter the number?"))
2. if number==10:
3. print("number is equals to 10")
4. elif number==50:
5. print("number is equal to 50");
6. elif number==100:
7. print("number is equal to 100");
8. else:
9. print("number is not equal to 10, 50 or 100");

Output:

SRINIVASARAO G (PROF)-VITAP 27
PROBLEM SOLVING USING PYTHON

Enter the number?15


number is not equal to 10, 50 or 100

Example 2
1. marks = int(input("Enter the marks? "))

2. f marks > 85 and marks <= 100:


3. print("Congrats ! you scored grade A ...")

4. elif marks > 60 and marks <= 85:


5. print("You scored grade B + ...")

6. elif marks > 40 and marks <= 60:


7. print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
8. print("You scored grade C ...")

9. else:
10. print("Sorry you are fail?")

SRINIVASARAO G (PROF)-VITAP 28
PROBLEM SOLVING USING PYTHON

Example Programs for Operators Concept

 Arithmetic Operators

Addition operator +

x = 10
y = 40
print(x + y)

# Output
50

name = "Kelly"

surname = "Ault"
print(surname + " " + name)

# Output
Ault Kelly

Subtraction -

x = 10
y = 40
print(y - x)

# Output
30

SRINIVASARAO G (PROF)-VITAP 29
PROBLEM SOLVING USING PYTHON

Multiplication *
x=2
y=4

z=5
print(x * y)
print(x * y * z)

# Output
8
40

name = "Jessa"
print(name * 3)

# Output
JessaJessaJessa

Division /
x=2
y=4

z=8
print(y / x)
print(z / y / x)

# Output
2.0

1.0

Floor division //
x=2

SRINIVASARAO G (PROF)-VITAP 30
PROBLEM SOLVING USING PYTHON

y=4

z = 2.2

# normal division
print(y / x)
# Output
2.0

# floor division to get result as integer

print(y // x)
# Output
2

Modulus %
x = 15
y=4
print(x % y)

# Output
3

Exponent **
num = 2

# 2*2
print(num ** 2)

# 2*2*2
print(num ** 3)

SRINIVASARAO G (PROF)-VITAP 31
PROBLEM SOLVING USING PYTHON

# Output
4
8

 Relational (comparison) operators

x = 10
y=5
z=2

# > Greater than


print(x > y) # True
print(x > y > z) # True

# < Less than


print(x < y) # False

print(y < x) # True

# Equal to
print(x == y) # False

print(x == 10) # True

# != Not Equal to
print(x != y) # True

print(10 != x) # False

# >= Greater than equal to

print(x >= y) # True


print(10 >= x) # True

SRINIVASARAO G (PROF)-VITAP 32
PROBLEM SOLVING USING PYTHON

# <= Less than equal to

print(x <= y) # False


print(10 <= x) # True

Output
True

True
False
True
False
True
True
False
True
True
False
True
 Assignment operators

a=4
b=2

a += b
print(a)

a=4

a -= 2
print(a)

a=4

a *= 2

SRINIVASARAO G (PROF)-VITAP 33
PROBLEM SOLVING USING PYTHON

print(a)

a=4

a /= 2
print(a)

a=4

a **= 2
print(a)

a=5

a %= 2
print(a)

a=4

a //= 2
print(a)

Output
6
2
8
2.0

16
1
2

SRINIVASARAO G (PROF)-VITAP 34
PROBLEM SOLVING USING PYTHON

 Logical operators

and (Logical and)


print(True and False) # False

# both are True


print(True and True) # True
print(False and False) # False

print(False and True) # false

# actual use in code


a=2

b=4
# Logical and

if a > 0 and b > 0:


# both conditions are true
print(a * b)

else:
print("Do nothing")

Output
False

True
False
False
8

In the case of arithmetic values, Logical and always returns the second value; as a result,
see the following example.
Example
print(10 and 20) # 20
print(10 and 5) # 5
print(100 and 300) # 300

SRINIVASARAO G (PROF)-VITAP 35
PROBLEM SOLVING USING PYTHON

or (Logical or)

Example
print(True or False) # True

print(True or True) # True


print(False or False) # false
print(False or True) # True

# actual use in code


a=2

b=4

# Logical and

if a > 0 or b < 0:
# atleast one expression is true so conditions is true
print(a + b) # 6

else:
print("Do nothing")

Output
True

True
False
True
6

In the case of arithmetic values, Logical or it always returns the first value; as a result,
see the following code.
Example
print(10 or 20) # 10

SRINIVASARAO G (PROF)-VITAP 36
PROBLEM SOLVING USING PYTHON

print(10 or 5) # 10
print(100 or 300) # 100

not (Logical not)

Example
print(not False) # True return complements result

print(not True) # True return complements result

# actual use in code

a = True

# Logical not

if not a:
# a is True so expression is False
print(a)

else:
print("Do nothing")

Output
Do nothing

In the case of arithmetic values, Logical not always return False for nonzero value.

Example
print(not 10) # False. Non-zero value

print(not 1) # True. Non-zero value


print(not 5) # False. Non-zero value
print(not 0) # True. zero value

SRINIVASARAO G (PROF)-VITAP 37
PROBLEM SOLVING USING PYTHON

 Membership operators

In operator
my_list = [11, 15, 21, 29, 50, 70]

number = 15
if number in my_list:
print("number is present")

else:
print("number is not present")

Output
number is present

Not in operator

Example
my_tuple = (11, 15, 21, 29, 50, 70)

number = 35
if number not in my_tuple:
print("number is not present")

else:
print("number is present")

Output
number not is present

SRINIVASARAO G (PROF)-VITAP 38
PROBLEM SOLVING USING PYTHON

 Identity operators

is operator
x = 10
y = 11

z = 10
print(x is y) # it compare memory address of x andy

print(x is z) # it compare memory address of x and z


Output
False

True
is not operator
x = 10
y = 11

z = 10
print(x is not y) # it campare memory address of x andy

print(x is not z) # it campare memory address of x and z

Output
True

False

SRINIVASARAO G (PROF)-VITAP 39
PROBLEM SOLVING USING PYTHON

 Bitwise Operators

Bitwise and &


a=7

b=4
c=5
print(a & b)

print(a & c)
print(b & c)

Output
4
5
4

Bitwise or |

a=7
b=4
c=5
print(a | b)

print(a | c)
print(b | c)

Output
7
7
5

SRINIVASARAO G (PROF)-VITAP 40
PROBLEM SOLVING USING PYTHON

Bitwise xor ^
a=7
b=4
c=5
print(a ^ c)

print(b ^ c)

Output
3
2
1

Bitwise 1’s complement ~


a=7

b=4
c=3
print(~a, ~b, ~c)

# Output -8 -5 -4

Bitwise left-shift <<


print(4 << 2)
# Output 16

print(5 << 3)
# Output 40

Bitwise right-shift >>

print(4 >> 2)
# Output 1

print(5 >> 2)
# Output 1

SRINIVASARAO G (PROF)-VITAP 41
PROBLEM SOLVING USING PYTHON

Python Operators Precedence

In Python, operator precedence and associativity play an essential role in solving the expression.
An expression is the combination of variables and operators that evaluate based on operator
precedence.

We must know what the precedence (priority) of that operator is and how they will evaluate down
to a single value. Operator precedence is used in an expression to determine which operation to
perform first.
Example: -
print((10 - 4) * 2 +(10+2))
# Output 24

In the above example. 1st precedence goes to a parenthesis(), then for plus and minus
operators. The expression will be executed as.
(10 - 4) * 2 +(10+2)

6 * 2 + 12
12 + 12

The following tables shows operator precedence highest to lowest.

Precedence level Operator Meaning

1 (Highest) () Parenthesis

2 **
Exponent

3 +x, -x ,~x Unary plus, Unary Minus, Bitwise negation

4 *, /, //, % Multiplication, Division, Floor division, Modulus

5 + ,- Addition, Subtraction

SRINIVASARAO G (PROF)-VITAP 42
PROBLEM SOLVING USING PYTHON

6 <<, >> Bitwise shift operator

SRINIVASARAO G (PROF)-VITAP 42
PROBLEM SOLVING USING PYTHON

Precedence level Operator Meaning

7 & Bitwise AND

8 ^
Bitwise XOR

9 | Bitwise OR

10 ==, !=, >, >=, <, <= Comparison

11 is, is not, in, not in Identity, Membership

12 not Logical NOT

13 and Logical AND

14 (Lowest) or Logical OR

SRINIVASARAO G (PROF)-VITAP 43

You might also like