0% found this document useful (0 votes)
11 views36 pages

Unit 2 - TCS-102 Notes

This document provides an overview of Python programming, including its history, features, and applications. It covers basic concepts such as syntax, variables, data types, string manipulation, and input/output functions. Additionally, it includes instructions for installing Python and running simple programs.

Uploaded by

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

Unit 2 - TCS-102 Notes

This document provides an overview of Python programming, including its history, features, and applications. It covers basic concepts such as syntax, variables, data types, string manipulation, and input/output functions. Additionally, it includes instructions for installing Python and running simple programs.

Uploaded by

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

Unit 2: Python Basics and Functions

Python and It’s History


Python is a fairly old language created by Guido Van Rossum. The design began in the late 1980s and was
first released in February 1991.
In late 1980s, Guido Van Rossum was working on the Amoeba distributed operating system group. He wanted
to use an interpreted language like ABC (ABC has simple easy-to-understand syntax) that could access the
Amoeba system calls. So, he decided to create a language that was extensible. This led to design of a new
language which was later named Python.
Rossum was fan of a comedy series from late seventies. The name "Python" was adopted from the same series
"Monty Python's Flying Circus".
Features of Python Programming
1. Easy to Learn
Python has a very simple and elegant syntax. It's much easier to read and write Python programs compared
to other languages like: C++, Java, C#. Python makes programming fun and allows you to focus on the
solution rather than syntax.
2. Free and open-source
You can freely use and distribute Python, even for commercial use. Not only can you use and distribute
software written in it, you can even make changes to the Python's source code.
Python has a large community constantly improving it in each iteration.
3. Portability
You can move Python programs from one platform to another, and run it without any changes. It runs
seamlessly on almost all platforms including Windows, Mac OS X and Linux.
4. Extensible and Embeddable
Suppose an application requires high performance. You can easily combine pieces of C/C++ or other
languages with Python code.
This will give your application high performance as well as scripting capabilities which other languages
may not provide out of the box.
5. A high-level, interpreted language
Unlike C/C++, you don't have to worry about daunting tasks like memory management, garbage collection
and so on.
Likewise, when you run Python code, it automatically converts your code to the language your computer
understands. You don't need to worry about any lower-level operations.
6. Large standard libraries to solve common tasks
Python has a number of standard libraries which makes life of a programmer much easier since you don't
have to write all the code yourself. For example: Need to connect MySQL database on a Web server? You
can use MySQLdb library using import MySQLdb .
Standard libraries in Python are well tested and used by millions of people across the globe.
7. Object-oriented
Everything in Python is an object. Object oriented programming (OOP) helps you solve a complex
problem naturally.
With OOP, the complex problems can be divided into smaller sets by creating objects.
Applications of Python
• Web Applications
• Scientific and Numeric Computing
• Creating software Prototypes
• Good Language to Teach Programming
Reasons to Choose Python as First Language
1. Simple Elegant Syntax
Programming in Python is fun. It's easier to understand and write Python code. Why? The syntax feels natural.
Take this source code for an example:
a=2
b=3
sum = a + b
print(sum)
Even if you have never programmed before, you can easily guess that this program adds two numbers and
prints it.
2. Not overly strict
You don't need to define the type of a variable in Python. Also, it's not necessary to add semicolon at the end
of the statement.
Python enforces you to follow good practices (like proper indentation). These small things can make learning
much easier for beginners.
3. Expressiveness of the language
Python allows you to write programs having greater functionality with fewer lines of code. Here's a link to
the source code of Tic-tac-toe game with a graphical interface and a smart computer opponent in less than
500 lines of code. This is just an example. You will be amazed how much you can do with Python once you
learn the basics.
Install and Run Python in Windows
1. Go to Download Python page on the official site and click Download Python latest version (You may see
different version name).
2. When the download is completed, double-click the file and follow the instructions to install it. When
Python is installed, a program called IDLE is also installed along with it. It provides graphical user
interface to work with Python.
3. Open IDLE, copy the following code below and press enter.
print("Hello, World!")

4. To create a file in IDLE, go to File > New Window (Shortcut: Ctrl+N).


5. Write Python code (you can copy the code below for now) and save (Shortcut: Ctrl+S) with .py file
extension like: hello.py or your-first-program.py
6. Go to Run > Run module (Shortcut: F5) and you can see the output. Congratulations, you've successfully
run your first Python program.
Your First Python Program
Often, a program called "Hello, World!" is used to introduce a new programming language to beginners. A
"Hello, World!" is a simple program that outputs "Hello, World!".
However, Python is one of the easiest language to learn, and creating "Hello, World!" program is as simple
as writing print("Hello, World!"). So, we are going to write a different program.

Program to Add Two Numbers


# Add two numbers
num1 = 3
num2 = 5
sum = num1+num2
print(sum)

How this program works?


Line 1: # Add two numbers
Any line starting with # in Python programming is a comment.
Comments are used in programming to describe the purpose of the code. This helps you as well as other
programmers to understand the intent of the code. Comments are completely ignored by compilers and
interpreters.
Line 2: num1 = 3
Here, num1 is a variable. You can store a value in a variable. Here, 3 is stored in this variable.
Line 3: num2 = 5
Similarly, 5 is stored in num2 variable.
Line 4: sum = num1+num2
The variables num1 and num2 are added using + operator. The result of addition is then stored in another
variable sum.
Line 5: print(sum)
The print() function prints the output to the screen. In our case, it prints 8 on the screen.
Python Indentations
Where in other programming languages the indentation in code is for readability only, in Python the
indentation is very important. Python uses indentation to indicate a block of code.
Instead of curly braces { }, indentations are used to represent a block.
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
if 5 > 2:
print("Five is greater than two!")

Comments
Programming reflects programmer’s way of thinking in order to describe the single step’s that were followed
to solve a problem using a Computer. Commenting helps the programmers to explain the thought process
involved, and helps the programmer and others to understand the intention of the code. This allows one to
easily find errors, to fix them, to improve the code later on, and to reuse it in other applications as well.
• Single line Comment: Single line Comment(s) in Python are written starting with # (hash)
character
# Program to read two numbers and
# display it to the screen
Y=25//2 # finds the integer division
• Multiline Comments: Single line Comment(s) in Python are written in """ quotes.
"""
Write a Python Program to read two numbers and display the remainder to the screen after dividing the
first number by second.
"""
Python Keywords
Keywords are the reserved words in Python.
We cannot use a keyword as a variable name, function name or any other identifier. They are used to define
the syntax and structure of the Python language.

In Python, keywords are case sensitive.


There are 35 keywords in Python 3.10.5. This number can vary slightly in the course of time.
All the keywords except True, False and None are in lowercase and they must be written as it is. The list of
all the keywords is given below.

False class from or


None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not

Python Variables
• Creating Variables
Unlike other programming languages, Python has no command for declaring a variable. A variable is created
the moment you first assign a value to it.
x=5
y = "John"
print(x) #5
print(y) #John

Variable Names/Rules for writing identifiers


A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)

▪ Output Variables
The Python print statement is often used to output variables.
To combine both text and a variable, Python uses the + character:
i)
x = "Python"
ver="3.10.5"
print("Version of “ + x +” is "+ ver))
Output: Version of Python is 3.10.5
ii)
x = "Python is "
y = "awesome"
z=x+y
print(z)
O/P: Python is awesome

iii)
x=5
y = "John"
print(x + y)
O/P: TypeError: unsupported operand type(s) for +: 'int' and 'str

iv)
a, b, c = 5, 3.2, "Hello"
print (a)
print (b)
print (c)
O/P:
5
3.2
Hello

Python Numbers
There are three numeric types in Python:
• int
• float
• complex

x=1
print(type(x)) # int
y = 2.8
print(type(x)) # float
z = 1j
print(type(x)) # complex

int
x=1
y = 35656222554887711
z = -3255522

float
x = 1.10
y = 1.0
z = -35.59
x = 35e3 is equivalent of 35×103
y = 12E4 is equivalent of 12×104
z = -87.7e100 is equivalent of 87.7×10 100

Complex
x = 3+5j
print(x) => 3+5j
print(x.real) => 3.0
print(x.imag) => 5.0

y = 5j
print(y.real) => 0.0
print(y.imag) => 5.0

z = -5j
print(z.real) => 0.0
print(x.imag) => -5.0
Python Casting
Sometimes you may need to assign a specific type to a variable. This process is called casting. Since Python
is an object-oriented language, it uses classes to define data types—even for its basic types.
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by rounding down to the
previous whole number), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string literal (providing
the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer literals and
float literals

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

x = float(1) # x will be 1.0


y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

x = str("s1") # x will be 's1'


y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is
the same as "hello".
Strings can be output to screen using the print function. For example: print("hello").
Like many other popular programming languages, strings in Python are arrays of bytes representing unicode
characters. However, Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.
a = "Hello, World!"
print(a[1])
O/P: e
Strings are immutable
In Python, strings are immutable, which means:
• Once a string object is created, its contents cannot be changed.
• Any operation that looks like it’s modifying a string (e.g., concatenation, replace, slicing
assignment) actually creates a new string object in memory.
Example:
s = "hello"
print(id(s)) # prints the memory address of "hello"
s = s + " world"
print(s) # "hello world"
print(id(s)) # prints different memory address i.e. of new string s

Slicing:
Extracting a Substring from the existing string by specifying the index.
Slicing syntax
string[ start : end : step]
• start → index where slicing begins (default = 0)
• end → index where slicing stops (exclusive)
• step → interval (default = 1)
Examples:
s = "Python Programming"
1. Basic slicing
print(s[0:6]) # Output: Python (from index 0 to 5)
print(s[:6]) # Output: Python (start default = 0)
print(s[7:]) # Output: Programming (till end)
2. Negative indexing
print(s[-11:-1]) # Output: Programmin (counting from end)
print(s[-7:]) # Output: mming
3. Using step
print(s[::2]) # Output: Pto rgamn (every 2nd char)
print(s[1::2]) # Output: yhnPormig (every 2nd char starting at index 1)
4. Reversing a string
print(s[::-1]) # Output: gnim margorP nohtyP
5. Extracting substrings
print(s[0:6]) # "Python"
print(s[7:18]) # "Programming"
Length of a string:
The len() method returns the length of a string:
a = "Hello, World!"
print(len(a))

String Manipulation Operations:


lower():
The method returns the string in lower case.
a = "Hello, World!"
print(a.lower())
O/P: hello, world!
upper():
The method returns the string in upper case.
a = "Hello, World!"
print(a.upper())
O/P: HELLO, WORLD!
replace() :
method replaces a string with another string.
a = "Hello, World!"
print(a.replace("H", "J"))
O/P: Jello, World!
s = "Python Programming"
index= s.find("Prog") #7
index= s.find("A") # -1
capitalize():
• Makes the first character uppercase and the rest lowercase.
• Works on the whole string, not word by word.
s = "python programming"
print(s.capitalize()) # Output: "Python programming"
title():
Makes the first letter of every word uppercase and the rest lowercase.
s = "python programming language"
print(s.title()) # Output: "Python Programming Language"
Input/Output Functions:
Reading an input from the user. Python provides a built-in function called input that gets input from the
keyboard. When this function is called, the program stops and waits for the user to type something. When the
user presses Return or Enter, the program resumes and input returns what the user typed as a string ie ‘str’
type.

inp = input() #String “It’s a great way” is given as input


print(inp)
O/P: It’s a great way

print statement:
A statement is a unit of code that the Python interpreter can execute. print is an executable statement. When
print statement is typed in interactive mode, the interpreter executes it and displays the result, if there is one.
Ex.
name = "Prashant"
age = 25
print(f"My name is {name} and I am {age} years old.")
or
print("My name is {} and I am {} years old.".format(name, age))
or
print("My name is %s and I am %d years old." % (name, age))
In above cases the output remains the same.
#Output: My name is Prashant and I am 25 years old.

Ex. ff=56.78943
print("Value of ff is %0.2f" % (ff))
#Output: Value of ff is 56.79
Ex. A string can be passed to be displayed to the user before pausing for input:
name = input('What is your name?\n') # “Kiran” is passed as input
print(name)
O/P: Kiran
Ex.. Two add two numbers by accepting from the user
num1=input(‘Enter the first number:’)
num2=input(‘Enter the second number:’)
sum =int(num1)+int(num2)
print(‘The sum is :’ , sum)
Ex
x = "Python"
ver="3.10.5"
print("Version of {} is {} ".format(x , ver))
Output: Version of Python is 3.10.5
Ex
x=10
y=78.976467
print(f”{x} , {y:0.2f}”)
O/P: 10 , 78.98

Python Operators
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
1. Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Opera Name Example
tor

+ Addition x+y

- Subtraction x-y

* Multiplication x*y

/ Division x/y

% Modulus x%y

** Exponentiation x ** y

// Floor division x // y

2. Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

3. Python Comparison Operators


Comparison operators are used to compare two values:

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

4. Python Logical Operators


Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements are true x < 5 and x < 10
Short-
Circuit
or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result not(x < 5 and x < 10)
is true
Evaluation of Logical Expressions
Python processes a logical expression such as x >= 2 and (x/y) > 2, by evaluating the expression from left to
right. When Python detects that there is nothing to be gained by evaluating the rest of a logical expression, it
stops its evaluation and does not do the computations in the rest of the logical expression. When the evaluation
of a logical stops because the overall value is already known, it is called short-circuiting the evaluation.

The short-circuit behaviour leads to a clever technique called the guardian pattern. Consider the following
code sequence in the Python interpreter:

>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
O/P: True

>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
O/P: False

>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero
5. Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same
object, with the same memory location:

Operator Description Example

is Returns true if both variables are the same x is y


object

is not Returns true if both variables are not the x is not y


same object

x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z) # returns True because z is the same object as x
print(x is y) # returns False because x is not the same object as y, even if they have thew same content
print(x == y) # to demonstrate the difference betweeen "is" and "==": this comparison returns True
because x is equal to y
O/P:
True
False
True

x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z) # returns False because z is the same object as x
print(x is not y) # returns True because x is not the same object as y, even if they have the same content
print(x != y) # to demonstrate the difference between "is not" and "!=": this comparison returns False
because x is equal to y
O/P:
False
True
False

6. Python Membership Operators


Membership operators are used to test if a sequence is presented in an object:

Operator Description Example

in Returns True if a sequence with the specified x in y


value is present in the object

not in Returns True if a sequence with the specified x not in y


value is not present in the object

x = ["apple", "banana"]
print("banana" in x) # returns True because a sequence with the value "banana" is in the list
O/P: True

x = ["apple", "banana"]
print("pineapple" not in x) # returns True because a sequence with the value "pineapple" is not in the
list
O/P: True

7. Bitwise Operators

• These operators are used to perform logical operation (and, or, not) on individual bits of a binary
number.

• There are 6 bitwise operators:


Operators Meaning of operators
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ Bitwise complement
<< Shift left
>> Shift right
Truth Table
A B A&B A|B A^B ~A
0 0 0 0 0 1
0 1 0 1 1 1
1 0 0 1 1 0
1 1 1 1 0 0

Ex: for ~ (bitwise complement)


a = 12 = 00001100
~a= 11110011

Ex: for & (bitwise AND)


a= 12 = 00001100
b= 15 = 00001111
a & b = 00001100

Ex: for | (bitwise OR)


a= 12 = 00001100
b= 15 = 00001111
a | b = 00001111

Ex: for ^ (bitwise XOR)


a= 12 = 00001100
b= 15 = 00001111
a ^ b = 00000011
• The operator that is used to shift the data by a specified number of bit positions towards left or right is
called shift operator.

• The syntax is shown below for <<


b=a << num, where a is value to be shifted and num is number of bits to be shifted.

• The syntax is shown below for >>


b=a >> num, where a is value to be shifted and num is number of bits to be shifted.

Ex: for <<(left shift):


a = 13 #after binary conversion- 0000 1101
b = a<<1
After 1 bit shift to the left, the answer in binary is 0001 1010
Ex: for >>(right shift):
a = 13 #after binary conversion- 0000 1101
b = a<<1
After 1 bit shift to the left, the answer in binary is 0000 0110
CONTROL FLOW:
Conditional execution
Conditional statements allow checking the conditions and changing the behaviour of the
program accordingly.
The simplest form is the if statement:
if x > 0 :
print('x is positive')

The boolean expression after the if statement is called the condition. The if statement with a
colon character (:) and the line(s) after the if statement are indented (as indicated by the arrow
tab spacing).
The statement consists of a header line that ends with the colon character (:) followed by an
indented block. These statements are called compound statements because they stretch across
more than one line.
There is no limit on the number of statements that can appear in the body, but there must be at
least one. If body has no statements, then pass statement may be used, which does nothing.
For Example:
x=100
if x>99:
x=x+500
if x < 101 and x>99:
y=x+100
x=x-50
x=x+y
print(x)
OUTPUT:
600

Alternative Execution
A second form of if statement is alternative execution, in which there are two possibilities
and the condition determines which one gets executed. The syntax looks like this:
if x%2 == 0:
print('x is even')
else:
print('x is odd')

Ex. Write a program in python to accept an integer from the user and determine whether its
even or odd.
Solution:
num=input('Input a number:') num=int(num)
if(num!=0):
if num%2!=0:
print(num,'is an Odd number')
else:
print(num,'is an Even number')

Chained Conditional Constructs


If there are more than two possibilities and we need more than two branches. This can be
done by chained conditional:
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')

elif is an abbreviation of “else if”. There is no limit on the number of elif statements.

Example:
Write a program in python to accept an integer from the user and determine whether its
positive, negative or zero.
Solution:
num=input('Input a number:') num=int(num)
if num >0:
print(num,' is a positive number')
elif num<0:
print(num,’ is a negative number')
else:
print(num,’ is zero')

Nested Conditional Satements:


A condition can also be nested within another condition. The three-branch examples could be
written as:
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Example:
Write a program in python to accept three integers from the user and determine the largest of
the three.
n1=input('Input the first number:')
n1=int(n1)
n2=input('Input the second number:')
n2=int(n2)
n3=input('Input the third number:')
n3=int(n3)
if n1>n2:
if n1>n3:
print(n1, ' is the largest')
else:
print(n3, ' is the largest')
elif n2>n3:
print(n2, ' is the largest')
else:
print(n3, ' is the largest')

Match-case
What is Match-Case?

• Match-case is a new feature introduced in Python 3.10 for pattern matching.


• It simplifies complex conditional logic.

Syntax:

match value:
case pattern1:
# Code to execute if value matches pattern1
case pattern2:
# Code to execute if value matches pattern2
case _:
# Default case (if no patterns match)
# Default case (if no patterns match)

Example:

status = 404

match status:
case 200:
print("Success!")
case 404:
print("Not Found")
case _:
print(“Unknown Status”)

Python Loops
Python has two primitive loop commands:
1. while loop:
Syntax for while loop:
while (expression):
statement(s)

# Python program to illustrate while loop


count = 0
while (count < 3):
count = count + 1
print("Graphic Era Hill University")

2. for loop:
Syntax:
for variable_name in sequence:
Statement(s)

Example:
S= “Hello”
for i in S:
print(i)
Output:
H
e
l
l
o

range function:
Syntax:
range(start, stop, step)
where The start and step arguments are optional.
Example1:
# create a sequence from 0 to 3 (4 is not included)
for i in range(4):
print(i)
Output:
0
1
2
3

Example2:
for i in range(1,5):
print(i)
Output:
1
2
3
4

Example3:
for i in range(1,10,2):
print(i)
Output:
1
3
5
7
9

break statement: break statement is used to exit a loop based on certain condition.
for i in range(10):
print(i)
if i == 2:
break

Output:
0
1
2

# Python program to demonstrate break statement using for loop


s = 'Graphic Era Hill University' # Using for loop
for letter in s:
print(letter)
# break the loop as soon it sees 'e' # or 'a'
if letter == 'e' or letter == 'a':
break
print("Out of for loop" )

Continue statement: The continue statement skips the current iteration of the loop and the
control flow of the program goes to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)

Output:
0
1
2
4

pass statement: The Python pass statement is a null statement. But the difference between
pass and comment is that comment is ignored by the interpreter whereas pass is not ignored.
n = 10
for i in range(n):
pass

Built-in functions
In the context of programming, a function is a set statements grouped under a name that
performs a specific task. When a function is defined, first name is specified and then the set or
sequence of statements. Function is called by its name.
type(32)
O/P: <class 'int'>
The name of the function is type(). The expression in parentheses is called the argument of the
function. The argument is a value or variable that we are passing into the function as input to
the function. The result, for the type function, is the type of the argument. The result sent back
by the function is called the return value.

The max() and min() functions give us the largest and smallest values in a list, respectively:
print ( max('Hello world') )
O/P: 'w'
print ( min('Hello world') )
O/P: ' '

The max() function tells us the “largest character” in the string (which turns out to be the letter
“w”) and the min() function shows us the smallest character (which turns out to be a space).
A very common built-in function is the len() function which tells how many items are in its
argument. If the argument to len() is a string, it returns the number of characters in the string.
print(len('Hello world'))
O/P: 11

Type conversion functions


Python also provides built-in functions that convert values from one type to another. The int
function takes any value and converts it to an integer, if it can, or displays an error otherwise:
int('32')
O/P: 32
int('Hello')
O/P: ValueError: invalid literal for int() with base 10: 'Hello'

int(-2.3)
O/P: -2
Rounds by chopping the fractional part.

float converts integers and strings to floating-point numbers:


float(32)
O/P: 32.0
float('3.14159')
O/P: 3.14159

Finally, str converts its argument to a string.


str(32)
O/P: '32'
str(3.14159)
O/P: '3.14159'

User Defined Functions


• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.

Creating a Function
In Python a function is defined using the def keyword:
EXAMPLE:
# A simple Python function
def fun():
print("Welcome to Graphic Era")

RULES FOR DEFINING FUNCTION IN PYTHON


• Function blocks begin with the keyword def followed by the function name and
parentheses (()).
• Any input parameters or arguments should be placed within these parentheses. We also
define parameters inside these parentheses.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an
expression to the caller.
• A return statement with no arguments is the same as return None.

FUNCTION SYNTAX
1. Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python
followed by parenthesis containing parameters of that particular function.
EXAMPLE:
# Defining function print_str(str1)
#This function prints the string being passed as an argument
def print_str(str1):
print(str1)
return

# Calling user-defined function


print_str("Calling the user defined function”)

2. Parameters in function
The information into the functions can be passed as the parameters. The parameters are
specified in the parentheses. We can give any number of parameters separated by comma.
Example 1: # A simple Python function to check whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)
Output:
Even
Odd

Example 2: #Full Pyramid Patterns in Python using Loop


def full_pyramid(n):
for i in range(1, n + 1):
# Print leading spaces
for j in range(n - i):
print(" ", end="")
# Print asterisks for the current row
for k in range(1, 2*i):
print("*", end="")

Example3: #Reverse the words in the given string program.


# input string
string = "Graphic Era Hill University"
# reversing words in a given string
s = string.split()[::-1]
l = []
for i in s:
# appending reversed words to l '
l.append(i)
# printing reverse words
print(" ".join(l))

Example 4: #Count all letters, digits, and special symbols from a given string
def find_digits_chars_symbols(sample_str):
chr_count = 0
digit_count = 0
symbol_count = 0
for chr in sample_str:
if chr.isalpha():
chr_count += 1
elif chr.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1
print("Chars =", chr_count, "Digits =", digit_count, "Symbol =", symbol_count)
sample_str = "Gra@phic2Era&#Hi5ll@univer&$sity"
print("total counts of chars, Digits, and symbols \n")
find_digits_chars_symbols(sample_str)

Example 5: # Python function to return sum and multiplication of two numbers


def cal(a,b):
sum=a+b
mul=a*b
return sum,mul
# Driver code to call the function
a=int(input(“Enter first number: ”))
b= int(input(“Enter second number: ”))
c,d=cal(a,b)
print(f”Sum of {a} and {b} is {c} and multiplication is {d}”)

Output:
Enter first number: 5
Enter second number: 6
Sum of 5 and 6 is 11 and multiplication is 30

Example 6: # Python function to return multiple values


#Python program to swap two numbers
def swap(x,y):
t=x
x=y
y=t
return x,y
a=int(input(Enter the value of a:”))
b=int(input(Enter the value of b:”))
num1,num2=swap(a,b)
print(“Swapped numbers are {0} and {1}”.format(num1,num2))

3. Functions without return

• All functions in Python have a return value, even if no return line inside the code
• Functions without a return return the special value None
• None is a special constant in the language
• None is used like NULL, void, or nil in other languages
• None is also logically equivalent to False
• The interpreter’s REPL(Read-Eval-Print loops) doesn’t print None

Function Arguments & Return Values

Functions can take parameters and return values.

Types of Arguments:

1. Positional Arguments

def add(a, b):


return a + b

print(add(5, 3)) # Output: 8


2. Default Arguments

def greet(name="Guest"):
return f"Hello, {name}!"
def student(name, age):
print(f"Name: {name},
print(greet()) Age:
# Output: {age}")
Hello, Guest!

student(age=20, name="Bob")

3. Keyword Arguments

Lambda Functions in Python

Lambda functions are anonymous, inline functions.

Syntax:

square = lambda x: x * x
print(square(4)) # Output: 16

Recursion in Python

A function calling itself to solve a problem.


Example: Factorial using Recursion:
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
else:
# Recursive case
return n * factorial(n - 1)
print(factorial(5)) # Output: 120

Built-in modules
1. random module
Given the same inputs, most computer programs generate the same outputs every time, so they
are said to be deterministic. In determinism, it’s expected that the same calculation yield’s the
same result. For some applications, though, the computer needs to be unpredictable. Games are
an obvious example, but there are more.
The function random returns a random float between 0.0 and 1.0 (including 0.0 but not 1.0).
Each time random is called, the next number is generated in a long series. The following
program produces the following list of 10 random numbers between 0.0 and up to but not
including 1.0:
import random
for i in range(10):
x = random.random()
print(x)
The function randint takes the parameters low and high, and returns an integer between low
and high (including both).

random.randint(5, 10)
O/P: 5
random.randint(5, 10)
O/P: 9

To choose an element from a sequence at random, you can use choice:


t = [1, 2, 3]
random.choice(t)
O/P: 2

random.choice(t)
O/P: 3

2. math module
Python has a math module that provides most of the familiar mathematical functions. Before
using the module, it must be imported:
import math
This statement creates a module object named math. If you print the module object, you get
some information about it:
print(math)
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module. To access one
of the functions, specify the name of the module and the name of the function, separated by a
dot (also known as a period). This format is called dot notation.
ratio = signal_power/noise_power
decibels = 10 * math.log10(ratio)

radians = 0.7
height = math.sin(radians)

The first example computes the logarithm base 10 of the signal-to-noise ratio. The math module
also provides a function called log that computes logarithms base e. The second example finds
the sine of radians. The name of the variable is a hint that sin and the other trigonometric
functions (cos, tan, etc.) take arguments in radians. To convert from degrees to radians, divide
by 360 and multiply by 2:
degrees = 45
radians = degrees / 360.0 * 2 * math.pi
math.sin(radians)
O/P: 0.7071067811865476

The expression math.pi gets the variable pi from the math module. The value of this variable
is an approximation of pi, accurate to about 15 digits.

Custom Modules
You can create your own modules by saving Python code in a .py file. You can then import
and use them in other scripts.
# mymodule.py
def greet(name):
return f"Hello, {name}! Welcome to Python modules."

def add(a, b):


return a + b

pi = 3.14159
# main.py
import mymodule # importing our custom module

# Using functions from mymodule


print(mymodule.greet("Alice"))
print("Sum of 5 and 7 is:", mymodule.add(5, 7))
print("Value of pi is:", mymodule.pi)

Output:
Hello, Alice! Welcome to Python modules.
Sum of 5 and 7 is: 12
Value of pi is: 3.14159

Exception Handling Basics

This is a mechanism to handle errors that occur during program execution.

• try-except block: Code that might raise an exception is placed in the try block. If an
exception occurs, the code in the corresponding except block is executed.
• finally block: This block is always executed, whether an exception occurred or not.

Example:
try:
num = 10 / 0
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
finally:
print("This code always runs.")

You might also like