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

Chap2

Chapter 2 discusses errors and exceptions in Python, differentiating between syntax errors and logical errors (exceptions), and introduces the try-except block for handling exceptions. It also covers functions, including standard and user-defined functions, their declaration, calling, and the use of arguments, default arguments, and variable-length arguments with *args and **kwargs. Additionally, the chapter explains string operations, escape sequences, formatting, and various string methods.

Uploaded by

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

Chap2

Chapter 2 discusses errors and exceptions in Python, differentiating between syntax errors and logical errors (exceptions), and introduces the try-except block for handling exceptions. It also covers functions, including standard and user-defined functions, their declaration, calling, and the use of arguments, default arguments, and variable-length arguments with *args and **kwargs. Additionally, the chapter explains string operations, escape sequences, formatting, and various string methods.

Uploaded by

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

Chapter – 2

Errors and Exceptions:


Errors are the problems in a program due to which the program will stop the execution. On
the other hand, exceptions are raised when some internal events occur which changes the
normal flow of the program.
Two types of Error occurs in python.
1. Syntax errors
2. Logical errors (Exceptions)
Syntax errors
When the proper syntax of the language is not followed then a syntax error is thrown.

# initialize the amount variable


amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")

logical errors:
When in the runtime an error that occurs after passing the syntax test is called exception or
logical type. For example, when we divide any number by zero then the ZeroDivisionError
exception is raised, or when we import a module that does not exist then ImportError is
raised.
# initialize the amount variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)

Exceptions:
An exception is an unexpected event that occurs during program execution.
Try and except block:
we have placed the code that might generate an exception inside the try block. Every
try block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used
without the try block.
Syntax:
try:
# code that may cause exception
except:
# code to run when exception occurs
else block: In some situations, we might want to run a certain block of code if the code block
inside try runs without any errors.
For these cases, you can use the optional else keyword with the try statement.
finally block: the finally block is always executed no matter whether there is an exception or
not.
The finally block is optional. And, for each try block, there can be only one finally block.
2 BCA,
Dept. of computer science
KFGSC, Tiptur
Example:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print ("Error: Denominator cannot be 0.")
finally:
print ("This is finally block.")

Functions: A function is a block of code that performs a specific task.


Types of function
There are two types of function in Python programming:

 Standard library functions - These are built-in functions in Python that are available
to use.
 User-defined functions - We can create our own functions based on our
requirements.
Python Function Declaration
Syntax:
def function_name(arguments):
function body
return
Here,

 def - keyword used to declare a function


 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from aa’ function

example:
def greet():
print(“ hello “)

Calling a function:
Syntax:
def greet():
print(“hello”)
greet()

Here,
 When the function is called, the control of the program goes to the function definition.
 All codes inside the function are executed.
 The control of the program jumps to the next statement after the function call.

2 BCA,
Dept. of computer science
KFGSC, Tiptur
Function with arguments: As mentioned earlier, a function can also have arguments. An
argument is a value that is accepted by a function.
If we create a function with arguments, we need to pass the corresponding values while
calling them.

# function with two arguments


def add_numbers(num1, num2):
sum = num1 + num2
print("Sum: ",sum)

# function call with two values


add_numbers(5, 4)

The return statement: A Python function may or may not return a value. If we want our
function to return some value to a function call, we use the return statement.
Syntax:
def add_numbers():
………
return sum
example:
# function definition
def find_square(num):
result = num * num
return result

# function call
square = find_square(3)

print('Square:',square)

Output: Square: 9

Default arguments in python: In Python, we can provide default values to function


arguments.
We use the = operator to provide default values.

def add_numbers( a = 7, b = 8):


sum = a + b
print('Sum:', sum)
# function call with two arguments
add_numbers(2, 3)
# function call with one argument
add_numbers(a = 2)
# function call with no arguments
add_numbers()
2 BCA,
Dept. of computer science
KFGSC, Tiptur
output
sum: 5
sum: 10
sum: 15

args and keyword arguments: In Python, we can pass a variable number of arguments to a
function using special symbols. There are two special symbols:
1. *args (Non Keyword Arguments)
2. **kwargs (Keyword Arguments)

args:We use *args and **kwargs as an argument when we are unsure about the number of
arguments to pass in the functions.
Python has *args which allow us to pass the variable number of non keyword arguments to
function.
In the function, we should use an asterisk * before the parameter name to pass variable length
arguments.The arguments are passed as a tuple and these passed arguments make tuple inside
the function with same name as the parameter excluding asterisk *
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)

output
Sum: 8
Sum: 22
Sum: 17

Keyword arguments: Python passes variable length non keyword argument to function
using *args but we cannot use this to pass keyword argument. For this problem Python has
got a solution called **kwargs, it allows us to pass the variable length of keyword arguments
to the function.
In the function, we use the double asterisk ** before the parameter name to denote this type
of argument. The arguments are passed as a dictionary and these arguments make a
dictionary inside function with name same as the parameter excluding double asterisk **.

def intro(**data):
print("\nData type of argument:",type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)
intro(Firstname="John", Lastname="Wood", Email="[email protected]",
Country="Wakanda", Age=25, Phone=9876543210)
2 BCA,
Dept. of computer science
KFGSC, Tiptur
output
Data type of argument: <class 'dict'>
Firstname is Sita
Lastname is Sharma
Age is 22
Phone is 1234567890

Data type of argument: <class 'dict'>


Firstname is John
Lastname is Wood
Email is [email protected]
Country is Wakanda
Age is 25
Phone is 9876543210

Command line arguments: The arguments that are given after the name of the Python script
are known as Command Line Arguments and they are used to pass some information to the
program.
Recursive function: a function can call other functions. It is even possible for the function to
call itself. These types of construct are termed as recursive functions.
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

Output
The factorial of 3 is 6

Scope of variables in python: we can declare variables in three different scopes: local scope,
global, and nonlocal scope.
Based on the scope, we can classify Python variables into three types:

1. Local Variables
2. Global Variables
3. Nonlocal Variables

2 BCA,
Dept. of computer science
KFGSC, Tiptur
Local variables: When we declare variables inside a function, these variables will have a
local scope (within the function). We cannot access them outside the function.

These types of variables are called local variables.

def greet():

# local variable
message = 'Hello'
print('Local', message)

greet()

# try to access message variable


# outside greet() function
print(message)
global variables: a variable declared outside of the function or in global scope is known as a
global variable. This means that a global variable can be accessed inside or outside of the
function.
# declare global variable
message = 'Hello'

def greet():
# declare local variable
print('Local', message)

greet()
print('Global', message)

nonlocal variables: nonlocal variables are used in nested functions whose local scope is not
defined. This means that the variable can be neither in the local nor the global scope.

We use the nonlocal keyword to create nonlocal variables.


# outside function
def outer():
message = 'local'
# nested function
def inner():
# declare nonlocal variable
nonlocal message
message = 'nonlocal'
print("inner:", message)
2 BCA,
Dept. of computer science
KFGSC, Tiptur
inner()
print("outer:", message)
outer()
Strings: a string is a sequence of characters. For example, "hello" is a string containing a
sequence of characters 'h', 'e', 'l', 'l', and 'o'
create a string using double quotes
string1 = "Python programming"
create a string using single quotes
string1 = 'Python programming'
Here, we have created a string variable named string1. The variable is initialized with the
string Python Programming.
create string type variables
name = "Python"
print(name)
message = "I love Python."
print(message)
Accessing string characters:
We can access the characters in a string in three ways.

1. Indexing: One way is to treat strings as a list and use index values.
greet = 'hello'
access 1st index element
print(greet[1]) # "e"

2. Negative Indexing: Similar to a list, Python allows negative indexing for its strings
greet = 'hello'
Access 4th last element
print(greet[-4]) # "e"

3. Slicing: Access a range of characters in a string by using the slicing operator colon :
greet = 'Hello'
Access character from 1st index to 3rd index
print(greet[1:4]) # "ell"

Multiline string:
We can also create a multiline string in Python. For this, we use triple double quotes """
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)

Operations on strings:
Compare Two Strings
We use the == operator to compare two strings. If two strings are equal, the operator
returns True. Otherwise, it returns False.

2 BCA,
Dept. of computer science
KFGSC, Tiptur
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)# compare str1 and str3
print(str1 == str3)

Join Two or More Strings


In Python, we can join (concatenate) two or more strings using the + operator.
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)

Output: Hello, Jack

Iterate through string


We can iterate through a string using a for loop.
greet = 'Hello'
# iterating through greet string
for letter in greet:
print(letter)
string length: we use the len() method to find the length of a string.
greet = 'Hello'
# count length of greet string
print(len(greet))

Escape sequences in python:


escape double quotes
example = "He said, \"What's there?\""
escape single quotes
example = 'He said, "What\'s there?"'
print(example)

Output: He said, "What's there?"


Here is a list of all the escape sequences supported by Python.

Escape Sequence Description


\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed

2 BCA,
Dept. of computer science
KFGSC, Tiptur
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value HH

Formatting the strings: Python f-Strings make it really easy to print values and variables.
name = 'Cathy'
country = 'UK'
print(f'{name} is from {country}')

output
Cathy is from UK

Raw string and Unicode: a raw string is a special type of string that allows you to include
backslashes (\) without interpreting them as escape sequences.
Program to use raw strings
#Define string with r before quotes and assign to variable
s1 = r'Python\nis\easy\to\learn'
print(s1)

output
python\nis\easy\to\learn

Unicode: Unicode is also called Universal Character set. ASCII uses 8 bits(1 byte) to
represents a character and can have a maximum of 256 (2^8) distinct combinations.
The issue with the ASCII is that it can only support the English language but what if we
want to use another language like Hindi, Russian, Chinese, etc. We didn’t have enough
space in ASCII to covers up all these languages and emojis. This is where Unicode comes,
Unicode provides us a huge table to which can store ASCII table and also the extent to store
other languages, symbols, and emojis.In UTF-8 character can occupy a minimum of 8 bits
and in UTF-16 a character can occupy a minimum of 16-bits. UTF is just an algorithm that
turns Unicode into bytes and read it back
from __future__ import unicode_literals
example:
# creating variables to holds the letters in python word.
p = "\u2119"
y = "\u01b4"
t = "\u2602"
h = "\u210c"
o = "\u00f8"
n = "\u1f24"
# printing Python encoding to utf-8 from ascii
print(p+y+t+h+o+n).encode("utf-8")

Python string methods:


 lower(): Converts all uppercase characters in a string into lowercase
 upper(): Converts all lowercase characters in a string into uppercase

2 BCA,
Dept. of computer science
KFGSC, Tiptur
 title(): Convert string to title case
 swapcase(): Swap the cases of all characters in a string
 capitalize(): Convert the first character of a string to uppercase

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified
value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the
specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and
returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and
returns the position of where it was found
isalnum() Returns True if all characters in the string
are alphanumeric
isalpha() Returns True if all characters in the string
are in the alphabet
isascii() Returns True if all characters in the string
are ascii characters
isdecimal() Returns True if all characters in the string
are decimals
isdigit() Returns True if all characters in the string
are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string
are lower case
isnumeric() Returns True if all characters in the string
are numeric
isprintable() Returns True if all characters in the string
are printable
isspace() Returns True if all characters in the string
are whitespaces
istitle() Returns True if the string follows the rules
of a title
isupper() Returns True if all characters in the string
are upper case

2 BCA,
Dept. of computer science
KFGSC, Tiptur
join() Converts the elements of an iterable into a
string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in
translations
partition() Returns a tuple where the string is parted
into three parts
replace() Returns a string where a specified value is
replaced with a specified value
rfind() Searches the string for a specified value and
returns the last position of where it was
found
rindex() Searches the string for a specified value and
returns the last position of where it was
found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted
into three parts
rsplit() Splits the string at the specified separator,
and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator,
and returns a list
splitlines() Splits the string at line breaks and returns a
list
startswith() Returns true if the string starts with the
specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper
case and vice versa
title() Converts the first character of each word to
upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0
values at the beginning

2 BCA,
Dept. of computer science
KFGSC, Tiptur

You might also like