0% found this document useful (0 votes)
9 views97 pages

Python Programming Basics and Concepts

Python is a simple, easy-to-learn programming language developed by Guido van Rossum in the late 1980s, with its source code available under the GNU General Public License. It features extensive libraries, is interpreted, and supports various programming paradigms, including procedural and object-oriented programming. The document covers Python's history, installation, variables, keywords, operators, identifiers, comments, constants, expressions, and provides examples of simple programs.

Uploaded by

drockyvi
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)
9 views97 pages

Python Programming Basics and Concepts

Python is a simple, easy-to-learn programming language developed by Guido van Rossum in the late 1980s, with its source code available under the GNU General Public License. It features extensive libraries, is interpreted, and supports various programming paradigms, including procedural and object-oriented programming. The document covers Python's history, installation, variables, keywords, operators, identifiers, comments, constants, expressions, and provides examples of simple programs.

Uploaded by

drockyvi
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

PYTHON P R O G R A M M I N G

Python is simple and easy to


learn fast

Python is an example of FLOSS


(Free/Libre and Open Source Software )
Portability

Extendable / Extensible
INTERPRETED

HUGE LIBRARIES
Python was developed by Guido van Rossum in the late
eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including
ABC, Modula-3, C, C++, Algol-68, SmallTalk, and Unix shell
and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now
available under the GNU General Public License (GPL).
Python is now maintained by a core development team at
the institute, although Guido van Rossum still holds a vital
role in directing its progress.
HISTORY OF PYTHON

Guido van Rossum created the Python programming language in the late 1980s. Python source code is available
under the GNU General Public License (GPL).

Implementation started - December, 1989

Internal releases at Centrum Wiskunde & Informatica – 1990


Python IDEs and Code Editors

A code editor is a tool that is used to write and edit code. They are usually
lightweight and can be great for learning. However, once your program gets larger,
you need to test and debug your code, that's where IDEs come in.

Python Integrated Development Environments (IDEs) are the software that


provides Python developers with a bundle of tools in a single environment rather than
installing separate packages of Python for different functionalities like auto-code
completion, syntax highlighting, code colouring, easy navigation, etc.

some of them are free to use so you can start using it as a beginner, and
become handy to use the enhanced and paid versions that are helpful while
working on larger projects. The more intelligence they have, the less work you
need on the code.
HOW TO INSTALL PYTHON
CLICK DOWNLOADS

DOWNLOADS
ith Python for
Dev
IDLE is Python's Integrated Development a n d Learning Environment
PYTHON VARIABLES
Variables are nothing but reserved memory locations to store values.
When you create a variable you reserve some space in memory.
In Python , a variable is seen as a tag that is tied to some value.
Example : num = 1
• Python consider the value as objects.
• Based on the data type of a variable, the interpreter allocates memory and decides what
can be stored in the reserved memory.
• By assigning different data types to variables, you can store integers, decimals or
characters in these variables.
• We do not need to declare variables before using them or declare their type.
PYTHON VARIABLES
Example
X = 10
Y= “ABC”
Z= 35.10
X=Y=Z= 20
A ,B,C = 2, 10.2 , “HELLO ”

Rules for creating variables in Python


•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 (name, Name and NAME are three different variables).
•The reserved words(keywords) cannot be used naming the variable.
Python Keywords
• Python Keywords are special reserved words which convey a special
meaning to the compiler/interpreter.
• Each keyword have a special meaning and a specific operation.
• These keywords can't be used as variable.

True False None and as


asset def class continue break
else finally elif del except
global for if from import
raise try or return pass
nonlocal in not is lambda
Python Operators

Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators

Operator Description Example


+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns remainder b%a=0

a**b =10 to the power


** Exponent Performs exponential (power) calculation on operators
20

The division of operands where the result is the quotient in which the 9//2 = 4 and 9.0//2.0 =
// Floor Division
digits after the decimal point are removed. 4.0
Comparison (Relational) Operators
Operator Description Example

== If the values of two operands are equal, then the condition becomes true. (a == b) is not true.

!= If values of two operands are not equal, then condition becomes true. (a != b) is true.

(a <> b) is true. This is similar to


<> If values of two operands are not equal, then condition becomes true.
!= operator.

If the value of left operand is greater than the value of right operand, then condition
> (a > b) is not true.
becomes true.
If the value of left operand is less than the value of right operand, then condition
< (a < b) is true.
becomes true.

If the value of left operand is greater than or equal to the value of right operand, then
>= (a >= b) is not true.
condition becomes true.

If the value of left operand is less than or equal to the value of right operand, then
<= (a <= b) is true.
condition becomes true.
A SSIG N M EN TO PERATO R
Operator Description Example
c = a + b assigns value of a + b
= Assigns values from right side operands to left side operand
into c
+= It adds right operand to the left operand and assign the result to left
c += a is equivalent to c = c + a
Add AND operand

-= It subtracts right operand from the left operand and assign the result to
c -= a is equivalent to c = c - a
Subtract AND left operand

*= It multiplies right operand with the left operand and assign the result to
c *= a is equivalent to c = c * a
Multiply AND left operand

/= It divides left operand with the right operand and assign the result to left
c /= a is equivalent to c = c / a
Divide AND operand

%=
It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
Modulus AND

**= Performs exponential (power) calculation on operators and assign value


c **= a is equivalent to c = c ** a
Exponent AND to the left operand

//= It performs floor division on operators and assign value to the left
c //= a is equivalent to c = c // a
Floor Division operand
LOGICAL OPERATOR

Operator Description Example

And If both the operands are true then condition


(a and b) is true.
Logical AND becomes true.

Or If any of the two operands are non-zero then


(a or b) is true.
Logical OR condition becomes true.

not Not (a and b) is


Used to reverse the logical state of its operand.
Logical NOT false.
BITWISE OPERATOR

Operator Description Example

& Operator copies a bit to the result if it exists in (a & b) = 12


Binary AND both operands. (means 0000 1100)

| (a | b) = 61
It copies a bit if it exists in either operand.
Binary OR (means 0011 1101)
^ It copies the bit if it is set in one operand but (a ^ b) = 49
Binary XOR not both. (means 0011 0001)
(~a ) = -61 (means 1100 0011 in 2's
~
It is unary and has the effect of 'flipping' bits. complement form due to a signed binary
Binary Ones Complement
number.

<< The left operands value is moved left by the a << 2 = 240
Binary Left Shift number of bits specified by the right operand. (means 1111 0000)

>> The left operands value is moved right by the a >> 2 = 15


Binary Right Shift number of bits specified by the right operand. (means 0000 1111)
M EM BERSHIP OPERATOR

Operator Description Example

Evaluates to true if it finds a variable in


x in y, here in results in a 1 if
in the specified sequence and false
x is a member of sequence y.
otherwise.

Evaluates to true if it does not finds a x not in y, here not in results


not in variable in the specified sequence and in a 1 if x is not a member of
false otherwise. sequence y.
IDENTITY OPERATOR

Operator Description Example

Evaluates to true if the variables on either


x is y, here is results in 1 if id(x)
is side of the operator point to the same object
equals id(y).
and false otherwise.

Evaluates to false if the variables on either


x is not y, here is not results in 1 if
is not side of the operator point to the same object
id(x) is not equal to id(y).
and true otherwise.
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or other object.
Rules for Python Identifiers
Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore _.
Example - Valid Names - myClass, var_1 print_this_to_screen, all are valid example.
An identifier cannot start with a digit.
Example - Invalid
1variable is invalid.
But variable1 is a valid name.
Keywords cannot be used as identifiers
Python is a case-sensitive language. This means, Variable and variable are not the same.
Python Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Comments starts with a #


# This is a comment
To add a multiline comment you could insert a # for each line.
Example Single Line
print("Hello, World!") #This is a comment
Example Multi Line
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Multi lined comment can be given inside triple quotes.
eg:
''''' This
Is
Multipline comment'''
Constants
A constant is a type of variable whose value cannot be changed.
Python Literals
Lite ra ls a re v a lue s a ssig ne d to a v a ria b le o r c o nsta nt.
Pytho n sup p o rt the fo llo wing lite ra ls:
• String Lite ra ls
• N um e ric Lite ra ls
• Bo o le a n Lite ra ls
• Spe c ia l Lite ra ls
I. String literals:
String literals c a n b e formed by enclosing a text in the quotes. We c a n use both single as well as d ou
quotes for a String.
Eg:
“GN C " , ‘456‘
Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg. : >>> TEXT = ‘GN C ’
Multi line String- A piece of text that is spread along multiple lines is known as Multiple line String.
> > > TEXT= ‘G N C /
AUTONOMOUS’
O UTPUT : ‘G N C A UTO N O M O US’
• Numeric Literals
Numeric literals can belong to following four different numerical types.

Int(signed integers)-Numbers( can be both positive and negative) eg. : 200


Long(long integers)-Integers of unlimited size followed by lowercase or uppercase L eg:
87032845L
float(floating point)-Real numbers with both integer and fractional part eg: -26.2
Complex(complex)-In the form of a+bj where a forms the real part and b forms the imaginary
part of complex number. eg: 3.14j
• Boolean literals:
A Boolean literal can have any of the two values: True or False.
Eg. Value = True
• Special literals.
Python contains one special literal i.e., None.
None is used to specify to that field that is not created.
Eg. Value = None
EXPRESSION
• An expression is a combination of variables constants and operators written according to the
syntax of Python language.
• In Python every expression evaluates to a value i.e., every expression results in some value
of a certain type that can be assigned to a variable.
Example:
A*b-c
(m+n)*(x+y)
3*x*x+2*x+1
x/y+c
• The expression is evaluated first and then replaces the previous value of the variable on the
left hand side.
• The Expression can be evaluated based operator precedence.
OPERATOR PRECEDENCE
Operator Description
( ) Parenthesis
** Exponentiation (raise to the power)
~ x, +x, -x Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators
# PROGRAM FOR EXPRESSION

a = 20
b = 10
c = 15
d=5
exp1 = (a+b) * c/d #( 30 * 15 ) / 5
print("expression1 result = " , exp1)
exp2 = ((a+b) *c )/d #(30 * 15 ) / 5
print("expression2 result :" , exp2)
exp3 = (a+b) *(c/d) #(30) * (15/5)
print("expression result3 :" , exp3)
exp4 = a +(b*c)/d #20 + (150/5)
print("expression4 result ; " , exp4
# Sim p le Pro g ra m s in Pytho n

# First Pro g ra m

# This p ro g ra m a d d s tw o num b e rs
num 1 = 5
num 2 = 10
# A d d two numbers
sum = num 1 + num 2
# D isp la y the sum
p rint('The sum o f tw o num b e rs = ' , sum )

# Sec o nd Pro g ra m

# Python Program to convert temperature in celsius to fahrenheit


celsius = 37.5
# c a lc ula te fa hre nhe it
fa hre nhe it = (c e lsius * 1.8) + 32
p rint(' C e lsius to Fa hre nhe it = ' , fa hre nhe it)
# PROGRAM FOR CHECKING THE INPUT IS RESERVED WORD OR NOT
>>> import keyword (MODULE)
>>> kwlist = [Link] (FUNCTION)
>>> kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
>>> kw = input('enter a keyword..')
enter a keyword..catch
>>> kw in kwlist
False
>>> kw = input('enter a keyword..')
enter a keyword..import
>>> kw in kwlist
True
Interactive Input
input ( ) : This function first takes the input from the user
eg. : name = input(“Enter your Name”)
How the input function works in Python :
• When input() function executes program flow will be stopped until the user has given an input.
• The text or message display on the output screen to ask a user to enter input value is optional i.e. the
prompt, will be printed on the screen is optional.
• Whatever you enter as input, input function convert it into a string.
• if you enter an integer value still input() function convert it into a string.
•You need to explicitly convert it into an integer in your code using typecasting.
Eg.
val1 = input("enter number1")
val2 = input("enter nmeber2")
sum = val1 + val2
print('sum = ' , sum)
Python Display Statement
Syntax
print()
The print() function prints the given object to the standard output device (screen) or to the
text stream file.
Eg. print(“hello”)
Python Functions

• A function is a block of code which only runs


when it is called.
• A function is a block of organized, reusable code that is
used to perform a single, related action. Functions provide
better modularity for your application and a high degree of
code reusing.
• You can pass data, known as parameters, into
a function.
•A function can return data as a result.
FUNCTIONS

FUNCTIONS

BUILT-IN FUNCTIONS
or USER DEFINED
PRE-DEFINED FUNCTIONS
FUNCTIONS
FUNCTIONS
Type Conversion Functions

Function Converting what to what Example


>>> int(‘2015')
2015
int() string, floating point→integer >>> int(3.141592)
3
>>> float('1.99')
1.99
string, integer→floating point
float() >>> float(5)
number
5.0
>>> str(3.141592)
'3.141592'
integer, float, list, tuple, dictionary
str() >>> str([1,2,3,4])
→string
'[1, 2, 3, 4]'
Type Conversion in Python with Examples

The process of converting a Python data type into another data type is known as type conversion.
There are mainly two types of type conversion methods in Python, namely, implicit type conversion and
explicit type conversion.

In Python, when the data type conversion takes place during compilation or during the run time, then it’s
called animplicit data type conversion.

Example

a=5
b = 5.5
sum = a + b print (sum)
print (type (sum)) #type() is used to display the datatype of a variable

Output:
10.5
<class ‘float’>
Type Conversion in Python with Examples
Explicit type conversion is also known as typecasting.
Explicit type conversion takes place when the programmer clearly and explicitly defines the same in
the program. Various forms of explicit type conversion are explained below:

[Link](a, base): This function convertsany data type to integer. ‘Base’ specifies thebase in which string isif the
data type is a string.
[Link](): This function is used to convertany data type to afloating-pointnumber.

Example :
# adding string and integer data types using explicit type conversion
a = 100
b = “200”
result1 = a + b
print(result1)
b = int(b)
result2 = a + b
print(result2)
The math module is used to access mathematical functions in the Python. All methods of this functions are
used for integer or real type objects. import math
Functions
ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number x.
factorial(x)
Returns factorial of x. where x≥0
floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.
gcd(x, y)
Returns the Greatest Common Divisor of x and y
pow(x, y)
Return the x to the power y value.
sqrt(x)
Finds the square root of x
log10(x)
Returns the Log of x, where base is 10
sin(x)
Return the sine of x in radians
cos(x)
Return the cosine of x in radians
tan(x)
Return the tangent of x in radians
User Defined Functions in Python

User User-defined functions (UDFs) are the functions defined by the user to perform a
specific task.

All the functions that are written by any of us come under the category of user-defined
functions.

Below are the steps for writing user-defined functions in Python.

SYNTAX
User Defined Functions in Python

Example

def area(r):
area= 3.14*r*r
print ("the area of the circle is:= ", area)

area(10)
Returning vs Printing

>>>def print_greeting():
… print("Hello, World")

>>>print_greeting()
Hello, World

>>>def ret_greeting():
… return "Hello, World"

>>>ret_greeting()
‘Hello, World’
COMPOSITION OF FUNCTIONS

A composite function is generally a function that is written inside another function.


Composition of a function is done by substituting one function into another function.
For example,f [g (x)] is the composite function of f (x) and g (x).

The composite function f [g (x)] is read as “f of g of x”.

Example 1
Given the functions f (x) = x2 + 6 and g (x) = 2x – 1, find (f∘g) (x).
Solution
Substitute x with 2x – 1 in the function f(x) = x2 + 6. (f∘g) (x)
= (2x – 1) 2 + 6 = (2x – 1) (2x – 1) + 6
IDENTATION

•Indentation in Python Programming is simply the spaces at the beginning of a code line
•Indentation in other languages like c, c++, etc., is just for readability,
•In Python, indentation is an essential and mandatory concept that should be followed when writing
Python code;
•Otherwise, the Python interpreter throws an Indentation Error.
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.

#One Argument
def greet(name):
print(name + " Happy Morning")

greet(“RAM,")
greet(“AADITHYA,")
greet(“ PRIYA,")

# Two Arguments
def greet(Fname, Lname):
print(Fname + " " + Lname)

greet(“Raja", "Ram“)
Function Arguments
You can call a function by using the following types of formal arguments−
•Required arguments
•Keyword arguments
•Default arguments

•Required arguments

Required arguments are the arguments passed to a function in the correct positional order.
Here, the number of arguments in the function call should match exactly with the function
definition.
To call the function greet(), you need to pass one argument, otherwise, it gives a syntax error
as follows−
•Keyword arguments

Keyword arguments are related to the function calls.


When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter can use the keywords
provided to match the values with parameters.
You can also make keyword calls to the printinfo()function in the following ways−

Example
def printinfo( name, age ):
#This prints a passed info into this function
print ("Name: ", name)
print ("Age ", age )
return

# Now you can call printinfo function


printinfo( age=35, name="mike" )
Default arguments

A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.

def printinfo( name, age = 35 ):


"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call printinfo function


printinfo( age=5, name="mike" )
printinfo( name="miki“)
DATA TYPES

Pythonstandard data types:


Numbers
Boolean
String
List
Tuple
Set
Dictionary
NUMBERS
Python supports four different numerical types:
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers EXAMPLE
Program:
a= 3
b = 2.65
c = 98657412345L
d = 2+5j
print ("int is",a)
print ("float is",b)
print ("long is",c)
print ("complex is",d) Output:
int is 3
float is 2.65
long is 98657412345
complex is (2+5j)
BOOLEAN

Booleans are identified by True or False.


Program:
a = True
b = False
print a
print b

Output: True False


STRINGS

• Strings in Python are identified as a contiguous set of characters represented in the

quotation marks.

• Python allows for either a pair of single or double quotes.

str ="WELCOME"
WORKING WITH FUNCTIONS
USING PYTHON
Definition OF Function
• A program is a set of statements that takes some input,
does specific computations based on given input and
produces desired output.
• A very Large program with a huge single list of
instructions increases complexity.
• Python allows us to divide a large program into some
small independent units or blocks known as functions.
• Decomposing a complex problem into simpler one
using functions improves clarity of the code.
• Functions are the most important segments or
subprograms of an application used to perform specific
tasks.
• A python program can have one or more functions.
The advantages of using functions

• Reduce duplication By using functions, we can avoid


of code. rewriting same logic/code again
and again, Thus function reduces
program size.

• Induce reusability of We can call python functions


code. any number of times from any
part of the [Link] function
induces reusability in a
program.
Types of Functions:
Basically, there are three types of functions used in Python program:
• Built-in functions (python library functions)
– These are predefined functions and are always available in Python
library.
• Functions defined within modules
– These are also predefined functions available in different modules.
• User-defined functions
– These are defined by programmer.
[Link]- in Functions
• These functions are already built in the library of
python and can be accessed by programmer
easily.
• These are always available and for using them, we
don't have to import any module (file).
• Python has a small set of built-in functions like
abs(), max(), min(), len(), range(),round(),bool()
chr(), float(), int(),long(),str( ),type( ),id( ) etc.
Example:
max( x, y, z) returns the largest of its 3 arguments.
>>>max(80, -70, 100)
[Link]- in Functions

abs() Returns the abs value of number value of a number

float() Returns a floating point number

input() Allowing user input

int() Returns an integer number

len() Returns the length of an object

min() Returns the smallest item in an iterable

print() Prints to the standard output device


Returns a sequence of numbers, starting from 0 and
range() increments by 1 (by default)
[Link] defined in modules
When we want to use module based functions in our program,
we need to import the corresponding module of that particular
function.
The functions available in math module are:
ceil(), floor(), fabs(), exp(), log(), pow(), sqrt() cos(), sin()etc.
Example:
ceil(x) returns the smallest integer not less than x
fabs(x) returns the absolute value of x,where x is a numeric value.
Example:
To work with the functions of math module, we
must import math module in our program.
sqrt() returns the square root of a number
>>>import math
>>>[Link](49)
7.0
User defined function
In Python, programmers can also develop their own function(s). They
are known as user defined functions.

Syntax of function
def function-name(parameters)
:
#block of statement(s)
Example:
def hello_world(): #called function
print("hello world")

hello_world() #calling function

Output:
hello world
Defining functions in Python
def functionName( list of parameters):
function_block
return [expression]

Top level statements


• In python program, generally all python definitions are
given at the top followed by statements which are not part
of any functions These statements are not indented at all.

• The non indented statements written after all the function


Top level statements definitions are often called top level statements .

def userfunction (arg1, arg2, arg3...):


program statement1
program statement2
program statement3
....
return
userfunction(arg1,arg2,arg3)
Function definition with example
#python function to calculate the sum of two variables
• Keyword def marks the start of the function
header.
#defining the function
• A function name to uniquely identify it. The name of def sum(a,b):
the Function follows the same rule of naming the
identifier.
#takes a and b and return the sum
• Parameters (arguments) through which we pass return a+b;
values to a function are optional.
• A colon (:) is used to mark the end of t h e #taking values from the user
function header. a = int(input("Enter a: "))
• The string after the function header is called the b = int(input("Enter b: "))
docstring. It is briefly used to explain what a function
does. Comments are ignored by the Python #printing the sum of a and b
interpreter but docstrings can be viewed when the print("Sum = ",sum(a,b))
program is running.
• One or more Python statements form a function body. Output:
All the statements of the block should have the same Enter a: 10
indentation level. Enter b: 20
• A return statement is used to return value(s) from Sum = 30
the function
Function definition with example

# function that adds two numbers


def square(n): def add_numbers(num1, num2):
sum = num1 + num2
'''Takes in a number n, returns the square of n'''
return sum
return n**2
# calling function with two
print(square.__doc__) values
result = add_numbers(5, 4)

print('Sum: ', result)

# Output: Sum: 9
Function definition with example

import math
Code Reusable

• # sqrt computes the square root
square_root = [Link](4)
• # function definition
print("Square Root of 4 def get_square(num):
is",square_root)
• return num * num
• # pow() comptes the power
power = pow(2, 3) for i in [1,2,3]:
• # function call
print("2 to the power 3 is",power)
result = get_square(i)
print('Square of',i, '=',result)
HOW A FUNCTION WORKS
• Execution always begins from the first statement of the program.
• A python program may contain several funtion
definitions.
• If any function definition is found,python executes only function header
for the correctness of it and skips all lines of function body(block).
• When python sequentially reaches top level statement’s function call,
python transfers control to the function header and then execution of
function body takes place.
• Finally function execution ends with a return statement if any or the
last statement of function body.
FLOW OF EXECUTION IN A FUNCTION CALL
• Flow of execution refers to the order in which statements are
executed.
• A function body is executed in the execution frame.
• Whenever a function call statement is executed, an execution frame for
the called function is created and the control is transferred to invoke the
called function.
• Within the function’s execution frame, the body of the function gets
executed and after the last statement of the function the control returns to
the statement with/without any value(s) to the function from where it is
called(calling function).
Function Parameters:
The values being passed through a function call statement are called arguments or actual parameters.
The values received in the function definition are called parameters or formal parameters.

A function has two types of parameters:


• Formal Parameter(parameters): Formal parameters are written in the function prototype(function
definition). Formal parameters are local variables that are assigned values from the arguments when the
function is called.
• Actual Parameter(arguments): When a function is called, the values that are passed are called actual
parameters. At the time of the call, each actual parameter is assigned to the corresponding formal
parameter in the function definition.

Note:
[Link] which is called by another Function is called Called Function. The called function contains
the definition of the function and formal parameters are associated with them.
2. The Function which calls another Function is called Calling Function and actual paramaters are
associated with them.
[Link] python, a function must be defined before the function calling otherwise python interpreter
gives an error.
Lambda function
Python lambda function doesn’t have any return statement. It has Example:
only a single expression which is always returned by default. The add = lambda x, y : x + y

Python lambda function is anonymous as it is a function without a print(add(10, 20))

def keyword and name. To create a Python lambda function, we print("Result from a Function")
have to use the lambda keyword.
def add_func(x, y):
return x + y
The basic syntax of Python lambda is
Lambda arguments : expression print(add_func(10, 20))

The Python lambda function accepts any number of arguments


but uses only one expression. Both the lambda function and regular function return the
same result. However, the regular function needs a def
keyword, a function name, and a return value. Whereas,
For instance,
the lambda function does not need any of them. By
lambda a, b: a + b. Here, a and b are the arguments accepted by
default, it returns the expression result.
the lambda function. a + b is the expression.
Summary of Module 1

• What is a function?
• How a function works?
• Syntax of user-defined function
• Calling function and called function
• Formal parameter and actual parameter
SOLVED QUESTIONS
1. Differentiate between round () and floor() functions with suitable examples.
Ans. The function round() is used to convert a fractional number into whole as the nearest next whereas
the function floor() is used to convert the nearest lower whole number. e.g.,
round (4.1) = 5 and floor (6.9) = 6

2. Name the Python Library modules which need to be imported to invoke the
following functions:
(i) sin( ) (ii) randint ( )
1
Ans.
(i) math (ii) random

[Link] will be the output of the following code? a=1


def f():
a=10
print(a)
OUTPUT:
1

4. What is a lambda function? Explain with an example.


A lambda function is a small anonymous function that can take any number of arguments, but can only
have one expression.
E.g.
x = lambda a, b : a * b
print(x(5, 6)) OUTPUT:
30
WORKSHEET 1
1. What is the significance of having function in a program?
2. Why are docstrings used? How are they different from comments?
3. How do we define a function?
4. What is lambda function?
5. What is the difference between formal parameterand actual parameter?
6. Write the syntax of function definition and explain with an example.
7. Write a program to generate fibonacci series with a function.
8. What is the importance of void function?
9. Differentiate between built in function and functions defined in module.
10. Rewrite the following Python function after removing all the syntactical errors (if any)
def checkval:
x = raw_input(“Entera number”)
if x % 2 = 0 :
print x,”is even”
else if x<0 :
print x,”should be positive”
else ;
print x,”is odd”
11. Write a python program using function to find the largest element in a list.
def largest(L,n) :
max = L[0]
for i in range(1, n) :
if L[i] > max :
max =L[i]
return max
M = [10, 24, 45, 90, 98]
n = len(M)
max= largest(M, n)
print ("Largest in the given List is", max)
Output
Largest in the give n List is 98
THANK
YOU
PYTHON TYPE CONVERSION
Python Type Conversion

In programming, type conversion is the process of converting data of one type to another.

For example: converting int data to str.


There are two types of type conversion in Python.
Implicit Conversion - automatic type conversion
Explicit Conversion - manual type conversion
Python Implicit Type Conversion
In certain situations, Python automatically converts one data type to another.
This is known as implicit type conversion.
Example 1: Converting integer to float

Let's see an example where Python promotes the conversion of the lower data type (integer) to the higher data type
(float) to avoid data loss.

integer_number = 123
float_number = 1.23

new_number = integer_number + float_number

# display new value and resulting data type


print("Value:",new_number)
print("Data Type:",type(new_number))

Output
Value: 124.23
Data Type: <class 'float'>
In the above example, we have created two variables:

integer_number and float_number of int and float type respectively.

Then we added these two variables and stored the result in new_number.

As we can see new_number has value 124.23 and is of the float data type.

It is because Python always converts smaller data types to larger data types to avoid the loss of data.

We get TypeError, if we try to add str and int.

For example, '12' + 23. Python is not able to use Implicit Conversion in such conditions.

Python has a solution for these types of situations which is known as Explicit Conversion.
Explicit Conversion
In Explicit Type Conversion, users convert the data type of an object to required data type.

We use the built-in functions like int(), float(), str(), etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts (changes) the data type of the objects
Data types can be converted to each other in Python.
The functions used for type conversion are :

To convert to string - > str()

.To convert to integer - > int()

To convert to float - > float()

Example
num1 = 5.8
num2 = int(num1)
print(num2)

Output
5
Explicit Conversion
Example

num1 = 12
num2 = float(num1)
print(num2)

Output
12.0

value = “ TWO”
num1 = int(value)
print(num1)

Output
Value error

num1 = “8”
num2 = int(num1)
print(num2)

Output
8
Example 2: Addition of string and integer Using Explicit Conversion
num_string = '12'
num_integer = 23

print("Data type of num_string before Type Casting:",type(num_string))


# explicit type conversion
num_string = int(num_string)
print("Data type of num_string after Type Casting:",type(num_string))
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))

Run Code

Output

Data type of num_string before Type Casting: <class 'str'>


Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>
In the above example, we have created two variables: num_string and num_integer with str and int type values respectively.
Notice the code,

num_string = int(num_string)
Here, we have used int() to perform explicit type conversion of num_string to integer type.

After converting num_string to an integer value, Python is able to add these two variables.

Finally, we got the num_sum value i.e 35 and data type to be int.

Key Points to Remember


• Type Conversion is the conversion of an object from one data type to another data type.

• Implicit Type Conversion is automatically performed by the Python interpreter.

• Python avoids the loss of data in Implicit Type Conversion.

• Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by
the user.

• In Type Casting, loss of data may occur as we enforce the object to a specific data type

You might also like