Chap2
Chap2
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.")
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,
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.
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
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
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.
def greet():
# local variable
message = 'Hello'
print('Local', message)
greet()
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.
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)
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")
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