0% found this document useful (0 votes)
2 views32 pages

Python Basics

This document provides an introduction to programming concepts, focusing on Python. It covers the basics of writing programs, installing Python, using the IDE, and understanding variables, assignments, and operators. Additionally, it discusses string operations, comments, and functions in Python, along with examples and explanations of various programming constructs.
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)
2 views32 pages

Python Basics

This document provides an introduction to programming concepts, focusing on Python. It covers the basics of writing programs, installing Python, using the IDE, and understanding variables, assignments, and operators. Additionally, it discusses string operations, comments, and functions in Python, along with examples and explanations of various programming constructs.
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

Unit 1

Chapter-1

INTRODUCTION

What Is a Program
A program is a sequence of instructions that specifies how to perform a computation.

The computation might be something mathematical, such as solving a system of equations or finding the roots of a
polynomial, but it can also be a symbolic computation, such as searching and replacing text in a document or
something graphical, like processing an image or playing a video.

few basic instructions appear in just about every language:


input:
Get data from the keyboard, a file, the network, or some other device.
output:
Display data on the screen, save it in a file, send it over the network, etc.
math:
Perform basic mathematical operations like addition and multiplication.
conditional execution:
Check for certain conditions and run the appropriate code.
repetition:
Perform some action repeatedly, usually with some variation.

Install and Run Python:


Installing Python
Download the latest version of Python.
Run the installer file and follow the steps to install Python During the
install process, check Add Python to environment variables. This will add Python to environment
variables, and you can run Python from any part of the computer. Also, you can choose the path
where Python is installed.

Installing Python on the computer


Once you finish the installation process, you can run Python.

1. Run Python in Immediate mode

Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.
Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit() and press enter.

Running Python on the Command Line

2. Run Python in the Integrated Development Environment (IDE)


IDE is a piece of software that provides useful features like code hinting, syntax highlighting
and checking, file explorers, etc. to the programmer for application development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use it to
run Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.

Python IDLE
Now you can create a new file and save it with .py extension.
For example, [Link]
Write Python code in the file and save it.
To run the file, go to Run > Run Module or simply click F5.
Running a Python program in IDLE
The First Program:

>>> print('Hello, World!')


This is an example of a print statement
the result is the words Hello, World!
The quotation marks in the program mark the beginning and end of the text to be
displayed; they don’t appear in the result.
The parentheses indicate that print is a function.

Operators:
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then –

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 b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on operators a**b =10 to the power
20

// Floor Division - The division of operands where the 9//2 = 4 and


result is the quotient in which the digits after the 9.0//2.0 =
decimal point are removed. But if one of the operands 4.0,
is negative, the result is floored, i.e., rounded away -11//3 = -4,
from zero (towards negative infinity) − -11.0//3 = -4.0

Values and Types


A value is one of the basic things a program works with, like a letter or a number.
Some values we have seen so far are 2, 42.0, and 'Hello, World!'
These values belong to different types: 2 is an integer, 42.0 is a floating-point number
and 'Hello, World!' is a string

If you are not sure what type a value has, the interpreter can tell you:
>>> type(2)
<class 'int'>
>>> type(42.0)
<class 'float'>
>>> type('Hello, World!')
<class 'str'>
In these results, the word “class” is used in the sense of a category; a type is a category
of values.
What about values like '2' and '42.0'? They look like numbers, but they are in quotation
marks like strings:
>>> type('2')
<class 'str'>
>>> type('42.0')
<class 'str'>
Therefore they’re strings.
Chapter-2

Variables, Assignments and Statements

[Link] assignment statement creates a new variable and gives it a value:


>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.141592653589793
This example makes three assignments.
The first assigns a string to a new variable named message; the second gives the integer 17 to n;
the third assigns the (approximate) value of π to pi
Variable Names
Programmers generally choose names for their variables that are meaningful Variable names can be as
long as you like.
Rules for naming :
They can contain both letters and numbers,but they can’t begin with a number. Can use both lower
and uppercase [Link] underscore character, _, can appear in a name. Keywords should not use as a
variable name.

Note: If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade'


SyntaxError: invalid syntax b’ coz it begins with a number
>>> more@ = 1000000
SyntaxError: invalid syntax b’ coz it contains illegal character @.
>>> class = 'Adanced Theoretical Zymurgy'
Keywords in Python:
False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and,
del, global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, raise.

Expressions and Statements:


An expression is a combination of values, variables, and operators. A value all by itself is considered an
expression, and so is a variable, so the following are all legal expressions:
>> 42
42
>>> n
17
>>> n + 25
42
When you type an expression at the prompt, the interpreter evaluates it, which
means that it finds the value of the expression. In this example, n has the value 17 and
n + 25 has the value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a
value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a value to n. The second line is a print statement
that displays the value of n.

2. Script Mode:

Inscript mode type code in a file called a script and savefile with .py extention. script mode to execute
the script. By convention, Python scripts have names that end with .py.
for ex: if you type the following code into a script and run it, you get no output at all. Why because but it
doesn’t display the value unless you tell it to. But it displays in interactive mode.
miles = 26.2
miles * 1.61
Sol is:
miles = 26.2
print(miles * 1.61)

3. Order of perations:

When an expression contains more than one operator, the order of evaluation depends on the order of
[Link] mathematical operators, Python follows order PEMDAS.
P-parentheses,
E- Exponentiation,
M- Multiplication
D-Division
A-Addition,
S- Substraction

• Parentheses have the highest precedence.


For ex in the following expressions in parentheses are evaluated first,
Ex:1. 2 * (3-1) is 4, and
Ex: 2. (1+1)**(5-2) is 8.
• Exponentiation has the next highest precedence,
For ex: 1 + 2**3 is 9, not 27, and
2 * 3**2 is 18, not 36.
• Multiplication and Division have higher precedence than Addition and Subtraction.
For ex: 2*3-1 is 5, not 4, and 6+4/2 is 8, not 5.
Note: Operators with the same precedence are evaluated from left to right (except
exponentiation). So in the expression degrees / 2 * pi, the division happens first and the result is
multiplied by pi.

4. Operations on strings:

Note : Mathematical operations on strings are not allowed so the following are illegal:
'2'-'1' 'eggs'/'easy' 'third'*'a charm'

How to Create Strings in Python?


Creating strings is easy as you only need to enclose the characters either in single or double-quotes.
In the following example, we are providing different ways to initialize [Link] share an important note
that you can also use triple quotes to create strings. However, programmers use them to mark multi-line
strings and docstrings.
# Python string examples - all assignments are identical.
String_var = 'Python'
String_var = "Python"
String_var =
"""Python"""

# with Triple quotes Strings can extend to multiple lines


String_var = """ This document will help you to explore all the concepts of Python
Strings!!! """

# Replace "document" with "tutorial" and store in another variable


substr_var = String_var.replace("document", "tutorial")
print (substr_var)

String Operators in Python


Concatenation (+):It combines two strings into
one.
# example
var1 = 'Python'
var2 = 'String'
print (var1+var2) # PythonString Repetition (*):This operator creates a new string by repeating
it a given number of times.
# example
var1 = 'Python'
print (var1*3)
# PythonPythonPython

Slicing [ ]:The slice operator prints the character at a given index.


# example
var1 = 'Python'
print (var1[2]) # t
Range Slicing [x:y]
It prints the characters present in the given range.
# example
var1 = 'Python'
print (var1[2:5]) # tho

Membership (in):This operator returns ‘True’ value if the character is present in the given String.
# example
var1 = 'Python'
print ('n' in var1) # True
Membership (not in):
:
It returns ‘True’ value if the character is not present in the given String.
# example
var1 = 'Python'
print ('N' not in var1)
# True

Iterating (for): With this operator, we can iterate through all the characters of a string.
# example
for var in var1: print (var, end ="") # Python

Raw String (r/R):We can use it to ignore the actual meaning of Escape characters inside a string.
For this, we add ‘r’ or ‘R’ in front of the String.
# example
print (r'\n') # \n
print (R'\n') # \n

Unicode String support in Python


Regular Strings stores as the 8-bit ASCII value, whereas Unicode String follows the 16-bit
ASCII standard. This extension allows the strings to include characters from the different
languages of the world. In Python, the letter ‘u’ works as a prefix to distinguish between
Unicode and usual strings.
print (u' Hello Python!!')

OUTPUT:

#Hello Python

Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case


center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was found

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string


lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of where it was
found

rindex() Searches the string for a specified value and returns the last position of where it was
found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string


split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

But there are two exceptions, + and *.


The + operator performs string concatenation,
For example:
>>> first = 'throat'
>>> second = 'warbler'
>>> first + second
throatwarbler
The * operator also works on strings; it performs repetition.
For example, 'Spam'*3 is 'SpamSpamSpam'.
EXAMPLE1:
var1 = 'Hello World!'
var2 = "Python Programming"

print "var1[0]: ", var1[0]


print "var2[1:5]: ", var2[1:5]
When the above code is executed, it produces the following result −
var1[0]: H
var2[1:5]: ytho

EXAMPLE2:
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
When the above code is executed, it produces the following result −
Updated String :- Hello Python

5. Comments:
Comments are of two types .
Single-line comments
Multi line Comments
Single-line comments are created simply by beginning a line with the hash (#) character,
and they are automatically terminated by the end of line.
For Ex: #This would be a comment in Python
Multi Line Comments that span multiple lines and are created by adding a delimiter (“””) on
each end of the comment
For Ex:
"""
This would be a multiline comment in Python that spans several lines and describes your code,
your day, or anything you want it to """

Chapter-3
Functions

What is a Function in Python?


A Function in Python is used to utilize the code in more than one place in a program. It is
also called method or procedures. Python provides you many inbuilt functions like print(),
but it also gives freedom to create your own functions.
Functions:
A function is a named sequence of statements that performs a computation.
How to define and call a function in Python

Function in Python is defined by the "def " statement followed by the function name and
parentheses ( () )
Example:
Let us define a function by using the command " def func1():" and call the function. The
output of the function will be "I am learning Python function"

The function print func1() calls our def func1(): and print the command " I am learning
Python function None."There are set of rules in Python to define a [Link] args or input
parameters should be placed within these [Link] function first statement can be an
optional statement- docstring or the documentation string of the function The code within
every function starts with a colon (:) and should be indented (space) The statement return
(expression) exits a function, optionally passing back a value to the caller. A return statement
with no args is the same as return None.
Significance of Indentation (Space) in Python:

Before we get familiarize with Python functions, it is important that we understand the
indentation rule to declare Python functions and these rules are applicable to other elements
of Python as well like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code, since Python functions
don't have any explicit begin or end like curly braces to indicate the start and stop for the
function, they have to rely on this indentation. Here we take a simple example with "print"
command. When we write "print" function right below the def func 1 (): It will show an
"indentation error: expected an indented block".
Now, when you add the indent (space) in front of "print" function, it should print as expected.

How Function Return Value?


Return command in Python specifies what value to give back to the caller of the function.
Let's understand this with the following example
Step 1) Here - we see when function is not "return". For example, we want the square of 4,
and it should give answer "16" when the code is executed. Which it gives when we simply
use "print x*x" code, but when you call function "print square" it gives "None" as an output.
This is because when you call the function, recursion does not happen and fall off the end of
the function. Python returns "None" for failing off the end of the function.
Step 2) To make this clearer we replace the print command with assignment command. Let's
check the output.

When you run the command "print square (4)" it actually returns the value of the object since
we don't have any specific function to run over here it returns "None".
Step 3) Now, here we will see how to retrieve the output using "return" command. When you
use the "return" function and execute the code, it will give the output "16."
Step 4) Functions in Python are themselves an object, and an object has some value. We will
here see how Python treats an object. When you run the command "print square" it returns
the value of the object. Since we have not passed any argument, we don't have any specific
function to run over here it returns a default value (0x021B2D30) which is the location of the
object. In practical Python program, you probably won't ever need to do this.

Arguments in Functions
The argument is a value that is passed to the function when it's [Link] other words on the calling side,
it is an argument and on the function side it is a parameter. Let see how Python Args works -
Step 1) Arguments are declared in the function definition. While calling the function, you can
pass the values for that args as shown below

Step 2) To declare a default value of an argument, assign it a value at function definition.

Example: x has no default values. Default values of y=0. When we supply only one argument
while calling multiply function, Python assigns the supplied value to x while keeping the
value of y=0. Hence the multiply of x*y=0
Step 3) This time we will change the value to y=2 instead of the default value y=0, and it will
return the output as (4x2)=8.

Step 4) You can also change the order in which the arguments can be passed in Python. Here
we have reversed the order of the value x and y to x=4 and y=2.
Step 5) Multiple Arguments can also be passed as an array. Here in the example we call the
multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args) function;
it prints out the output as (1,2,3,4,5)

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 [Link] code block within every function starts
with a colon (:) and is indented. The statement return [expression] exits a function, but it is
optional

Syntax:
def functionname( parameters ):
function_suite
return [expression]
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")

my_function() #calling function

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function are not visible from outside the function. Hence, they
have a local scope.

The lifetime of a variable is the period throughout which the variable exits in the memory.
The lifetime of variables inside a function is as long as the function [Link] are
destroyed once we return from the function. Hence, a function does not remember the value
of a variable from its previous [Link] is an example to illustrate the scope of a variable
inside a function.
def my_func():
x = 10
print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)
Output
Value inside function: 10
Value outside function: 20

2. Math Functions:
Python has a math module that provides mathematical functions. A module is a file that
contains a collection of related [Link] we can use the functions in a module, we
have to import it with an import statement:
>>> import math

Note: The module object contains the functions and variables defined in the module. To
access one of the functions, you have to 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.
For ex:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)
>>> radians = 0.7
>>> height = [Link](radians)
Some Constants
These constants are used to put them into our calculations.
[Link]. Constants & Description

1 pi - Return the value of pi: 3.141592

4 inf - Returns the infinite

5 nan - Not a number type.

Numbers and Numeric Representation


These functions are used to represent numbers in different forms. The methods are like below

[Link]. Function & Description

1 ceil(x)
Return the Ceiling value. It is the smallest integer, greater or equal to the number
x.

3 fabs(x)
Returns the absolute value of x.

4 factorial(x)
Returns factorial of x. where x ≥ 0

5 floor(x)
Return the Floor value. It is the largest integer, less or equal to the number x.

6 fsum(iterable)
Find sum of the elements in an iterable object

7 gcd(x, y)
Returns the Greatest Common Divisor of x and y

8 isfinite(x)
Checks whether x is neither an infinity nor nan.

9 isinf(x)
Checks whether x is infinity

10 isnan(x)
Checks whether x is not a number.

11 remainder(x, y)
Find remainder after dividing x by y

Example program:
import math
print([Link](23.56) )

my_list = [12, 4.25, 89, 3.02, -65.23, -7.2, 6.3]


print([Link](my_list))
print('The GCD of 24 and 56 : ' + str([Link](24, 56)))
x = float('nan')
if [Link](x):
print('It is not a number')
x = float('inf')
y = 45
if [Link](x):
print('It is Infinity')
print([Link](x)) #x is not a finite number
print([Link](y)) #y is a finite number

O/P:
24
42.13999999999999
The GCD of 24 and 56 : 8
It is not a number
It is Infinity
False
True
>>>

Power and Logarithmic Functions


These functions are used to calculate different power related and logarithmic related tasks.

[Link]. Function & Description

1 pow(x, y)
Return the x to the power y value.

2 sqrt(x)
Finds the square root of x

3 exp(x)
Finds xe, where e = 2.718281

4 log(x[, base])
Returns the Log of x, where base is given. The default base is e

5 log2(x)
Returns the Log of x, where base is 2
6 log10(x)
Returns the Log of x, where base is 10
Example Code
import math
print('The value of 5^8: ' + str([Link](5, 8)))
print('Square root of 400: ' + str([Link](400)))
print('The value of 5^e: ' + str([Link](5)))
print('The value of Log(625), base 5: ' + str([Link](625, 5)))
print('The value of Log(1024), base 2: ' + str(math.log2(1024)))
print('The value of Log(1024), base 10: ' + str(math.log10(1024)))

Output
The value of 5^8: 390625.0
Square root of 400: 20.0
The value of 5^e: 148.4131591025766
The value of Log(625), base 5: 4.0
The value of Log(1024), base 2: 10.0
The value of Log(1024), base 10: 3.010299956639812

Trigonometric & Angular Conversion Functions

These functions are used to calculate different trigonometric operations.


[Link]. Function & Description

1 sin(x)
Return the sine of x in radians

2 cos(x)
Return the cosine of x in radians

3 tan(x)
Return the tangent of x in radians

4 asin(x)
This is the inverse operation of the sine, there are acos, atan
also.

5 degrees(x)
Convert angle x from radian to degrees

6 radians(x)
Convert angle x from degrees to radian
Example Code
import math
print('The value of Sin(60 degree): ' + str([Link]([Link](60))))
print('The value of cos(pi): ' + str([Link]([Link])))
print('The value of tan(90 degree): ' + str([Link]([Link]/2)))
print('The angle of sin(0.8660254037844386): ' +
str([Link]([Link](0.8660254037844386))))
Output
The value of Sin(60 degree): 0.8660254037844386
The value of cos(pi): -1.0
The value of tan(90 degree): 1.633123935319537e+16
The angle of sin(0.8660254037844386): 59.99999999999999

3. Composition:
So far, we have looked at the elements of a program—variables, expressions, and statements—in
isolation, without talking about how to combine(Composition) [Link] example, the argument of a
function can be any kind of expression, including arithmetic operators:
x = [Link](degrees / 360.0 * 2 * [Link])
And even function calls:
x = [Link]([Link](x+1))

4. Adding new functions:


Pass by reference vs value:All parameters (arguments) in the Python language are passed by reference. It
means if you change what a parameter refers to within a function, the change also reflects back in the calling
function. For example −

#!/usr/bin/python

# Function definition is here


def changeme( mylist ):
"This changes a passed list into this function"
[Link]([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Here, we are maintaining reference of the passed object and appending values in the same
object. So, this would produce the following result −
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

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 [Link] 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:Variables that are defined inside a function body have a local scope,
and those defined outside have a global [Link] 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 −
#!/usr/bin/python

total = 0; # This is global variable.


# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0

The import Statement


You can use any Python source file as a module by executing an import statement in some
other Python source file. The import has the following syntax −
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the module if the module is
present in the search path. A search path is a list of directories that the interpreter searches
before importing a module. For example, to import the module [Link], you need to put
the following command at the top of the script −
#!/usr/bin/python

# Import module support


import support

# Now you can call defined function that module as follows


support.print_func("Zara")
When the above code is executed, it produces the following result −
Hello : Zara

5. Flow of Execution

The order in which statements are executed is called the flow of execution
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order, from top to bottom.
Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it left off.

6. Parameters and Arguments:


Parameter: The terms parameter and argument can be used for the same thing: information
that are passed into a [Link] a function's perspective:
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called. Arguments
You can call a function by using the following types of formal arguments –
[Link] arguments
[Link] arguments
[Link] arguments
[Link]-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.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a
syntax error as follows −

#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "[Link]", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

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
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 −
#!/usr/bin/python

# Function definition is here


def printme( str ):
"This prints a passed string into this function"
print str
return;

# Now you can call printme function


printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives more clear picture. Note that the order of parameters does not
matter.
#!/usr/bin/python

# Function definition is here


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=50, name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50

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. The following example gives an idea on default
arguments, it prints default age if it is not passed −

#!/usr/bin/python

# Function definition is here


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=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you specified while defining
the function. These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default [Link] for a function with non-
keyword variable arguments is this − def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call. Following is a simple example −
#!/usr/bin/python

# Function definition is here


def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50

Example
def my_function(fname):
print(fname +" krishna")
my_function("Rama")
my_function("Siva")
my_function("Hari")
o/p: Ramakrishna
Sivakrishna
Harikrishna.

Parameters Vs Arguments
A parameter is the variable listed inside the parentheses in the function definition.
An argument is the value that is sent to the function when it is called.

Number of Arguments
A function must be called with the correct number of arguments. Meaning that if your
function expects 2 arguments, you have to call the function with 2 arguments, not more, and
not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname +" "+ lname)
my_function("Srinu", "vasulu")

Arbitrary Arguments( *args)


If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access the items
accordingly:
Example
If the number of arguments is unknown, add a * before the parameter name:
def my_function(*kids):
print("The youngest child is "+ kids[2])
my_function("raju", "somu", "vijay)
O/p: vijay

Default Parameter Value:


When we call the function without argument, it uses the default value:
Example
def my_function(country = "Norway"): #default value is Norway
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function() #o/p: Norway
my_function("Brazil")

Passing a List as an Argument:


You can send any data types of argument to a function (string, number, list, dictionary etc.)
E.g. if you send a List as an argument, it will still be a List when it reaches the function:
Example
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)

Return Values:
To return a value, we use the return statement:
Example
def my_function(x):
return 5 * x

print(my_function(3)) # o/p: 15
print(my_function(5)) # o/p: 25
print(my_function(9)) # o/p: 45

The pass Statement


function definitions cannot be empty, but if you for some reason have a function definition
with no content, put in the pass statement to avoid getting an error.
Example
def myfunction():
pass
7. Variables and Parameters Are Local
When you create a variable inside a function, it is local, which means that it only
exists inside the function.
For example:
def cat_twice(part1, part2):
cat = part1 + part2
print_twice(cat)

line1 = 'Bing tiddle '


line2 = 'tiddle bang.'
cat_twice(line1, line2)
print(cat) #error

here cat_twice terminates, the variable cat is destroyed. If we try to print it, we get
an exception:
>>> NameError: name 'cat' is not defined

8. Stack Diagrams:
Stack diagram used to keep track of which variables can be used which function.
For ex, consider the following code:

def cat_twice(part1, part2):


cat = part1 + part2
print_twice(cat)

line1 = 'Bing tiddle '


line2 = 'tiddle bang.'
cat_twice(line1, line2)

Stack diagram for above code is:

Here each function is represented by a frame. A frame is a box with the name of a function
beside it and the parameters and variables of the function inside it.
The frames are arranged in a stack that indicates which function called which, and so on. In
this example, print_twice was called by cat_twice, and cat_twice was called by main ,
which is a special name for the topmost frame. When you create a variable outside of any
function, it belongs to main .

9. Fruitful Functions and Void Functions


The function that returns a value is called fruitful function.
The function that does not returns any value is called void function.

Fruitful Functions:
Ex :def add(x,y):
return (x+y)

Z
=
a
d
d
(
1
,
2
)

p
r
i
n
t
(
z
)

void Functions:
Ex : def add(x,y):
print(x+y)

add(1,2)

10. Why Functions?

There are several reasons for why functions:


• improves readability: Creating a new function gives you an opportunity
to name a group of statements, which makes your program easier to read
and debug.
• debugging easy : Functions can make a program smaller by eliminating
repetitive code. Later, if you make a change, you only have to make it in
one place.
• modularity: Dividing a long program into functions allows you to
debug the parts one at a time and then assemble them into a working
whole.
• reusability : Well-designed functions are often useful for many
programs. Once you write and debug one, you can reuse it.

You might also like