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

py2

cn pysical

Uploaded by

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

py2

cn pysical

Uploaded by

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

PYTHON PROGRAMMING 1

UNIT-II

PRESETED BY
E.RAJALAKSHMI
PYTHON PROGRAMMING
2

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


• Control Flow Statements
• Sequential
• Selection
• Repetition
• Continue and break statements
• Syntax Error
• Python Strings
• Index and Slice strings in Python
• String Operations
• Built in functions using strings
PYTHON PROGRAMMING
3

Control Flow Statements

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


A program’s control flow is the order in which the program’s code executes.The control flow of a
Python program is regulated by conditional statements, loops, and function calls.

Python has three types of control structures:

Sequential - default mode

Selection - used for decisions and branching

Repetition - used for looping, i.e., repeating a piece of code multiple times.
PYTHON PROGRAMMING
4

Sequential

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Sequential statements are a set of statements whose execution process
happens in a sequence. The problem with sequential statements is that if the
logic has broken in any one of the lines, then the complete source code
execution will break.
## This is a Sequential statement
a=20
b=10
c=a-b
print("Subtraction is : ",c)
PYTHON PROGRAMMING
5

Selection

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


In Python, the selection statements are also known as Decision control
statements or branching statements.
Some Decision Control Statements are:

Simple if

if-else

nested if

if-elif-else
PYTHON PROGRAMMING
6

Simple if

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


The syntax of the if-statement is given below

if expression:
statement

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

Output:
enter the number?10
Number is even
PYTHON PROGRAMMING
The if-else statement 7

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

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


if condition:
#block of statements
else:
#another block of statements (else-block)

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


if age>=18:
print("You are eligible to vote !!");
else:
print("Sorry! you have to wait !!");

Output:

Enter your age? 90


You are eligible to vote !!
PYTHON PROGRAMMING
8
The elif statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


The syntax of the elif statement is given below.

if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
PYTHON PROGRAMMING
9
The elif statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10")
elif number==50:
print("number is equal to 50");
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");
PYTHON PROGRAMMING
10
Nested if statements

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


if condition:
if condition: mark = 72
statements
else:
if mark > 50:
statements if mark > = 80:
else: print ("You got A Grade !!")
statements
elif mark > =60 and mark < 80 :
print ("You got B Grade !!")
else:
print ("You got C Grade !!")
else:
print("You failed!!")
PYTHON PROGRAMMING
11

Repetition

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


A repetition statement is used to repeat a group(block) of programming
instructions.
In Python, we generally have two loops/repetitive statements:

•for loop for loop


•while loop

Syntax
for item in sequence:
statements(s)
PYTHON PROGRAMMING
12

for loop

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Example
colors = ("Red", "Blue", "Green")
for color in colors:
print(color)
Output:
Red
Blue
Green
PYTHON PROGRAMMING
13

while loop

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Loops are one of the most important features in computer programming languages .
As the name suggests is the process that get repeated again and again . It offer a
quick and easy way to do something repeated until a certain condition is reached.
Every loop has 3 parts:
x=0
•Initialization while(x < =5):
•Condition print(x)
x+=1
•Updation
OUTPUT
0
Syntax 1
while (condition) :
2
statement(s)
3
4
5
PYTHON PROGRAMMING
14

Continue and break statements

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Python break statement

# Use of break statement inside the loop


for val in "string":
if val == "i":
break
print(val)
print("The end")

Output:
s
t
r
The end
PYTHON PROGRAMMING
15

Continue and break statements

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Python continue statement
Syntax of Continue

>>> for name in names:


... if name != "Nina":
... continue
... print(f"Hello, {name}")
...
Hello, Nina
PYTHON PROGRAMMING
16

Catching exceptions using try and except statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


 ZeroDivisionError: Occurs when a number is divided by zero.
 NameError: It occurs when a name is not found. It may be local or global.
 IndentationError: If incorrect indentation is given.
 IOError: It occurs when Input Output operation fails.
 EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.
PYTHON PROGRAMMING
17

Catching exceptions using try and except statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


a = int(input("Enter a:"))
b = int(input("Enter b:")) Output:
Enter a:10
c = a/b Enter b:0
print("a/b = %d" %c) Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
#other code: c = a/b;
print("Hi I am other part of the program") ZeroDivisionError: division by zero
PYTHON PROGRAMMING
18

Catching exceptions using try and except statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Exception handling in python

Syntax

#block of code
except Exception1:
#block of code
except Exception2:

try:
#block of code
#other code
PYTHON PROGRAMMING
19

Catching exceptions using try and except statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Exception handling in python

try:
a = int(input("Enter a:")) Output:
b = int(input("Enter b:")) Enter a:10
Enter b:0
c = a/b Can't divide with zero
except:
print("Can't divide with zero")
PYTHON PROGRAMMING
20

Catching exceptions using try and except statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Exception handling in python

try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
PYTHON PROGRAMMING
21

Catching exceptions using try and except statement

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Exception handling in python

try:
a = int(input("Enter a:"))
Output:
b = int(input("Enter b:")) Enter a:10
c = a/b Enter b:0
can't divide by zero
print("a/b = %d"%c) <class 'Exception'>
# Using Exception with except statement.
If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
PYTHON PROGRAMMING
22

Syntax Error

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Some syntax error can be:
Error in structure
Missing operators
Unbalanced parenthesis
if (number=200)
count << "number is equal to 20";
else
count << "number is not equal to 200"
PYTHON PROGRAMMING
23

Python

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Strings
# Python string examples - all assignments are identical.
String_var = 'Python'
String_var = "Python"
String_var = """Python"""
# with Triple quotes Strings can extend to multiple lines
String_var = """ This document will help you to
explore all the concepts
of Python Strings!!! """
# Replace "document" with "tutorial" and store in another
variable
substr_var = String_var.replace("document", "tutorial")
print (substr_var)
PYTHON PROGRAMMING
24

Index and Slice Strings in Python

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


sample_str = 'Python String'
print (sample_str[0]) # return 1st character
# output: P
print (sample_str[-1]) # return last character
# output: g
print (sample_str[-2]) # return last second character
# output: n
PYTHON PROGRAMMING
25

String Operations

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Concatenation of Two or More Strings

# Python String Operations


str1 = 'Hello' Output:
str1 + str2 = HelloWorld!
str2 ='World!' str1 * 3 = HelloHelloHello
# using +
print('str1 + str2 = ', str1 + str2)
# using *
print('str1 * 3 =', str1 * 3)
PYTHON PROGRAMMING
26

String Operations

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Slice a String

sample_str = 'Python String'


print (sample_str[3:5]) #return a range of character
# ho
print (sample_str[7:]) # return all characters from index 7
# String
print (sample_str[:6]) # return all characters before index 6
# Python
print (sample_str[7:-4])
# St
PYTHON PROGRAMMING
27

String Operations

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


String Membership Test String comparison
>>> 'a' in 'program'
True
You can use ( > , < , <= , <= , == , != ) to compare two strings.
>>> 'at' not in 'battle'
False Python compares string lexicographically i.e using ASCII value
of the characters.

str1="Hello"
str2="Hello"
str3="HELLO"
print(str1 == str2)
print(str1 == str3)
Output:
True
False
PYTHON PROGRAMMING
28
Built in functions using strings
String Upper()

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Python string method upper() returns a copy of the string in which all case-based characters
have been uppercased.
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower()

Output
this is string example....wow!!!
String Lower ()
Python string method lower() returns a copy of the string in which all case-based characters
have been lowercased.
str = "THIS IS STRING EXAMPLE....WOW!!!";
print str.lower()

Output
this is string example....wow!!!
PYTHON PROGRAMMING
29
Built in functions using strings
string_name.islower()

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


islower() is used to check if string_name string is in lowercase or not. This functions returns a boolean value
as result, either True or False.

>>> print ("hello, world".islower())


Output
True

string_name.isupper()

isupper() is used to check if the given string is in uppercase or not. This function also returns a boolean
value as result, either True or False.

>>> print ("HELLO, WORLD".isupper());


Output
True
PYTHON PROGRAMMING
30
Built in functions using strings

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


String len()

Python string method len() returns the length of the string.


Syntax : len( str )

Example
>>> s = "Hello"
>>> print (len(s))
Output
Length of the string: 5
PYTHON PROGRAMMING
31
Built in functions using strings

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


string_name.replace(old_string, new_string)

replace() function will first of all take a string as input, and ask for some subString within
it as the first argument and ask for another string to replace that subString as the second
argument. For Example,

>>> print ("Hello, World".replace("World", "India"));


Output
Hello, India
PYTHON PROGRAMMING
32
Built in functions using strings

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


String Join()

Python string method join() returns a string in which the string elements of sequence have
been joined by str separator.
Syntax: str.join(sequence)

s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
Output:
a-b-c
PYTHON PROGRAMMING
33
Built in functions using strings

E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE


Python String split()
txt = "welcome to the jungle"
x = txt.split()
print(x)
output:
['welcome', 'to', 'the', 'jungle']

string traversing.

fruit = "fruit"
index = 0
while index < len(fruit):
letter = fruit[index]
print(letter)
index = index + 1
E.RAJALAKSHMI-RAAK ARTS AND SCIENCE COLLEGE
34
PYTHON PROGRAMMING

You might also like