Python CS1002 PDF
Python CS1002 PDF
Introduction to Python
Section I
VI
•Anything after #symbol is comment.
ex: print “Hello world”
avg=sum/num #computes the average of values
•Comments are not part of command which can be used by
anyone reading code.
•Indentation : A code block (body of a function, loop etc.)
starts with indentation and ends with the first unindented
line. The amount of indentation is up to you, but it must be
consistent throughout that block.
•Generally four whitespaces are used for indentation and is
preferred over tabs.
Input, Output operation in in python
VI
Python provides numerous built-in functions that are readily
available to us at the Python prompt.
Some of the functions like input() and print() are widely used
for standard input and output operations respectively.
We use the print() function to output data to the standard
output device (screen).
How to read and write in Python
Every program is eventually a data processor, so we should
VI
know how to input and output data within it. There exists a
function, print(), to output data from any Python program. To use
it, pass a comma separated list of arguments that you want to
print to the print() function. Let's see an example. Press "run"
and then "next" to see how the program is being executed line by
line:
print(5 + 10) # Result : 15
print(3 * 7, (17 - 2) * 8) # Result : 21 120
print(2 ** 16) # two stars are used for exponentiation (2 to the
power of 16) # Result : 65536
print(37 / 3) # single forward slash is a division (12.3333)
print(37 // 3) # double forward slash is an integer division #
it returns only the quotient of the division (i.e. no remainder)
print(37 % 3) # percent sign is a modulus operator # it gives
the remainder of the left value divided by the right value ( Result
: 1)
How to read and write in Python
Here's a program that reads the user's name and greets them:
a = input()
b = input()
s=a+b
print (s)
Note: After running the example we can see that it prints 57. As we were
taught in school, 5 + 7 gives 12. So, the program is wrong, and it's important
to understand why. The thing is, in the third line s = a + b Python has
"summed" two strings, rather than two numbers. The sum of two strings
in Python works as follows: they are just glued one after another. It's also
sometimes called "string concatenation".
Sum of numbers and strings
a = int(input())
b = int(input())
s=a+b
print(s)
Example:
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can even
change type after they have been set.
Python Variables - Example
VI x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable Names
Variables of numeric types are created when you assign a value to them:
Example :
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
Example :
print(type(x))
print(type(y))
print(type(z))
Int
print(type(x))
print(type(y))
print(type(z))
Float
VI Note:
Float can also be scientific numbers with an "e" to indicate
the power of 10.
Example
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Example:
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Python Operators
VI
- Subtraction Subtracts right hand operand from left hand a – b = -10
Arithmetic operators are used with numeric values to
operand.
perform common mathematical operations:
* Multiplication Multiplies values on either side of the operator a * b = 200
!= Not equal x != y
Bitwise operator:
Operator meaning
& Bitwise AND
∣ Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift
<< Bitwise left shift
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
VI Sr.No. Operator & Description
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
Control flow statement
Decision making :
VI 1. if statement
2. if … else
3. if … else if …else
4. Nested if statement
Example :
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
if…else
VI if else conditional statement in Python has the following syntax:
if condition: true-block several instructions that are executed if
the condition evaluates to True
else: false-block several instructions that are executed if the
condition evaluates to False
Syntax :
if (condition/test expression):
statement1
statement 2 True block
else:
statement 1
statement 2 false block
statement x
if…else
VI Prog: Given number is positive and Negative
There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the nested if
construct.
Output:
Enter the number:12
Enter the number: 34
Enter the number: 56
12 is less than 34 and 56
End of Nested if
Example : Nested if
VI Prog: find largest among 3 number
VI The elif statement allows you to check multiple expressions for TRUE
and execute a block of code as soon as one of the conditions evaluates
to TRUE.
Similar to the else, the elif statement is optional. However,
unlike else, for which there can be at most one statement, there can be
an arbitrary number of elif statements following an if.
Output
3 - Got a true expression value
100
Good bye!
if...elif...else construct
VI var = 100
if var < 200:
print ("Expression value is less than 200")
if var == 150:
print ("Which is 150")
elif var == 100:
print ("Which is 100")
elif var == 50:
print ("Which is 50")
elif var < 50:
print ("Expression value is less than 50")
else:
print ("Could not find true expression")
print ("Good bye!")
output
Expression value is less than 200
Which is 100
Good bye!
Nested condition
VI x = int(input( ))
y = int(input( ))
if x > 0:
if y > 0:
# x is greater than 0, y is greater than 0
print("Quadrant I")
else:
# x is greater than 0, y is less or equal than 0
print("Quadrant IV")
else:
if y > 0:
# x is less or equal than 0, y is greater than 0
print("Quadrant II")
else:
# x is less or equal than 0, y is less or equal than 0
print("Quadrant III")
Input Output
2 Quadrant IV
-3
if-elif-else
VI For the given integer X print 1 if it's positive, -1 if it's negative, or 0 if it's equal to
zero.
Try to use the cascade if-elif-else for it.
x = int(input( ))
if x > 0:
print(1)
elif x == 0:
print(0)
else:
print(-1)
Examples
VI Write a python program where a student can get a grade based on marks that he has
scored in any subject. Suppose that marks 90 and above are A’s, marks in the
80s are B’s, 70s are C’s, 60s are D’s, and anything below 60 is an F.
Code:
grade = int (input('Enter your score: '))
if grade>=90:
print('A')
if grade>=80 and grade<90:
print('B')
if grade>=70 and grade<80:
print('C')
if grade>=60 and grade<70:
print('D')
if grade<60:
print('F')
Examples
VI Write a program that asks the user to enter a length in centimeters. If the user enters
a negative length, the program should tell the user that the entry is invalid.
Otherwise, the program should convert the length to inches and print out the result.
There are 2.54 centimeters in an inch.
Code:
len = float(input('Enter length in centimeters: '))
if(len<0):
print("The entry is invalid")
else:
inch=len/2.54
print("Equivalent length in inches is:", inch)
Examples
VI Write a program that asks the user for two numbers and prints ‘Numbers are Close’
if the numbers are within 0.001 of each other and ‘Numbers are not close’
otherwise.
Code:
n1 = float(input('Enter number 1: '))
n2 = float(input('Enter number 2: '))
if(n2-n1<=0.001):
print("Numbers are close")
else:
print("Numbers are not close")
Examples
VI Given three integers, determine how many of them are equal to each other. The
program must print one of these numbers: 3 (if all are the same), 2 (if two of them
are equal to each other and the third is different) or 0 (if all numbers are different)
Code:
a = int(input())
b = int(input())
c = int(input())
if a == b == c:
print(3)
elif a == b or b == c or a == c:
print(2)
else:
print(0)
VI
While - loop
end=12
n=1
while(n<=end):
print(n)
n = n+1
Result : It will print 1 to 12
While - loop
Write a program to find the sum of the digits of a given number
VI
num=int(input("please enter the number"))
x=num
sum=0
rem=0
while(num>0): #while loop is used &last digit of number is obtained by
rem=num%10 using modulus operator ,so it gives remainder
num=num//10 # (123/10) it will gives only 12 number (gives only integer)
sum=sum+rem # rem is added to variable sum each time the loop exexutes
print("sum of the digits of an entered number",x,"is=",sum)
Output:
please enter the number123
sum of the digits of an entered number 123 is= 6
Note: The integer number is read from the user. And it is stored in variable num
. Initially the value of sum and rem are initialized to 0. Unless and until the value of
num>0 the statement within the loop continue to be executed. The modulus operator
And division operator are used frequently to obtain the sum of the numbers enterd.
While - loop
Write a program to print factorial of a number using while loop
VI
num=int(input("please enter the number:"))
fact=1
ans=1
while(fact<=num):
ans=ans*fact
fact=fact+1
print("factorial of ",num," is: ",ans)
Output:
please enter the number:6
factorial of 6 is: 720
else: While - loop
count = 0
while count < 5:
print (count, " is less than 5")
count = count + 1
else:
print (count, " is not less than 5")
Result:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
While – loop - continue
Flow Diagram :
Example: While – loop - continue
VI var = 10
while var > 0: false
Condi
var = var -1 tion?
if var == 5: Exit loop
continue True
print ('Current variable value :', var)
print ("Good bye!")
VI It terminates the current loop and resumes execution at the next statement,
just like the traditional break statement in C.
The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax:
The syntax for a break statement in Python is as follows −
break
Flow Diagram:
Example: While – loop - break
Example:
range ( 0,n,1)
Where n is end or stop element , then last element should be n-1
i.e 0
1
2
n-1
The range( ) function
VI
A statement that is executed sequentially and allow us to to
execute group of statements multiple times.
It has the ability to iterate over the items of any sequence, such
as a list or a string.
Syntax:
for variable in sequence:
statements(s)
Output:
h
e
l
l
o
2. for i in range(10): # 0 to 9
print(“Hello world”)
Output:
hello world ( 10 times printed)
Example using for loop
Output:
Sachin
Rahul
Saurabh
Example using for loop
Output:
5
10
15
20
25
30
35
40
45
50
Note : if last element is 51 to 55 then it print up to 50. if last element is less
than 51 then it print up to 45. if last element is greater than 55 then it print up
to 55.
Example using for loop
VI Code:
for i in range(2):
print(i)
i=i+50
print(i)
Output:
0
50
1
51
Example using for loop
VI Code:
for i in range(10):
print(i)
i=i+50
print(i)
Output:
0
50
1
51
2
52
3
53
∣
∣
∣
9
59
Example using for loop
VI Code:
for j in range(10):
for i in range(j+1):
print("*",end="")
print()
Output:
*
*
*
*
*
*
*
*
*
*
Example using for loop
Program:
for i in range(5,8):
print(i, i ** 2)
print(‘end of loop’)
Output:
5 25
6 36
7 49
end of loop
VI print(1, 2, 3)
print(4, 5, 6)
Output:
123
456
print(1, 2, 3,end=',')
print(4, 5, 6)
Output
1 2 3,4 5 6
Example using for loop
VI By default, the function print( ) prints all its arguments separating them by a
space and the puts a newline symbol after it. This behavior can be changed
using keyword arguments sep (separator) and end.
e.g.
print(1, 2, 3) Output
print(4, 5, 6) 123
print(1, 2, 3, sep=', ', end='. ') 456
print(4, 5, 6, sep=', ', end='. ') 1, 2, 3. 4, 5, 6.
print( ) 123 -- 4 * 5 * 6.
print(1, 2, 3, sep=‘ ’, end=' -- ')
print(4, 5, 6, sep=' * ', end='.')
for loop with break
VI Problem: WAP using break statement to print first three letters in “string”
Output:
s
t
r
for loop with continue
Output:
s
t
r
n
g
for loop with continue
Output:
1
2
3
4
6
7
8
9
Python - Numbers
round(x x rounded to n digits from the decimal point. Python rounds away
[,n]) from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -
1.0.
sqrt(x) The square root of x for x > 0.
Mathematical Functions/ math module
VI
1.Python Number abs() : The method abs() returns absolute value of x - the
(positive) distance between x and zero.
Syntax:
Following is the syntax for abs() method −
abs( x )
Parameters
x − This is a numeric expression.
Return Value
This method returns absolute value of x.
Example:
print ("abs(-45) : ", abs(-45))
print ("abs(100.12) : ", abs(100.12))
print ("abs(119) : ", abs(119))
Output:
abs(-45) : 45
abs(100.12) : 100.12
abs(119) : 119
Mathematical Functions
Description
VI The fabs( ) method returns the absolute value of x. Although similar to the abs()
function, there are differences between the two functions.
They are −
•abs( ) is a built in function whereas fabs( ) is defined in math module.
•fabs( ) function works only on float and integer whereas abs( ) works with complex
number also.
Output
math.fabs(-45.17) : 45.17
math.fabs(100.12) : 100.12
math.fabs(100.72) : 100.72
math.fabs(math.pi) : 3.141592653589793
Mathematical Functions
ceil() function :
VI Description
The method ceil() returns ceiling value of x - the smallest integer not
less than x.
Python has many auxiliary functions for calculations with floats.
They can be found in the math module. To use this module, we need to import it first
by writing the following instruction at the beginning of the program:
import math
Syntax
Following is the syntax for ceil() method −
import math
math.ceil( x )
Example:
import math
print("math.ceil(-45.17) : ", math.ceil(-45.17))
print("math.ceil(100.12) : ", math.ceil(100.12))
print("math.ceil(100.72) : ", math.ceil(100.72))
Output:
math.ceil(-45.17) : -45
math.ceil(100.12) : 101
math.ceil(100.72) : 101
exp()
Description:
VI The method exp() returns exponential of x: ex.
Syntax
Following is the syntax for exp() method −
import math
math.exp( x )
Example :
print("math.exp(2) : ", math.exp(2))
print ("math.exp(100.12) : ", math.exp(100.12))
Output:
math.exp(2) : 7.38905609893065
math.exp(100.12) : 3.0308436140742566e+43
floor()
Description
VI The method floor() returns floor of x - the largest integer not greater
than x.
Syntax
Following is the syntax for floor() method −
import math
math.floor( x )
Example:
import math
print ("math.floor(-45.17) : ", math.floor(-45.17))
print ("math.floor(100.12) : ", math.floor(100.12))
Output:
math.floor(-45.17) : -46
math.floor(100.12) : 100
log()
Description:
VI The method log( ) returns natural logarithm of x, for x > 0.
Syntax:
Following is the syntax for log() method −
import math
math.log( x )
Example:
import math
print ("math.log(1) : ", math.log(1))
print ("math.log(100.12) : ", math.log(100.12))
Output:
math.log(1) : 0.0
math.log(100.12) : 4.6063694665635735
sqrt()
VI Description:
The method sqrt() returns the square root of x for x > 0.
Syntax:
Following is the syntax for sqrt() method −
import math
math.sqrt( x )
Example:
import math
print ("math.sqrt(100) : ", math.sqrt(100))
print ("math.sqrt(7) : ", math.sqrt(7))
Output:
math.sqrt(100) : 10.0
math.sqrt(7) : 2.6457513110645907
pow()
Syntax:
math.pow(x,y)
Example:
import math
print ("math.pow(5, 2) : ", math.pow(5, 2))
print ("math.pow(100, 2) : ", math.pow(100, 2))
Output:
math.pow(5, 2) : 25.0
math.pow(100, 2) : 10000.0
Mathematical Functions
Output
VI print ("round(70.23456) : ", round(70.23456)) round(70.23456) : 70
print ("round(56.659,1) : ", round(56.659,1)) round(56.659,1) : 56.7
print ("round(80.264, 2) : ", round(80.264, 2)) round(80.264, 2) : 80.26
print ("round(100.000056, 3) : ", round(100.000056, 3)) round(100.000056, 3) : 100.0
print ("round(-100.000056, 3) : ", round(-100.000056, 3)) round(-100.000056, 3) : -100.0
Description
Output
print ("max(80, 100, 1000) : ", max(80, 100, 1000))
max(80, 100, 1000) : 1000
print ("max(-20, 100, 400) : ", max(-20, 100, 400))
max(-20, 100, 400) : 400
print ("max(-80, -20, -10) : ", max(-80, -20, -10))
max(-80, -20, -10) : -10
print ("max(0, 100, -400) : ", max(0, 100, -400))
max(0, 100, -400) : 100
Description
The method min( ) returns the smallest of its arguments i.e. the value closest to
negative infinity.
Random number function
Output
randrange(1,100, 2) : 83
randrange(100) : 93
The seed( ) method initializes the basic random number generator. Call this function
before calling any other random module function.
Syntax
seed ([x], [y]) import random
random.seed()
print ("random number with default seed", random.random())
random.seed(10)
print ("random number with int seed",random.random())
random.seed("hello",2)
print ("random number with string seed", random.random())
Random number function
VI Description
The shuffle( ) method randomizes the items of a list in place.
Syntax
shuffle (lst,[random])
Description
The uniform( ) method returns a random float r, such that x is less than or equal to r and
r is less than y.
Syntax
uniform(x, y)
Trigonometric Functions -sin()
Description
VI The method sin() returns the sine of x, in radians.
Syntax
Following is the syntax for sin() method −
math.sin(x)
Example:
import math
print ("sin(3) : ", math.sin(3))
print ("sin(-3) : ", math.sin(-3))
print ("sin(0) : ", math.sin(0))
Output:
sin(3) : 0.1411200080598672
sin(-3) : -0.1411200080598672
sin(0) : 0.0
cos()
VI Description:
The method cos( ) returns the cosine of x radians.
Syntax:
Following is the syntax for cos() method −
cos(x)
Example:
print ("cos(3) : ", math.cos(3))
print ("cos(-3) : ", math.cos(-3))
print ("cos(0) : ", math.cos(0))
Output:
cos(3) : -0.9899924966004454
cos(-3) : -0.9899924966004454
cos(0) : 1.0
tan()
VI Description:
The method tan() returns the tangent of x radians.
Syntax:
Following is the syntax for tan() method −
tan(x)
Example:
import math
print ("tan(3) : ", math.tan(3))
print ("tan(-3) : ", math.tan(-3))
print ("tan(0) : ", math.tan(0))
Output:
tan(3) : -0.1425465430742778
tan(-3) : 0.1425465430742778
tan(0) : 0.0
degrees() Method
VI Description
The method degrees() converts angle x from radians to degrees.
Syntax
Following is the syntax for degrees() method −
degrees(x)
Note: This method returns degree value of an angle.
Example:
print ("degrees(3) : ", math.degrees(3))
print ("degrees(-3) : ", math.degrees(-3))
print ("degrees(0) : ", math.degrees(0))
print ("degrees(math.pi) : ", math.degrees(math.pi))
print ("degrees(math.pi/2) : ", math.degrees(math.pi/2))
Output:
degrees(3) : 171.88733853924697
degrees(-3) : -171.88733853924697
degrees(0) : 0.0
degrees(math.pi) : 180.0
degrees(math.pi/2) : 90.0
radians() Method
VI Description
The method radians() converts angle x from degrees to radians.
Syntax
Following is the syntax for radians() method −
radians(x)
Note: This method returns radian value of an angle.
Example:
import math
print ("radians(3) : ", math.radians(3))
print ("radians(math.pi) : ", math.radians(math.pi))
Output:
radians(3) : 0.05235987755982989
radians(math.pi) : 0.05483113556160755
Random Number Functions
VI Random numbers are used for games, simulations, testing, security, and
privacy applications. Python includes following functions that are commonly
used.
Function Description
1.choice(seq) A random item from a list, tuple, or string.
2.randrange ([start,] stop [,step]) A randomly selected element from
range(start, stop, step)
3.random()A random float r, such that 0 is less than or equal to r and r is less
than 1
4.seed([x])Sets the integer starting value used in generating random numbers.
Call this function before calling any other random module function. Returns
None.
5.shuffle(lst)Randomizes the items of a list in place. Returns None.
6.uniform(x, y)A random float r, such that x is less than or equal to r and r is
less than y
Python Strings
OR
An alternative way to create a string object is by assigning a string value to a
variable.
Example:
s1 = “ “ # create an empty string
s2 = “Hello” # Equivalent to s2 = str(“Hello”)
How to access character in a string?
VI Index[ ] operator:
As string is a sequence of characters . The characters in a string can be
accessed one at a time through the index operator.
The first character of the string is stored at the 0 th position and last character of
the string is stored at a position one less than that of the length of the string.
For the string Sammy Shark! the index breakdown looks like this:
As you can see, the first S starts at index 0, and the string ends at index
11 with the ! symbol. We also notice that the whitespace character
between Sammy and Shark also corresponds with its own index number.
In this case, the index number associated with the whitespace is 5.
The exclamation point (!) also has an index number associated with it.
Any other symbol or punctuation mark, such as *#$&.;?, is also a character
and would be associated with its own index number.
Example
VI Example:
>>> s1="python"
>>>s1[0] # Access the first element of the string
>>>s1[5] # Access the last element of the string
Accessing characters via Negative index
VI If we have a long string and we want to pinpoint an item towards the end, we
can also count backwards from the end of the string, starting at the index
number -1.
Example- Initialization
Syntax:
String[index]
where index = index of any mathematical expression
Example:
string = “hello”
string[0] = h
string[1] = e
string[2] = l
string[3] = l
string[4] = o
Traversing string with for & while loop
VI A programmer can use the for loop to traverse all characters in a string.
Code:
Write a program to traverse all elements of a string using for loop
Example:
s =“ India”
for ch in s:
print(ch , end = “ ”)
Output:
India
Explanation: The string ‘India’ is assigned to variable s. The for loop is used to
print all the character of a string s. The statement ‘for ch in s:’ can read as ‘for
each character ch in s print ch’
Traversing string with for & while loop
VI A programmer can use the for loop to traverse all characters in a string.
Code:
Write a program to traverse every second character of a string using for loop
Example:
s =“ ILOVEPYTHONPROGRAMMING”
for ch in range(0,len(s),2): # Traverse each second character
print(s[ch] , end = “ ”)
Output:
I 0 E YH N R GAM N
Example:
for ch in range(1,len(s),2):
print(s[ch] , end = " ")
Output:
LVPTOPOR MIG
Traversing string with while loop
VI A programmer can use the while loop to traverse all characters in a string.
Example:
s =“ India”
Index = 0
While index< len(s):
print(s[index] , end = “ ”)
index = index+1
Output:
India
Slices: single character
VI A slice gives from the given string one character or some fragment:
substring or subsequence.
There are three forms of slices. The simplest form of the slice:
a single character slice S[i] gives ith character of the string.
We count characters starting from 0. That is, if
S = 'Hello',
S[0] == 'H', S[1] == 'e', S[2] == 'l',S[3] == 'l', S[4] == 'o'.
Note that in Python there is no separate type for characters of the
string. S[i] also has the type str, just as the source string.
Number i in S[i] is called an index.
If you specify a negative index, then it is counted from the end, starting with
the number -1.
That is, S[-1] == 'o', S[-2] == 'l', S[-3] == 'l', S[-4] == 'e', S[-5] == 'H'.
Let's summarize it in the table:
Strings operators- Accessing substring
VI String contains the slicing operator and the slicing with step size parameter is
used to obtain the subset of string.
Example :
s=Hello"
print(s[1:4]) # The s[1:4] returns a subset of string starting
from start index 1 to one index less than that
Output : of end parameter of slicing operation (4-1=3)
ell
Note : we can get the same substring using S[-4:-1]
we can mix positive and negative indexes in the same slice, for
example, S[1:-1] is a substring without the first and the last character of the
string
Strings operators- Accessing substring
VI For example :
if s == 'Hello'
the slice S[1:5] returns the string 'ello', and the result is the same even if the
second index is very large, like S[1:100].
Strings slice with step size
VI We learnt , how to select a portion of string. But how does a programmer select
every second character from a string ?
This can be done by using step size. In slicing first two parameters are start
and end. We need to add a third parameter as step size to select the character
from a string with step size.
Syntax:
Name of variable of a string[ Start _ index : End _ index: step_ size ]
Example:
s="IIT-MADRAS"
print(s[0:len(s):2])
Output:
ITMDA
Some more complex example of string slicing
For example : s = “ IIT-MADRAS”
VI 1. s="IIT-MADRAS"
print(s[: :])
output : IIT-MADRAS # print entire string
2. print(s[1:])
output: IT-MADRAS
3. print(s[:3])
output: IIT
4. print(s[:-1]) # start with index 0 and exclude last
output: IIT-MADRA character stored at index-1.
5. print(s[1:-1])
output : IT-MADRA
6. print( s[: : 2] ) or print ( s[ 0: : 2] )
output: ITMDA #alternate characters are printed
7. print(s[::-1]
output : SARDAM-TII # display the string in reverse order
8. print(s[-1:0:-1])
output : SARDAM-TI # Access the character from -1
9. print(s[1::2])
output: I-ARS
String character sequence
Explanation : here we have assigned the string “I Love Python“ to str1. The
index [ ] operator is used to change the contents of the string. Finally it
show an error because the strings are immutable ( can not change the
existing string).
Solution - String character sequence
VI If you want to change the existing string, the best way is to create a new string
that is a variation of original string.
Example:
str1="I LOVE PYTHON"
str2="U"+str1[1:]
print(str2)
Output:
U LOVE PYTHON
How to concatenate and repetition of a string?
Output:
Hellopython
Note: print(str1+2 ) – Not allowed , it gives error
Output: HelloHelloHello
Note : print( str1*str2) - Not allowed , it gives error
String methods/ String function
VI Similarly, the method rfind() returns the index of the last occurrence of the
substring.
Example:
s = 'abracadabra'
print(s.find('b'))
Output : 1
print(s.rfind('b'))
Output : 8
Split Method
VI The method split() returns a list of all the words in the string ,
using str as the separator.
Basically create a list with elements of given string separated by space.
Example:
str="welcome to python"
print(str. split( ))
Output : ['welcome', 'to', 'python']
string function capitalize( ), center( )
Output
VI Syntax
str.capitalize( ) : This is string example....wow!!!
str.capitalize( )
Parameters
width − This is the total width of the string.
fillchar − This is the filler character.
b="hello"
print(b.center(11,"x"))
Output :
hello welcome to python programming
Note: here actual width of a string b is greater than 11. Hence it will print
hello welcome to python programming string.
Function find( )
Description
VI The find( ) method determines if the string str occurs in string, or in a substring of
string if the starting index beg and ending index end are given.
Syntax
str.find(str, beg = 0 end = len(string))
Parameters
str − This specifies the string to be searched.
beg − This is the starting index, by default its 0.
end − This is the ending index, by default its equal to the length of the string.
e.g.
b="hello welcome to python programming"
print(b.find("o",0,len(b)))
Output: 4
It return the index value of first occurrence of “o”
Function split
VI Description
The split( ) method returns a list of all the words in the string, using str as the separator
(splits on all whitespace if left unspecified), optionally limiting the number of splits to
num.
Syntax
str.split(str=" ", num = string.count(str)).
Parameters
str − This is any delimeter, by default it is space.
num − this is number of lines to be made
e.g.
str = "this is string example....wow!!!"
print (str.split( ))
print (str.split( 'i',1)) Output
['this', 'is', 'string', 'example....wow!!!']
print (str.split('w'))
['th', 's is string example....wow!!!']
['this is string example....', 'o', '!!!']
String Formatting Operator
VI One of Python's coolest features is the string format operator %. This operator is
unique to strings and makes up for the pack of having functions from C's printf( )
family.
e.g.
print ("My name is %s and weight is %d kg!" % ('Zara', 21))
Output
My name is Zara and weight is 21 kg!
Most complex format: python3 added a new string method called format( ) method.
Instead of %s we can use {0}, {1} and so on
Syntax: template.format(p0,p1,…..)
e.g.
print ("My name is {0} and weight is {1} kg!“.format ('Zara', 21))
Output
My name is Zara and weight is 21 kg!
Format Symbol & Conversion
VI
%c
character
%s
string conversion via str() prior to formatting
%i
signed decimal integer
%d
signed decimal integer
%u
unsigned decimal integer
%o
octal integer
%x
hexadecimal integer (lowercase letters)
Format Symbol & Conversion
VI %X
hexadecimal integer (UPPERcase letters)
%e
exponential notation (with lowercase 'e')
%E
exponential notation (with UPPERcase 'E')
%f
floating point real number
%g
the shorter of %f and %e
%G
the shorter of %f and %E
Function Index
VI Description
e.g. Output
str1 = "this is string example....wow!!!“ 15
str2 = "exam"; 15
print (str1.index(str2)) Traceback (most recent call last):
print (str1.index(str2, 10))
print (str1.index(str2, 40))
Function islower( ),len( )
Description
VI The islower( ) method checks whether all the case-based characters (letters) of the string
are lowercase.
Syntax
str.islower( )
e.g. Output
str = "THIS is string example....wow!!!" False
print (str.islower( )) True
str = "this is string example....wow!!!“
print (str.islower( ))
Description
The len( ) method returns the length of the string.
Syntax
len( str )
Output
e.g. Length of the string: 32
str = "this is string example....wow!!!"
print ("Length of the string: ", len(str))
Function lower( )
Description
VI The method lower() returns a copy of the string in which all case-based characters have
been lowercased.
Syntax
str.lower( )
Return Value
This method returns a copy of the string in which all case-based characters have been
lowercased.
e.g.
str = "THIS IS STRING EXAMPLE....WOW!!!"
print (str.lower( ))
Output
this is string example....wow!!!
Function replace( )
Description
VI The replace( ) method returns a copy of the string in which the occurrences of old have
been replaced with new, optionally restricting the number of replacements to max.
Syntax
str.replace(old, new, max)
Parameters
e.g.
str = "this is string example....wow!!! this is really string“
print (str.replace("is", "was"))
print (str.replace("is", "was", 3))
Output
thwas was string example....wow!!! thwas was really string
thwas was string example....wow!!! thwas is really string
Function : count()
Description
VI This method counts the number of occurrences of one string within another
string.
Syntax
s.count(substring)
Note : Only non-overlapping occurrences are taken into account
e.g.
print('Abracadabra'.count('a'))
print(('aaaaaaaaaa').count('aa'))
Output
4
5
list
VI The most basic data structure in Python is the sequence. Each element of a
sequence is assigned a number - its position or index. The first index is zero, the
second index is one, and so forth.
There are certain things you can do with all the sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
There are certain things you can do with all the sequence types. These operations
include indexing, slicing, adding, multiplying, and checking for membership. In
addition, Python has built-in functions for finding the length of a sequence and for
finding its largest and smallest elements.
list
VI
Python Lists
• The list is the most versatile data type available in Python, which can be written as
a list of comma-separated values (items) between square brackets. Important thing
about a list is that the items in a list need not be of the same type.
• Creating a list is as simple as putting different comma-separated values between
square brackets.
• e.g.
Output
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
VI You can update single or multiple elements of lists by giving the slice on the left-
hand side of the assignment operator, and you can add to elements in a list with the
append( ) method.
1. Append the element
seq = [ 10,20,30,40 ]
print( seq.append ( 50 )
Output : [ 10,20,30,40,50 ]
2. Reassign the element
list = ['physics', 'chemistry', 1997, 2000]
print ("Value available at index 2 : ", list[2])
list[2] = 2001
Print ( list )
Output:
Value available at index 2 : 1997
list = ['physics', 'chemistry', 2001, 2000 ]
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly
VI which element(s) you are deleting. You can use the remove() method if you do not
know exactly which items to delete.
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
Output
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
Example:
L1 = [ 10,20,30,40,50]
L1[ 1:4]
Output :
[20,30,40 ]
List Slicing with step size
We learnt how to select a portion of a list. In this , we will explore how to select every
VI second or third element of a list using step size. Hence we need to add a third
parameter a step size .
Syntax :
Name of list[start index : End index: step size]
Example:
mylist=["Hello",1,"Monkey",2,"Dog",3,"Donkey" ]
newlist=mylist[0:6:2] or newlist=mylist[0: len(mylist) :2]
print(newlist)
Output :
['Hello', 'Monkey', 'Dog']
Example:
mylist=["python",450,"c",300,"c++",670 ]
newlist=mylist[0:6:3]
print(newlist)
Output :
['python', 300]
Python inbuilt functions for Lists
len( ) Method :
VI Description
The method len() returns the number of elements in the list.
Syntax:
len(list)
Example
list1, list2 = [123, 'xyz', 'zara'], [456, 'abc']
print "First list length : ", len(list1)
print "Second list length : ", len(list2)
Output:
first list length : 3
Second list length : 2
Python inbuilt functions for Lists
max( ) Method
VI Description
The method max returns the elements from the list with maximum value.
Syntax
max(list)
Example:
list1, list2 = [‘123’, 'xyz', 'zara', 'abc'], [456, 700, 200]
print ("Max value element : ", max(list1))
print ("Max value element : ", max(list2))
Output:
Max value element : zara
Max value element : 700
Example:
list=['a','ab']
print(max(list))
Output:
ab
Example:
list=['a','100']
print(max(list))
Output: a
Python inbuilt functions for Lists
min() Method
VI Description
The method min returns the elements from the list with minimum value.
Syntax
min(list)
Example:
list1, list2 = [123, 'xyz', 'zara', 'abc'], [456, 700, 200]
print "Min value element : ", min(list1)
print "Min value element : ", min(list2)
Output:
Min value element : 123
Min value element : 200
Python inbuilt functions for Lists
append() Method
VI Description
The method append() appends a passed obj into the existing list.
Syntax
list. append(obj)
Example:
list = [123, 'xyz', 'zara', 'abc']
list. append( 2009 )
print("Updated List : ", list)
Output:
Updated List : [123, 'xyz', 'zara', 'abc', 2009]
Python inbuilt functions for Lists
extend() Method
VI Description
The method extend() appends a passed obj into the existing list.
Syntax
list. extend(seq)
Example:
List1 = [123, 'xyz', 'zara', 'abc', 123]
List2 = [2009, ‘sara']
List1.extend(List2)
print("Extended List : ", List1)
Output:
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, ‘sara']
Python inbuilt functions for Lists
index() Method
VI Description
The method index() returns the lowest index in list or which appear first in the list.
Syntax
list.index(obj)
Example:
List = [123, 'xyz', 'zara', 'abc'];
print ("Index for xyz : ", List.index( 'xyz' ))
print ("Index for zara : ", List.index( 'zara' ))
Output:
Index for xyz : 1
Index for zara : 2
Example :
seq = [1,2,3,4,5 ]
print(“Index for 4:” , seq. index(4))
Output: 3
Python inbuilt functions for Lists
insert() Method
VI Description
The method insert() inserts object or element at particular index position
Syntax
list. insert(index, obj)
Where , index − This is the Index where the object or element need to be inserted.
obj − This is the Object or element to be inserted into the given list
Example:
aList = [123, 'xyz', 'zara', 'abc']
aList.insert( 3, 2009) # insert element 2009 at index 3
print ("Final List : ", aList)
Output:
Final List : [123, 'xyz', 'zara', 2009, 'abc']
Python inbuilt functions for Lists
pop( ) Method
VI Description
The method pop( ) removes and returns last object or element from the list.
Syntax
list.pop(obj)
Example:
aList = [123, 'xyz', 'zara', 'abc']
print("A List : ", aList.pop( ))
print("B List : ", aList.pop(2))
Output:
A List : abc
B List : zara
Python inbuilt functions for Lists
remove( ) Method
VI Description
The method remove( ) removes the first occurrence of given value from the given list.
Syntax
list. remove(obj )
Example:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.remove('xyz');
print("List : ", aList)
aList.remove('abc');
print("List : ", aList)
Output:
List : [123, 'zara', 'abc', 'xyz']
List : [123, 'zara', 'xyz']
Python inbuilt functions for Lists
reverse( ) Method
VI Description
The method reverse( ) reverses objects or element of list.
Syntax
list. reverse( )
Example:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.reverse();
print ("List : ", aList)
Output:
List : ['xyz', 'abc', 'zara', 'xyz', 123]
Python inbuilt functions for Lists
sort( ) Method
VI Description
The method sort() sorts objects or element of list in ascending order.
Syntax
list.sort( ) # No arguments required
Example:
aList = [123, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print("List : ", aList)
Output:
List : [123, 'abc', 'xyz', 'xyz', 'zara']
Example:
seq = [ 1,2,3,1,4,1,5]
print( seq.sort( ) )
Output: [ 1,1,1,2,3,4,5]
Python inbuilt functions for Lists
sort( ) Method
VI Description
The method sort() sorts objects or element of list in ascending order.
Syntax
list.sort( ) # No arguments required
Example:
aList = [‘123’, 'xyz', 'zara', 'abc', 'xyz'];
aList.sort();
print("List : ", aList)
Output:
List : [123, 'abc', 'xyz', 'xyz', 'zara']
Example:
seq = [ 1,2,3,1,4,1,5]
print( seq.sort( ) )
Output: [ 1,1,1,2,3,4,5]
List Comprehensions
List comprehension is used to create a new list from existing sequences.
VI Syntax:
[<expression> for < element >in < sequence > if < condition > ]
It is read as “ Compute the expression for each element in the sequence, if the
condition is true”
Example:
Create a list to store five different numbers such as 10,20,30,40 and 50.using the
for loop, add number 5 to the existing elements of the list.
without list comprehension :
list[10,20,30,40,50 ]
Print(list) With list comprehension :
Output: list=[10,20,30,40,50]
[10,20,30,40,50 ] list=[x+5 for x in list]
for i in range(0,len(list)): print(list)
list[i] = list[i]+5 Output:
print(list) [15, 25, 35, 45, 55]
Output:
[15,25,35,45,55]
List Comprehensions
Example :
list[10,20,30,40,50]
list=[x+10 for x in list ]
A variable referring an
input sequence
Some problems statement
1. Python Program to Calculate the Average of Numbers in a Given List
VI Problem Description
The program takes the elements of the list one by one and displays the average of the
elements of the list.
Problem Solution
1. Take the number of elements to be stored in the list as input.
2. Use a for loop to input elements into the list.
3. Calculate the total sum of elements in the list.
4. Divide the sum by total number of elements in the list.
5. Exit.
Program/Source Code
Here is source code of the Python Program to Calculate the Average of Numbers in a
Given List. The program output is also shown below.
n=int(input("Enter the number of elements to be inserted: "))
a=[ ]
for i in range(0,n):
elem=int(input("Enter element: "))
a.append(elem)
avg=sum(a)/n
print("Average of elements in the list",round(avg,2)) # rounds the average up to 2
decimal places.
Some problems statement
2. Python Program to Find the Largest Number in a List
VI Problem Description
The program takes a list and prints the largest number in the list.
Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Sort the list in ascending order.
4. Print the last element of the list.
5. Exit.
Code:
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
Some problems statement
3. Python Program to Find the smallest Number in a List
VI Problem Description
The program takes a list and prints the smallest number in the list.
Code:
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(0,n):
b=int(input("Enter element:"))
a.append(b)
a.sort(reverse=True)
print("Largest element is:",a[n-1])
Some problems statement
4. Python Program to Put Even and Odd elements in a List into Two Different Lists
VI Problem Solution
1. Take in the number of elements and store it in a variable.
2. Take in the elements of the list one by one.
3. Use a for loop to traverse through the elements of the list and an if statement to
check if the element is even or odd.
4. If the element is even, append it to a separate list and if it is odd, append it to a
different one.
5. Display the elements in both the lists.
6. Exit.
Code:
a=[ ]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
even=[ ] else:
odd=[ ] odd.append(j)
for j in a: print("The even list",even)
if(j%2==0): print("The odd list",odd)
even.append(j)
Some problems statement
5. WAP to check whether enter string is palindrome or not
VI
Code:
string=input("Enter the string")
revstr=string[::-1]
if string==revstr:
print("string is palindrome")
else:
print("string is not palindrome")
input : madam
Output: madam
Some problems statement
1.Write a program to create a list with elements 1,2,3,4,5.Display even elements of
VI list using list compression.
tup1 = ( );
To write a tuple containing a single value you have to include a comma, even though
there is only one value −
tup1 = (50,)
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
Accessing Values in Tuples and Updating Tuples
To access values in tuple, use the square brackets for slicing along with the index or
VI indices to obtain the value available at that index.
Tuples are immutable, which means you cannot update or change the values of tuple
elements. You are able to take portions of the existing tuples to create new tuples
Output
(12, 34.56, 'abc', 'xyz')
Delete Tuple, Indexing and Slicing
Removing individual tuple elements is not possible. There is, of course, nothing wrong
VI with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.
tup = ('physics', 'chemistry', 1997, 2000);
print (tup) del tup;
print ("After deleting tup : ")
print (tup)
VI l1=['abc',[(1,2),([3],4)],5]
print(l1[1])
print(l1[1][1][0])
print(l1[1][1][0][0])
return [expression]
Function
1.Example:
VI def fun( ) : # function definition
print( “ I am learning python”)
fun ( ) # calling function
2.Example:
def print_hello( ):
print('Hello!')
print_hello( )
print('1234567')
print_hello( )
output :
Hello!
1234567
Hello!
Note: The first two lines define the function. In the last three lines we call the
function twice.
Function
A programmer wants to find out the sum of numbers starting from 1 to 25 , 50
VI to 75 and 90 to 100 without function.
Code:
sum= 0
for i in range ( 1, 26 ):
sum = sum +i
print (“sum of integers from 1to 25 is:”, sum)
sum= 0
for i in range ( 50, 76 ):
sum = sum +i
print (“sum of integers from 50 to 76 is:”, sum)
sum= 0
for i in range ( 90, 101):
sum = sum +i
print (“sum of integers from 90 to 101 is:”, sum)
VI
Example : Example:
x = 10 x = 10
y=20 y=20
z=30 z=30
Output:
num1 = 20
num2 = 10
The number 20 is greater than 10
Function
Example : write a program to find factorial of numbers
VI
Code:
def calc_ factorial ( num ):
fact = 1
print (“ Entered number is :”, num)
for i in range ( 1, num+1 ):
fact = fact* i
print ( “ factorial of number “ , num, “ is = “ ,fact )
number = int ( input ( “ Enter the number” ))
calc_ factorial( number)
Output:
Entered number = 5
Entered number is : 5
factorial of number 5 is = 120
Function
Recall that in mathematics the factorial of a number n is defined as n! = 1 ⋅ 2 ⋅ ... ⋅
VI n (as the product of all integer numbers from 1 to n). For example, 5! = 1 ⋅ 2 ⋅ 3 ⋅ 4 ⋅ 5
= 120. It is clear that factorial is easy to calculate, using a for loop. Imagine that we
need in our program to calculate the factorial of various numbers several times (or in
different places of code). Of course, you can write the calculation of the factorial once
and then using Copy-Paste to insert it wherever you need it:
Example:
# compute 3!
res = 1
for i in range(1, 4):
res *= i
print(res)
Output:
6
Functions are the code sections which are isolated from the rest of the program and
executed only when called. You've already met the function sqrt(), len() and print().
They all have something in common: they can take parameters (zero, one, or several of
them), and they can return a value (although they may not return). For example, the
function sqrt() accepts one parameter and returns a value (the square root of the given
number). The print() function can take various number of arguments and returns
nothing.
Function
Now we want to show you how to write a function called factorial() which takes a
VI single parameter — the number, and returns a value — the factorial of that number.
Example:
def factorial(n):
res = 1
for i in range(1, n + 1):
res *= i
return res
print(factorial(3))
Output:
6
Function
Here's the function max( ) that accepts two numbers and returns the maximum of them
VI (actually, this function has already become the part of Python syntax).
Example:
def max(a, b):
if a > b:
return a
else:
return b
print(max(3, 5))
print(max(5, 3))
print(max(int(input()), int(input())))
Output:
5
5
Function
Now you can write a function max3() that takes three numbers and returns the
VI maximum of them.
def max(a, b):
if a > b:
return a
else:
return b
print(max3(3, 5, 4))
Output:
5
Pass by Reference vs Value
All parameters (arguments) in the Python language are passed by reference. It means if
VI you change what a parameter refers to within a function, the change also reflects back
in the calling function.
Output
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
Function arguments
VI 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.
VI
Example:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
Output
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Variable-length Arguments
VI 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 arguments. An asterisk (*)
is placed before the variable name that holds the values of all non keyword variable
arguments.
VI
def printinfo( *vartuple ):
"This prints a variable passed arguments" Output:
print ("Output is: ") Output is:
10
for var in vartuple:
Output is:
print (var) 70
return 60
# Now you can call printinfo function 50
printinfo( 10 )
printinfo( 70, 60, 50 )
Return Values
Example:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output
15
25
45
The return Statement
Output:
Inside the function : 30
Outside the function : 30
Return Values
VI Example:
def minimum(a,b):
if a<b:
return a
Output
elif b<a:
85
return b
else:
return " Both the number are equal"
print(minimum(100,85))
def minimum(a,b):
if a < b:
return a
elif b < a: Output:
return b Both the number are equal
else:
return " Both the number are equal"
print(minimum(100,100))
Python Lambda / The Anonymous Functions
x = lambda a: a + 10
print(x(5))
Output: 15
Python Lambda / The Anonymous Functions
Example:
A lambda function that multiplies argument a with argument b and print the
result:
x = lambda a, b: a * b
print(x(5, 6))
Output: 30
Why Use Lambda Functions?
VI The power of lambda is better shown when you use them as an anonymous
function inside another function.
Say you have a function definition that takes one argument, and that argument
will be multiplied with an unknown number:
def myfunc(n):
return lambda a : a * n
Use that function definition to make a function that always doubles the
number you send in:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
Output: 30
Why Use Lambda Functions?
VI use the same function definition to make a function that always triples the
number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
Output: 33
Why Use Lambda Functions?
VI use the same function definition to make both functions, in the same program:
Example:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Output:
22
33
The Anonymous Functions/ Lambda function
VI Example:
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
Output:
Value of total : 30
Value of total : 40
Scope of Variables
VI 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 −
1.Global variables
2. Local variables
Global vs. Local variables
VI 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.
Example:
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)
Output:
Inside the function local total : 30
Outside the function global total : 0
Arguments
We can pass values to functions.
VI Example:
def print_ hello(n):
print('Hello ' * n)
print()
print_ hello(3)
print_ hello(5)
times = 2
print_ hello(times)
output:
Hello Hello Hello
Hello Hello
Note : When we call the print _ hello function with the value 3, that value gets stored
in the variable n. We can then refer to that variable n in our function’s code.
Arguments
You can pass more than one value to a function
VI Example:
def multiple_print(string, n):
print(string * n)
print()
multiple_print('Hello', 5)
multiple_print('A', 10)
Output:
HelloHelloHelloHelloHello
AAAAAAAAAA
Returning values
We can write functions that perform calculations and return a result.
VI Example 1:
Here is a simple function that converts temperatures from Celsius to Fahrenheit.
Output :
68.0
Note: The return statement is used to send the result of a function’s calculations
back to the caller.
Notice that the function itself does not do any printing. The printing is done outside of
the function.
That way, we can do math with the result, like below.
print(convert(20)+5)
If we had just printed the result in the function instead of returning it, the result would
have been printed to the screen and forgotten about, and we would never be able to do
anything with it
Default arguments and keyword arguments
You can specify a default value for an argument. This makes it optional, and if the
VI caller decides not to use it, then it takes the default value.
Example:
def multiple _ print(string, n=1):
print(string * n)
print()
multiple _ print('Hello', 5)
multiple _ print('Hello')
Output:
HelloHelloHelloHelloHello
Hello
Note: Default arguments need to come at the end of the function definition, after all of
the non-default arguments.