u1_python
u1_python
HISTORY OF PYTHON
The following table lists all the important versions history of Python:
Version Release Date Important Features
Python 0.9.0 February 1991 Classes with inheritance exception handling
Functions
Modules
Python 1.0 January 1994 Functional programming tools (lambda, map,
filter and reduce).
Support for complex numbers.
Functions with keyword arguments
Python 2.0 October 2000 List comprehension.
Python 2.7.0 - Current July 2010 Cycle-detecting garbage collector.
version Support for Unicode. Unification of data types
Python 2.7.15 - Current sub- May 2018 and classes
version
Python 3 December 2008 Backward incompatible.
Python 3.6 December 2016 print keyword changed to print() function
Python 3.6.5 March 2018 raw_input() function depreciated
Unified str/Unicode types.
Utilities for automatic conversion of Pytthon
2.x code
Python 3.7.0 - Current May 2018 New C API for thread-local storage
Version Built-in breakpoint()
Data classes
Context variables
Python Features:
Python is an interpreter-based language, which allows execution of one instruction at a time.
Easy-to-learn- Python has few keywords, simple structure, and a clearly defined syntax. This
allows a student to pick up the language quickly.
Extensive basic data types are supported e.g. numbers (floating point, complex, and unlimited-
length long integers), strings (both ASCII and Unicode), lists, and dictionaries.
Variables can be strongly typed as well as dynamic typed.
Supports object-oriented programming concepts such as class, inheritance, objects, module,
namespace etc.
Cleaner exception handling support.
Supports automatic memory management.
A broad standard library: Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode: Python has support for an interactive mode, which allows interactive testing
and debugging of snippets of code.
Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more
efficient.
Databases: Python provides interfaces to all major commercial databases.
GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
Scalable: Python provides a better structure and support for large programs than shell scripting.
Download Python
To install Python on your local machine, get a copy of the standard distribution of Python software
from https://www.python.org/downloads based on your operating system, hardware architecture and
version of your local machine.
Install Python on Windows:
To install Python on a Windows platform, you need to download the installer. A web-based installer,
executable installer and embeddable zip files are available to install Python on Windows.
Visit https://www.python.org/downloads/windows and download the installer based on your local
machine's hardware architecture.
The web-based installer needs an active internet connection. So, you can also download the standalone
executable installer. Visit https://www.python.org/downloads and click on the Download Python
3.7.0 button as shown below. (3.7.0 is the latest version as of this writing.)
Using Windows
A Windows installation creates a new folder in the Start menu that
contains your Python installation. You can access it by choosing Start ➪
All Programs ➪ Python 3.6. The two items of interest in the folder when
creating new applications are IDLE (Python GUI) and Python (command
line).
1. Click IDLE(Python GUI). Now the following screen is displayed.
2. The Python (command line) option opens a command prompt and executes the Python command, as
shown in Figure. Again, the environment automatically displays same above information such as the
Python version and the host platform.
To ensure that you have a usable installation, you need to test it. To see Python work, type print(“This
is my first Python program.”) and press Enter. Python displays the message you just typed, as shown
in Figure.
Interactive Mode:
Working in interactive mode is convenient for beginners and for testing small pieces of code
immediately. Python, in interactive mode, is good enough to learn, experiment or explore, but its
only drawback is that we cannot save the statements and have to retype all the statements once again
to re-run them.
Interactive Mode allows us to interact with OS. After executing, Python statement,
interpreter displays the result(s) immediately.
That means, when we type Python expression / statement / command after the prompt
(>>>), the Python immediately responses with the output of it.
Examples :
>>>print "WELCOME TO PYTHON PROGRAMMING"
WELCOME TO PYTHON PROGRAMMING
>>> print 5+10
15
Script Mode: A Python script can be executed at the command line by invoking the interpreter on
your application. In script mode, we type Python program in a file and then use interpreter to execute
the content of the file. But for coding of more than few lines, we should always save our code so that it
can be modified and reused.
The following script mode is typed and saved with the name of quotient_remainder.py
Example: Input any two numbers and to find Quotient and Remainder.
Python Identifier : Identifier is the name of the variables, functions, classes, modules, packages etc.
• An identifier name is the combination of alphabet letters (a-z or A-Z), digits (0-9) or
underscore. It should start with either an alphabet letter (lower or upper case) or an underscore
(_).No other characters are allowed.
• Identifiers are case sensitive which means variables named age and Age are different.
• An identifier cannot start with a digit. 1emp is invalid, but emp1 is a valid name.
• Can be any (reasonable) length
• Keywords cannot be used as identifiers.
Variable
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
• You can store integers, decimals or characters in these variables. Example : "Sara", 120, 25.36
• Variables are created when first assigned.
• Variables must be assigned before being referenced.
• The value stored in a variable can be accessed or updated later.
• No declaration required
• The type (string, int, float etc.) of the variable is determined by Python
• The interpreter allocates memory on the basis of the data type of a variable.
>>> myAge=21
Here myAge is an identifier (name) referring to integer value 21.
Rules for Variable Name
The name of the variable should start with either an alphabet letter or an underscore (_), but it
cannot start with a digit.
The variable name can consist of alphabet letter(s), number(s) and underscore(s) only.
For example, myVar, MyVar, _myVar, MyVar123 are valid variable names but m*var,
my-var, 1myVar are invalid variable names.
a, b = 3, 4
print(a,b) Output: a=3 b=4
print(b) Output; b=4
x, y, z = 1, 2, "abcd“
print(z) Output: z=”abcd”
c=d=10
print (c) Output: c = 10
Swap variable
Python swap values in a single line and this applies to all objects in python.
x = 10
y = 20
print(x)
print(y)
x,y=y, x
print(x)
print(y)
You can reuse variable names by simply assigning a new value to them :
>>> x = 100
>>> print(x) Output: x=100
>>> x = "Python
>>> print(x) Now Output: x=”Python”
>>>
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = “good”
def myfunc() :
print("Python is " + x)
myfunc()
def func2():
print("In side func2() var1 = ",var1)
func1()
func2()
Output:
In side func1() var1 = PHP
In side func2() var1 = Python
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
o/p
Python is fantastic
Python is awesome
Global variable inside function
To create a global variable inside a function, you can use the global keyword.
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
STATEMENTS
By default, the Python interpreter treats a piece of text terminated by hard carriage return (new line
character) as one statement.
A statement is an instruction that the Python interpreter can execute. Python program consists of a
sequence of statements. Statements are everything that can make up a line (or several lines) of Python
code. For example, z = 1 is an assignment statement.
msg="Hello World"
code=123
name="Steve"
You can show the text spread over more than one lines to be a single statement by using the backslash
(\) as a continuation character.
EXPRESSION
Expression is an arrangement of values and operators which are evaluated to make a new value.
Expressions are statements as well. A value is the representation of some entity like a letter or a number
that can be manipulated by a program.
A single value >>> 20 or a single variable >>> z or a combination of variable, operator and value >>>
z + 20 are all examples of expressions.
For example,
>>> 8 + 2
10
TYPES / DATA TYPE:
Type (i.e data type) is a set of values, and the allowable operations on those values. It
can be one of the following:
1. Number: Number data type stores Numerical Values. This data type is immutable (unmodifiable)
i.e. value of its object cannot be changed. Numbers are of three different types:
Integer & Long (to store whole numbers i.e. decimal digits without fraction part). Integers can
be of any length; it is only limited by the memory available.
Float/floating point (to store numbers with fraction part). A floating point number is accurate up
to 15 decimal places.
Complex (to store real and imaginary part). Complex numbers are written in the form, x + yj,
where x is the real part and y is the imaginary part.
Boolean : Condition is really just a yes-or-no question, the answer to that question is a Boolean value,
either True or False. The Boolean values, True and False are treated as reserved words.
2. None : None is a special data type. The None keyword is used to define a null value, or no value at
all or nothing. (Version 3.0)
Syntax
The syntax of None statement is: None
c) Tuples: Tuples are a sequence of values of any type and are indexed by integers.
They are immutable.(not modifiable) Tuples are enclosed in ( ).
4. Sets:
Python has a data type called a set. Sets work like mathematical sets.
Set is unordered collection of values of any type with no duplicate entry. It is immutable.
Sets are denoted by curly braces, like below:
S = {1,2,3,4,5}
Recall that curly braces are also used to denote dictionaries, and {} is the empty dictionary. To get
the empty set, use the set function with no arguments, like this:
S = set()
Working with sets There are a few operators that work with sets.
The symmetric difference of two sets gives the elements that are in one or the other set, but not
both. Here are some useful methods:
5. Mapping: This data type is unordered and mutable. Dictionaries fall under Mappings.
Dictionaries: It can store any number of python objects. What they store is a key -value pairs, which
are accessed using key. Dictionary is enclosed in curly brackets { }.
type : You can get the data type of a variable with the type() function.
Example :
x=5
y = "John"
print(type(x)) Output <class 'int'>
print(type(y)) Output <class 'str'>
Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) #Output x will be '3'
y = int(3) # Output y will be 3
z = float(3) # Output z will be 3.0
int() function
To explicitly convert a float to a number or a string to an integer, cast the number using int() function.
Output
After Float to Integer Casting the result is 3
After String to Integer Casting the result is 1
float() function
float() function returns a floating point number constructed from a number or string.
Program to Demonstrate float() Casting Function
int_to_float = float(4)
Output
After Integer to Float Casting the result is 4.0
After String to Float Casting the result is 1.0
str() function
The str() function returns a string which is fairly human readable.
Program to Demonstrate str() Casting Function
int_to_string = str(8)
float_to_string = str(3.5)
print(f"After Integer to String Casting the result is {int_to_string}")
print(f"After Float to String Casting the result is {float_to_string}")
chr() function
The chr() method returns a string representing a character whose >>> print (chr(65))
Unicode code point is an integer. The chr() method takes only one A
integer as argument. >>>
Syntax: chr(num)
num : integer value
PYTHON OPERATORS
Operators in general are used to perform operations on values and variables in Python. These are
standard symbols used for the purpose of logical and arithmetic operations.
1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.
Example - 1
>>> 10+35
45
# Example-2
a=9
b=4 Output
# Addition of numbers 13
add = a + b 5
# Subtraction of numbers 36
sub = a - b 2.25
2
# Multiplication of number 1
mul = a * b 6561
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
> Greater than: True if left operand is greater than the right
< Less than: True if left operand is less than the right
>= Greater than or equal to: True if left operand is greater than or equal to the right
<= Less than or equal to: True if left operand is less than or equal to the right
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
.3. Logical operators:
The logical operators are used for comparing or negating the logical values of their operands and to
return the resulting logical value. The result of the logical operator is always a Boolean value, True or
False.
Logical operators perform Logical AND, Logical OR and Logical NOT operations.
4. Assignment operators : Assignment operators are used to assign values to the variables.
Syntax: <variable> = <expr>
Add AND: Add right side operand with left side operand and a+=b
+= then assign to left operand a=a+b
Subtract AND: Subtract right operand from left operand and a-=b
-= then assign to left operand a=a-b
Multiply AND: Multiply right operand with left operand and a*=b
*= then assign to left operand a=a*b
Divide AND: Divide left operand with right operand and a/=b
/= then assign to left operand a=a/b
Modulus AND: Takes modulus using left and right operands a%=b a=a
%= and assign result to left operand %b
6. Membership operators-
in and not in are the membership operators; used to test whether a value or variable is in a sequence.
in True if value is found in the sequence
Output:
not in True if value is not found in the sequence
True
True
# Examples of Membership operator
False
x = 'Geeks for Geeks'
True
y = {3:'a',4:'b'}
False
print('G' in x)
print('geeks' not in x)
print('Geeks' not in x)
print(3 in y)
print('b' in y)
7. Bitwise Operator :
Bitwise operators treat their operands as a sequence of bits (zeroes and ones) and perform bit by bit
operation. For example, the decimal number ten has a binary representation of 1010. Bitwise operators
perform their operations on such binary representations, but they return standard Python numerical
values.
Precedence and Associativity of Operators: Operator precedence and associativity as these
determine the priorities of the operator.
Operator Precedence: This is used in an expression with more than one operator to determine which
operation to perform first.
Operator Precedence table
# Examples of Operator Precedence
Operator Associativity: If an expression contains two or more operators with the same precedence
then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.
Syntax
Print statement
In Python, single, double and triple quotes are used to denote a string. Most use single quotes when
declaring a single character. Double quotes when declaring a line and triple quotes when declaring a
paragraph/multiple lines.
f-strings
Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal that is prefixed
with “f”.
These strings may contain replacement fields, which are expressions enclosed within curly braces {}.
The expressions are replaced with their values. In the real world, it means that you need to specify the
name of the variable inside the curly braces to display its value.
COMMENT : Comments are remark statements. A comment is a message to someone reading your
program. Comments are often used to describe what a section of code does or how it works.
Multi-line comments
For comments that span several lines, you can use triple quotes.
""" Program name: Hello world
Author: Brian Heinold
Date: 1/9/11 """
print('Hello world')
Interview Questions of this unit
Why Numeric data type is immutable? i.e. value of its object cannot be changed.
None
Python supports a set of control flow statements that you can integrate into
your program. The statements inside your Python program are generally
executed sequentially from top to bottom, in the order that they appear.
Apart from sequential control flow statements you can employ decision
making and looping control flow statements to break up the flow of
execution thus enabling your program to conditionally execute particular
blocks of code.
2. Decision Control Flow Statements: Depending on whether a condition is True or False, the decision
structure may skip the execution of an entire block of statements or even execute one block of
statements instead of other (if, if…else and if…elif…else).
3. Loop Control Flow Statements: This is a control structure that allows the execution of a block of
statements multiple times until a loop termination condition is met (for loop and while loop). Loop
Control Flow Statements are also called Repetition statements or Iteration statements.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You
need to determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages –
Conditional operators
The comparison operators are ==, >, <, >=, <=, and !=. That last one is for not equals. Here are a few
examples:
Example :
if grade>=80 and grade<90:
print('Your grade is a B.')
if Condition
An if statement consists of a boolean expression followed by one or
more statements.
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute
statement(s) only if the text expression is True. If the text expression
is False, the statement(s) is not executed.
(ex)
num = 3
if num > 0:
print(num, "is a positive number.")
if...else statements
if test expression :
Body of if
else :
Body of else
The if..else statement evaluates test expression and will execute body of if only when test condition is
True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.
(ex)
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Nested if statements
You can use one if or else if statement inside another if or else if statement(s).
Syntax
If test expression :
Body of if
elif test expression :
Body of elif
else :
Body of else
The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False,
it checks the condition of the next elif block and so on.
If all the conditions are False, body of else is executed. Only one block among the several if...elif...else
blocks is executed according to the condition.
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
Another example
grade = eval(input('Enter your score: '))
if grade>=90:
print('A')
elif grade>=80:
print('B')
elif grade>=70:
print('C')
elif grade>=60:
print('D')
else:
print('F')
Nested if statements
A if...elif...else statement inside another if...elif...else statement. This is called n esting in computer
programming.
Any number of these statements can be nested inside one another.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output 1
Enter a number: 5
Positive number
Output 2
Enter a number: -1
Negative number
Looping
Looping Statements
A loop is a used for iterating over a set of statements repeatedly. In
Python we have three types of loops for, while and do-while.
Here <variable> is a variable that is used for iterating over a <sequence>. On every iteration it takes
the next value from <sequence> until the end of sequence is reached.
Python – For loop example
The following example shows the use of for loop to iterate over a list of numbers.
In the body of for loop we are calculating the square of each number present in list and Output
displaying the same.
1
# Program to print squares of all numbers present in a list 4
numbers = [1, 2, 4, 6, 11, 20] 16
sq = 0 36
for val in numbers:
121
sq = val * val 400
print(sq)
Function range()
In the above example, we have iterated over a list using for loop. However we can also use a range()
function in for loop to iterate over numbers defined by range().
range(start, stop): generates a set of whole numbers starting from start to stop-1.
For example:
range(5, 9) is equivalent to [5, 6, 7, 8]
range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify the
step_size, the numbers generated are having difference of 1. However by specifying step_size we can
generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]
Here we are using range() function to calculate and display the sum of first 5 natural numbers.
Example
for i in range(3):
num = eval(input('Enter a number: '))
print ('The square of your number is', num*num)
print('The loop is now done.')
For loop with else block
Unlike Java, In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block
executes only when the loop has completed all the iterations. Lets take an example:
When a for loop is present inside another for loop then it is called a nested for loop. Lets take an
example of nested for loop.
Output:
0 , 10
for num1 in range(3):
0 , 11
for num2 in range(10, 14):
0 , 12
print(num1, ",", num2)
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13
Print a 10 × 10 multiplication table.
for i in range(1,11):
for j in range(1,11):
print('{:3d}'.format(i*j), end=' ')
print()
Note : end function is worked only python 3 and abover version only. Not works in 2.7
A multiplication table is a two-dimensional object. To work with it, we use two for loops, one for
the horizontal direction and one for the vertical direction.
While Loop
While loop is used to iterate over a block of code repeatedly until a given condition returns false.
Syntax
while condition:
#body_of_while
1. First the given condition is checked, if the condition returns false, the loop is terminated and the
control jumps to the next statement in the program after the loop.
2. If the condition returns true, the set of statements inside loop are executed and then the control jumps
to the beginning of the loop for next iteration.
Example Output:
num = 1 1
while num < 10: 4
print(num) 7
#incrementing the value of num
num = num + 3
num = 10
Output:
while num > 6:
10
print(num)
9
num = num-1
8
else:
7
print("loop is finished")
loop is finished
Infinite loops
When working with while loops, sooner or later you will accidentally send Python into a never-
ending loop. Here is an example:
i=0
while i<10:
print(i)
In this program, the value of i never changes and so the condition i<10 is always true. Python will
continuously print zeroes. To stop a program caught in a never-ending loop, use Restart Shell
under the Shell menu. You can use this to stop a Python program before it is finished executing.
Sometimes a never-ending loop is what you want. A simple way to create one is shown below:
while True:
# statements to be repeated go here
The value True is called a boolean value
Output
baz
bar
foo
iter()
Instead of using the for loop as shown above, we can use the iterator function iter(). An iterator is an
object which represents a data stream. It returns one element at a time. Python's built-in
method iter() receives an iterable and returns an iterator object. The iterator object uses
the __next__() method. Every time it is called, the next element in the iterator stream is returned. When
there are no more elements available, StopIteration error is encountered.
>>> L1=[1, 2, 3]
>>>it=iter(L1)
>>>it.__next__()
1
>>>it.__next__()
2
>>>it.__next__()
3
>>>it.__next__()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
it.__next__()
StopIteration
next()
Calling the it.__next__() method every time is tedious. The built-in function next()accepts an iterator
object as a parameter and calls the __next__() method internally. Hence, it.__next__() is the same
as next(it). The following example uses the next() method to iterate the list.
>>> L1=[1,2,3]
>>>it=iter(L1)
>>>next(it)
>>>1
>>>next(it)
>>>2
>>>next(it)
>>>3
>>>next(it)
Python - Generator
Python provides a generator to create your own iterator function. A generator is a special type of
function which does not return a single value, instead it returns an iterator object with a sequence of
values. In a generator function, a yield statement is used rather than a return statement. The following is
a simple generator function.
def myGenerator():
print('First item') Example
yield 10
Type this coding and save in a
print('Second item') python file. mygenerator.py
yield 20
print('Last item')
yield 30
In the above example, myGenerator() is a generator function. It uses yield instead of return
keyword. So, this will return the value against the yield keyword each time it is called.
enumerate
The built-in enumerate function takes an iterable and returns a new iterable
consisting of pairs
(i,x) where i is an index and x is the corresponding element from the iterable. For
example:
s = 'abcde'
for (i,x) in enumerate(s):
print(i+1, x)
zip
The zip function takes two iterables and “zips” them up into a single iterable that contains
pairs (x,y), where x is from the first iterable, and y is from the second. Here is an example:
s = 'abc'
L = [10, 20, 30]
z = zip(s,L)
print(list(z))
o/p
In this example, we are searching a number ’88’ in the given list of numbers.
Continue Statement
The continue statement is used inside a loop to skip the rest of the statements in the body of loop for
the current iteration and jump to the beginning of the loop for next iteration.
Syntax
Continue
You may be wondering that a python comment works similar to the pass statement as it does nothing so
we can use comment in place of pass statement. Well, it is not the case, a comment is not a placeholder
and it is completely ignored by the Python interpreter while on the other hand pass is not ignored by
interpreter, it says the interpreter to do nothing.
FUNCTIONS
A function is a block of reusable code that is used to perform a specific action. The advantages of using
functions are:
Functions can be defined inside a module, a class, or another function. Function defined inside a class
is called a method.
Python includes many built-in functions. These functions perform a predefined task and can be called
upon in any program, as per requirement.
A function definition has several syntax elements. First, we need to provide the "def" keyword to
identify that the object is a function. Second , we need to provide the name of the function . Third, we
can provide zero or more arguments. Fourth, we need to indent the body of the function as the body of
the function forms a Python block. Last, a function can also return a value.
Why use function
1. Code re-usability:: To perform a specific task in several places of our code
repeatedly. Tracing and error correction task is easy in function using.
2. Improves Readability: It would be easier for anyone to look at the code and be able to understand the
flow and purpose of the code.
3.The Error finding, Debugging and Correction is easy.
In Python, it is also possible for programmer to write their own function(s). These functions can then
be combined to form module which can be used in other programs by importing them. To define a
function, keyword 'def' is used. After the keyword comes an identifier i.e. name of the function,
followed by parenthesized list of parameters and the colon which ends up the line, followed by the
block of statement(s) that are the part of function.
Syntax:
def NAME ([PARAMETER1, PARAMETER2, …..]):
#Square brackets include optional part of statement statement(s)
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
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. You can also
define parameters inside these parentheses.
The code block within every function starts with a colon (:) and is indented.
The first statement is called a docstring and it is optional. It is similar to a Comment / Remark
statement.
The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is not return None.
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function (or) directly from the Python prompt. Following is the example to call printme() function −
Function Arguments
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
>>> def sum(a,b):
return a+b
Output : 5
Suppose if we pass only one argument, the interpreter complains.
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 is able to
use the keywords provided to match the values with parameters. You can also make keyword calls to
the printme() function in the following ways −
The following example gives more clear picture. Note that the order of parameters does not matter.
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it prints
default age if it is not passed –
An asterisk (*) is placed before the variable name that holds the values of tuple. This tuple remains
empty if no additional arguments are specified during the function call. Following is a simple example
When the above code is executed, it
# Function definition is here produces the following result −
>>> def sayhello(*names): Output is:
for name in names: >>> sayhello('Ayushi','Leo','Megha')
print("Hello, {name}") Hello, Ayushi
Hello, Leo
Hello, Megha
And then when you call the function with a number of arguments, they get wrapped into a Python
tuple. We iterate over them using the for loop in python.
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.
All the above examples are not returning any value. You can return a value from a function as follows
2. BUILT IN FUNCTION:
Built in functions are the function(s) that are built into Python and can be accessed by
Programmer. 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 as most of the functions have
been partitioned to modules. This was done to keep core language precise.
3. THE ANONYMOUS / LAMBDA FUNCTION:
These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression
Syntax
The syntax of lambda functions contains only a single statement, which is as
follows −
Value of total : 30
Value of total : 40
Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
o/p : 15
Example
Lambda functions can take any number of arguments:
Multiply argument a with argument b and return the result:
x = lambda a, b : a * b
print(x(5, 6))
o/p: 30
def giveMeAFunction(varName):
if (varName == "even"):
return lambda x: x % 2 == 0
elif (varName == "odd"):
return lambda x: x % 2 != 0
Recursive Functions
Functions can even call themselves! Such functions are known as recursive functions.
def getFactorial(num):
factorial = 1
retValue = getFactorial(4)
The output shows how the function calls itself for all the integers starting from 4 to 1.
[user@codingtree]$ python3 function_recursive.py
Computing factorial for 4
Computing factorial for 3
Computing factorial for 2
Computing factorial for 1
The factorial of 4 is 24
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier.
There are two basic scopes of variables in Python −
Global variables
Local variables
Global vs. Local variables (Program to be added)
Variables that are defined inside a function body have a local scope, and those defined outside have a
global scope.
This means that local variables can be accessed only inside the function in which they are declared,
whereas global variables can be accessed throughout the program body by all functions. When you
call a function, the variables declared inside it are brought into scope. Following is a simple example –
Here we have a function add() that adds two numbers passed to it as parameters. Later after function
declaration we are calling the function twice in our program to perform the addition.
def SI(P,R,T):
return(P*R*T)
Output:
>>> SI(1000,2,10)
20000
Default arguments in Function
By using default arguments we can avoid the errors that may arise while calling a function without
passing all the parameters.
In this example we have provided the default argument for the second parameter, this default argument
would be used when we do not provide the second parameter while calling this function.
FunctionTest.py
def result(m1,m2,m3):
ttl=m1+m2+m3
percent=ttl/3
if percent>=50:
print ("Result: Pass")
else:
print ("Result: Fail")
return
Run the above script in IDLE with two different sets of inputs is shown below:
Indentation :
In Python, Programs get structured through Usually,
we expect indentation from any program code, but in
Python it is a requirement and not a matter of style. This principle makes the code look cleaner and
easier to understand and read.
Any statements written under another statement with the same indentation is interpreted to belong to
the same code block.
If there is a next statement with less indentation to the left, then it just means the end of the previous
code block.
In other words, if a code block has to be deeply nested, then the nested statements need to be indented
further to the right.
1. Write a program to input any number and to print all natural numbers up to given number.
Code:
n = input("enter any number")
for i in range(1,n+1):
print i, Output:
enter any number10
1 2 3 4 5 6 7 8 9 10
2. Write a program to input any number and to find sum of all natural numbers up to given number.
Code:
n = input("Enter any number")
sum= 0
for i in range(1,n+1):
sum = sum+i print "sum=",sum
Output:
Enter any number5 sum = 15
3. Write a program to input any number and to find reverse of that number.
Code:
n = input("Enter any number")
r = 0 while(n>0):
r = r*10+n%10 n = n/10
Output:
>>>
Enter any number345 reverse number is 543
>>>
1. sum = 0
for i in range(1,11,2):
sum+ = i
print "sum = ", sum output:
sum = 25
2. sum = 0 i = 4
while (i<=20): sum+=i i+= 4
print "Sum = ",sum output:
Sum = 60
1. for i in range(10,26,2):
print i
Ans: i=10 while(i<26):
print i
i+=2
2. s=0
for i in range(10,50,10):
s + =i
print " Sum= ", s
Ans:
s=0
i = 10 while(i<50):
s+ = i i+ = 10
print "Sum=",s
1. for i in range(10,50,5):
print i
Ans:
i values are 10,15,20,25,30,35,40,45
8 times
2. i=4 while(i<25):
print i i+=4
Ans:
i values are 4,8,12,16,20,24
6 times
Program to Find If a Given Number Is Odd or Even
number = int(input("Enter a number"))
if number % 2 == 0:
print(f"{number} is Even number")
else:
print(f"{number} is Odd number")
Output
Enter a number: 45
45 is Odd number
Program to Check If a Given Year Is a Leap Year
year = int(input('Enter a year'))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
else:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
Output
Enter a year 2014
2014 is not a Leap Year
Program to Find the Average of n Natural Numbers, Where n Is the Input from the User
number = int(input("Enter a number up to which you want to find the average"))
i=0
sum = 0
count = 0
while i < number:
i=i+1
sum = sum + i
count = count + 1
average = sum/count
print(f"The average of {number} natural numbers is {average}")
Output
Enter a number up to which you want to find the average 5
The average of 5 natural numbers is 3.0