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

Python (ch2)

Uploaded by

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

Python (ch2)

Uploaded by

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

Chapter 2

BY- MIS.ITISHREE BARIK


ASST. PROFESSOR, DEPT OF CSE, SIR MVIT
2.1 Boolean Values
• While the integer, floating-point, and string data types have an unlimited number of possible
values, the Boolean data type has only two values: True and False.
• The Name Boolean is because the data type is named after mathematician George Boole.
• The Boolean values True and False always start with a capital T or F, with the rest of the word
in lowercase.
>>> spam = True
# Boolean values are used in expressions and can be stored in variables
>>> spam
>>> true #If you don’t use the proper case Traceback (most recent call last): File ““<pyshell#>”,
line 1, in true NameError: name 'true' is not defined

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.2 Operators
These are the in-built logics which are in the form of symbols used to perform the particular task
on an operation.
Generally to perform an application two parameters are important.
1-Operands
2-Operators
Operand is the one on which the operation is performed.
Operator is the one by which the operation is performed.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.3 Comparison Operators
• Comparison operators compare two values and evaluate down to a single Boolean value. •
Table below lists the comparison operators.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Examples:

>>> 42 == 42

True

>>> 42 == 99

False

>>> 2 != 3

True

>>> 2 != 2

False

>>> 'hello' == 'hello'

True

>>> 'hello' == 'Hello'

False

>>> 'dog' != 'cat'

True

>>> 42 == ‘42’

False

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.4The Difference Between the == and = Operators
• The == operator (equal to) asks whether two values are the same as each other.
• The = operator (assignment) puts the value on the right into the variable on the left.
2.3 Boolean Operators •
The three Boolean operators (and, or, and not) are used to compare Boolean values. • Like
comparison operators, they evaluate these expressions down to a Boolean value.
• The and & or operators always take two Boolean values (or expressions), so they’re considered
binary operators.
* The AND operator evaluates an expression to True if both Boolean values are True; otherwise, it
evaluates to False.
*The OR operator evaluates an expression to True if one Boolean values are True.
*The NOT operator which is used to invert the input.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
2.5 Mixing Boolean and Comparison Operators
Examples:
>>> (4 < 5) and (5 < 6)
True
>>> (4 < 5) and (9 < 6)
False
>>> (1 == 2) or (2 == 2)
True
>>> 2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2
True
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
The process of evaluating (4 < 5) and (5 < 6) to True.
(4 < 5) and (5 < 6)

True and (5 < 6)

True and True

True

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.6 Flow control
• The real strength of programming isn’t just running (or executing) one instruction after another.
• Based on how the expressions evaluate, the program can decide to skip instructions, repeat
them, or choose one of several instructions to run.
• Flow control statements can decide which Python instructions to execute under which
conditions.
• These flow control statements directly correspond to the symbols in a flowchart.
A flowchart to tell you what to do if it is raining
• In a flowchart, there is usually more than one way to go from the start to the end.
• The same is true for lines of code in a computer program.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


• Flow charts represent these branching points with diamonds, while the other steps are
represented with rectangles.
• The starting and ending steps are represented with rounded rectangles.
• But before you learn about flow control statements, you first need to learn how to represent
those yes and no options, and you need to understand how to write those branching points as
Python code.
• To that end, let’s explore Boolean values, comparison operators, and Boolean operators

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7Elements of Flow Control
• Condition
• Clause
➢ Flow control statements often start with a part called the condition, and all are followed by a block of code called the clause.
• Conditions always evaluate down to a Boolean value, True or False.
• A flow control statement decides what to do based on whether its condition is True or False, and almost every flow control statement uses a
condition.
Blocks of Code
• Lines of Python code can be grouped together in blocks.
• You can tell when a block begins and ends from the indentation of the lines of code.
Rules for blocks There are three rules for blocks.
1. Blocks begin when the indentation increases.
2. 2. Blocks can contain other blocks.
3. 3. Blocks end when the indentation decreases to zero or to a containing block’s indentation.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Example:
if name == 'Mary':
print('Hello Mary')
if password == 'swordfish':
print('Access granted.')
else:
print('Wrong password.')
Explanation of the code:
• The first block of code starts at the line print('Hello Mary') and contains all the lines after it
. • Inside this block there is another block , which has only a single line in it: print('Access Granted.').
• The third block is also one line long: print('Wrong password.')

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Program Execution:
The program execution (or simply, execution) is a term for the current instruction being
executed.
2.7 Flow Control Statements
• if Statement
• else Statements
• elif Statements
• while Loop Statements
• break Statements
• continue Statements
• for Loops and the range() Function

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7.1 if Statement
• The most common type of flow control statement is the if statement.
• An if statement’s clause (that is, the block following the if statement) will execute if the
statement’s condition is True.
• The clause is skipped if the condition is False. In Python, an if statement consists of the
following:
• The if keyword
• A condition (that is, an expression that evaluates to True or False) • A colon(:) • Starting on the
next line, an indented block of code (called the if clause)

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


The flowchart for an if statement
Example: Syntax:
age = input('Enter your age:') if<condition>:
if int (age) >= 18: TSB
print("You're eligible to vote.") (tabspace)
print("Let's go and vote.")

Note: TSB—[True statement Block]

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7.2 if-Else Statements
• An if clause can optionally be followed by an else statement.
• The else clause is executed only when the if statement’s condition is False.
• In plain English, an else statement could be read as, “If this condition is true, execute this code.
Or else, execute that code.”
An else statement doesn’t have a condition, and in code, an else statement always consists of the
following:
• The else keyword
• A colon
• Starting on the next line, an indented block of code (called the else clause)

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


The flowchart for an if –else statement
Syntax-
if condition:
if-block;
else:
else-block;
In this syntax the if..else will execute the if-block
if the condition evaluates to True.Otherwise,
It will execute the else-block.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Example— Output—
st=input("char:")
if st in"aeiouAEIOU":
print("vowel") char:s
not vowel
else:
print("not vowel")

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7.3 elif Statements
• While only one of the if or else clauses will execute, you may have a case where you want one
of many possible clauses to execute.
• The elif statement is an “else if” statement that always follows an if or another elif statement.
In code, an elif statement always consists of the following:
• The elif keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the elif clause)

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Flowchart of el-if statement
Syntax:
if if-condition:
if-block
elif elif-condition1:
elif-block1
elif elif-condition2:
elif-block2
...
else:
else-block
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
Example- Output—
a=int(input("enter a no:"))
enter a no:5
if a>0: positive no
enter a no:-7
print("positive no")
Negative no
elif a<0: enter a no:0
neutral
print("negative no")
else:
print("neutral")

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


1.WAP to find out a number is even or odd.
n=int(input("enter a number:"))
if n%2==0:
print("even number")
else:
print("odd number")
o/p—
enter a number:6
even number
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
2.WAP to display the year is leap year or not.
year=2024
if year%4==0 and year%100!=0:
print("leap year")
else:
print("not a leap year")
o/p—
Leap year

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


3.WAP TO Verify if the given input is the single value or collection value.

a=(1,2,3)
if type(a) in (int,float,complex,bool):
print('single value')
else:
print('collection value')
o/p—
Collection value

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7.4 while Loop Statements
• You can make a block of code execute over and over again with a while statement.
• The code in a while clause will be executed as long as the while statement’s condition is True.
A while statement always consists of the following:
• The while keyword
• A condition (that is, an expression that evaluates to True or False)
• A colon
• Starting on the next line, an indented block of code (called the while clause)

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Flowchart of While statement
Syntax--

while condition:
# body of while loop
Here,
1.The while loop evaluates the condition.
2.If the condition is true, body of while loop is executed.
The condition is evaluated again.
3.This process continues until the condition is False.
4.Once the condition evaluates to False, the loop terminates.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Example— Output—
i=1
while i<=5:
Hello
print(‘Hello’) Hello
Hello
i=i+1 Hello
Hello

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


1.WAP to find out the factorial of a given no.
n=int(input("enter a number:"))
fact=1
i=1
while i<=n:
fact=fact*i
i=i+1
print(fact)
o/p—
enter a number:4
24

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.WAP to calculate the sum of numbers until user enters 0.
num=int(input("enter a number:"))
i=0
while num!=0:
i=i+num
num=int(input("enter a number:"))
print("the sum is",i) o/p—
enter a number:2
enter a number:5
enter a number:7
enter a number:0
the sum is 14

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


3.WAP to printing those numbers divisible by either 5 or 7 within 1 to 50 using while loop.
i=1
while i<51:
if i%5==0 or i%7==0:
print(i,end=' ')
i=i+1 o/p—
5 7 10 14 15 20 21 25 28 30 35 40 42 45 49 50

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7.5 for Loops and the range() Function
For Loop—
What if you want to execute a block of code only a certain number of times??
Solution is do this with a for loop statement and the range() function for always includes the following:
• The for keyword
• A variable name
• The in keyword
• A call to the range() method with up to three integers passed to it
• A colon
• Starting on the next line, an indented block of code (called the for clause)
Syntax-for value in sequence:
{loop body}

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Flowchart of For loop
WAP to display all vowels.
Example-
For i in ‘string’:
◦ Print(i)

◦ o/p—
◦ S
◦ T
◦ R
◦ I
◦ N
◦ g

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


1.WAP to check no is prime or not.
num=int(input("enter a number:"))
for i in range(2,num):
if num%i==0:
print("not prime")
break
else:
print("prime")

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


1.WAP To Adding all elements of a digit.
x=0
n=12345
Int object cannot itterable
s=str(n)
for i in s :
x=x+int(i)
print(x)
o/p—
15
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
#multiplication
x=1
n=23456
s=str(n)
for i in s :
x=x*int(i)
print(x)

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Range() function
• The range() function can also be called with three arguments.
• The first two arguments will be the start and stop values, and the third will be the step argument.
• The step is the amount that the variable is increased by after each iteration.
Example— Output—
7
for i in range(1,71): 14
21
if i%7==0: 28
print(i) 35
42
49
56
63
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
70
1. display the all prime no within a range.
start = 1 o/p--
end = 50
for num in range(start, end + 1):
if num > 1: # all prime #s are greater than 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num,end=' ')
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
2.7.5 break Statements
• ‘Break’ in Python is a loop control statement.
• There is a shortcut to getting the program execution to break out of a while loop’s clause early.
• If the execution reaches a break statement, it immediately exits the while loop’s clause.
• break statement is put inside the loop body (generally after if condition).
• In code, a break statement simply contains the break keyword.
**The syntax is as follows:
break;
It is used after the loop statements.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Syntax---

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Example--
for i in range(5):
if i == 3:
break
print(i) Output—

0
1
2

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.7.6 continue Statements
• The continue statement is used to skip the rest of the code inside a loop for the current iteration
only.
• Loop does not terminate but continues on with the next iteration
• When the program execution reaches a continue statement, the program execution immediately
jumps back to the start of the loop and re-evaluates the loop’s condition.
*Syntax—
continue

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


Example— Output—
for i in range(5):
if i == 3:
0
continue 1
2
print(i)
4

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


2.8 Importing Modules
• All Python programs can call a basic set of functions called built-in functions, including the
print(), input(), and len() functions.
• Python also comes with a set of modules called the standard library.
• Each module is a Python program that contains a related group of functions that can be
embedded in your programs.
• For example, the math module has mathematics- related functions
• The random module has random number–related functions, and so on.
• Before you can use the functions in a module, you must import the module with an import
statement.

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT


• An import statement consists of the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas
• Once you import a module, you can use all the functions of that module.
Example—
import math #You need to put this command,`import` keyword along with the name of
num = 4 the module you want to import
print(math.sqrt(num)) Output--
2.0
Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT
2.9 Ending a Program early with sys.exit()
# importing sys

import sys

temp = 100

if temp == 100:

sys.exit("Exiting the code with sys.exit()!") SystemExit: Exiting the


else:
code with sys.exit()!

print("Temp is not equal to 100",temp)

(python exit function sys.exit, is a built –in method used to terminate a python

Script)

Prepared by:ITISHREE BARIK Asst.Professor of CSE,MVIT

You might also like