0% found this document useful (0 votes)
29 views17 pages

PYTHON Concepts

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)
29 views17 pages

PYTHON Concepts

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

PYTHON CONCEPTS

Kumar Gaurav Singh


APS KANPUR
PYTHON Concepts
Revision Notes
Python was created by Guido Van Rossum in late '1980s' (Released in 1991) at National Research Institute in the
Netherland. Python got its name from a BBC comedy series – “Monty Python’s Flying Circus”. Python is based on two
programming languages:
(i) ABC language
(ii) Modula 3
Some qualities of Python based on the programming fundamentals are given below:
a. Interactive Mode: Interactive mode, as the name suggests, allows us to work interactively. It executes the code by
typing one command at a time in Python shell.
b. Script Mode: In script mode, we type Python program in a file and then execute the content of the file.
c. Indentation: Blocks of code are denoted by line indentation, which is rigidly enforced.
d. Comments: A hash sign (#) that is not inside a string literal begins a single line comment. We can use triple quoted
string for giving multi-line comments.
e. Variables: A variable in Python is defined through assignment. There is no concept of declaring a variable Other than
assignment. Value of variable can be manipulated during program run.
f. Dynamic Typing: In Python, while the value that a variable points to has a type, the variable itself has no strict type
in its definition.
g. Static Typing: In static typing, a data type is attached with a variable when it is defined first and it is fixed.
h. Multiple Assignment: Python allows you to assign a single value to several variables and multiple values to multiple
variables simultaneously.
i. For example: a=b=c=1
1. a, b, c = 1, 2, “john”
j. Token: The smallest individual unit in a program is known as a Token or a lexical unit.
k. Identifiers: An identifier is a name used to identify a variable, function, class, module, or other object. An identifier
starts with a letter A to Z or a to z or an underscore ( _ ) followed by zero or more letters, underscores, and digits (0
to 9).
Python does not allow punctuation characters such as @, $, and % within identifiers. Python is a case sensitive
programming language. Thus, Value and value are two different identifiers in Python.
Here are identifiers naming convention for Python:
a. Class names start with an uppercase letter and all other identifiers with a lowercase letter.
b. Starting an identifier with a single leading underscore indicates by convention that the identifier is meant to be
private.
c. Starting an identifier with two leading underscores indicates a strongly private identifier.
d. If the identifier ends with two trailing underscores, the identifier is a language-defined special name.
e. Words (Keywords): The following list shows the reserved words in Python v3.0 or later
Case Sensitive Programming: Case sensitivity describes a programming language's (C, C++, Java, C#, Verilog, Ruby,
Python and Swift) ability to distinguish between upper and lower case versions of a letter.
Reserved Words: Reserved words are all those words that have a strictly predefined meaning—they are reserved
for special use and cannot be used for any other purpose.
Maps or Mapping: A mapping type is a data type comprised of a collection of keys and associated values.
Python's only built-in mapping type is the dictionary.
Integer & Long: To store whole numbers i.e. decimal digits without fraction part.
Float/floating point: To store numbers with fraction part.
Complex: To store real and imaginary part.
a. These reserved words should not be used as constant or variable or any other identifier names. All the Python
keywords contain lowercase letters only except False, None and True which have first letter capital.
b. Literal/Constant: Literals (Often referred to as constant value) are data items that have a fixed value. Python allows
several kind of literals as String literals, Numeric literals, Boolean literals, special literal None and literal Collections
c. Data Types: Data type is a set of values and the allowable operations on those values. Python has a great set of useful
data types. Python’s data types are built in the core of the language. They are easy to use and straight forward.

• Numbers can be either integer/floating point or complex type numbers.


• None: It is a special data type with a single value. It is used to signify the absence of value in a situation.
• A sequence is an ordered collection of items, indexed by integers starting from 0. Sequences can be grouped into strings,
tuples and lists.
- Strings are lines of text that can contain any character. They can be declared with double quotes.
- Lists are used to group other data. They are similar to arrays.
- A tuple consists of a number of values separated by commas.
• A set is an unordered collection with no duplicate items.
• A dictionary is an unordered set of key value pairs where the keys are unique.
• Operator: Operators are special symbols which perform some computation. Operators and operands form an
expression. Python operators can be classified as given below:
Python Operators
• Expressions: An expression in Python is any valid combination of operators, literals and variables.
Conditional and Iterative Statements
A conditional is a statement which is executed, on the basis of result of a condition.
Control statements are used to control the flow of execution depending upon the specified condition/logic.
There are three types of control statements
1. Decision Making Statements (if, elif, else)
2. Iteration Statements (while and for Loops)
3. Jump Statements (break, continue, pass)
• if conditionals statement in Python has the following forms.
(A) Simple if

Syntax: if < conditional expression>:


[statements]
(B) The if-else conditional

Syntax: if < conditional expression>:


[statements]
else:
[statements]
(C) The if-elif-else conditional statement

Syntax: if < conditional expression>:


Statement
[statements]
elif < conditional expression>:
statement
[statements]
else:
statement
[statements]
(D) Nested if
• A nested if is an if which is inside another if's body or elif's body or else's body. Syntax: The syntax of the
nested if...elif...else construct may be:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)
• Storing conditions – Complex and repetitive conditions can be named and then used in if statements.
a. The iteration statements or repetition statements allow a set of instructions to be performed repeatedly.
b. Python provides three types of loops
(A) Counting loops repeat a certain number of times e.g. for
(B) Conditional loops repeat until a certain condition is true e.g. while.
(C) Nested loops

1. Python While Loop A while loop in Python iterates till its condition becomes False. In other words, it executes the
block of statements until the condition it takes is true.
Syntax
while <Logical Expression>:
loop body
When the program control reaches the while loop, the condition is checked. If the condition is true, the block of code
under it is executed. After that, the condition is checked again. This continues until the condition becomes false. Then
the first statement, if any after the loop is executed. Remember to indent all statements under the loop equally.
e.g.
>>> a=3
>>> while(a>0):
print(a)
a-=1
Output
3
2
1
(a) An Infinite Loop Be careful while using a while loop. Because if you forget to increment or decrement the counter
variable in Python, or write flawed logic, the condition may never become false. In such a case, the loop will run
infinitely, and the conditions after the loop will starve. To stop execution, press Ctrl+C. However, an infinite loop may
sometimes be useful.
(b) The else statement for while loop A while loop may have an else statement after it. When the condition becomes
false, the block under the else statement is executed. However, it doesn’t execute if you break out of the loop or if an
exception is raised.
e.g.
>>> a=3
>>> while(a>0):
print(a)
a-=1
else:
print("Reached 0")
Output
3
2
1
Reached ()
In the following code, we put a break statement in the body of the while loop for a==1. So, when that happens, the
statement in the else block is not executed.
e.g.
>>> a=3
>>> while(a>0):
print(a) a-=1
if(a==1):
break
else:
print("Reached 0")
Output
32
(c) Single Statement while Like an if statement, if we have only one statement in while loop’s body, we can write it all in
one line.
e.g.
>>> a=3
>>> while a>0:
print(a);
a-=1;
Output
3
2
1
You can see that there were two statements in while loop’s body, but we used semicolons to separate them. Without
the second statement, it would form an infinite loop.
2. Python for Loop Python for loop can iterate over a sequence of items. The structure of a for loop in Python is
different than that in C++ or Java.

>>> for a in range(3):


print(a)
Output
0
1
2
If we wanted to print 1 to 3, we could write the following code.
>>> for a in range(3):
print(a+1)
Output
1
2
3
(a) The range() function This function yields a sequence of numbers. When called with one argument, say n, it creates a
sequence of numbers from 0 to n-1.
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
We use the list function to convert the range object into a list object. Calling it with two arguments creates a sequence
of numbers from first to second.
>>> list(range(2,7))
[2, 3, 4, 5, 6]
You can also pass three arguments. The third argument is the interval.
>>> list(range(2,12,2))
[2, 4, 6, 8, 10]
Remember, the interval can also be negative.
>>> list(range(12,2,-2))
[12, 10, 8, 6, 4]
3. Nested Loops A loop may contain another loop in its body, this inner loop is called nested loop. But in a nested loop,
the inner loop must terminate before the outer loop.
e.g. for i in range(1,6):
for j in range (1,i):
print("*", end=" ")
print()
• Jump Statements: Python offers two jump statements-break and continue to be used within loops to jump out of loop
iterations.
• break statement: It terminates the loop it lies within. It skips the rest of the loop and jumps over to the
statement following the loop.
• continue statement: Unlike break statement, the continue statement forces the next iteration of the loop to
take place, skipping any code in between
Indentation: In most programming languages, the statements within a block are put inside curly brackets. However,
Python uses indentation for block as well as for nested block structures. Leading whitespace (spaces and tabs) at the
beginning of a statement is called indentation.
Control Structure: Control Structure is a programming language construct which affects the flow of the execution of
program.
FUNCTIONS IN PYTHON
Definition: It is simply a group of statements under any name i.e. function name and can be invoked (call)
from other part of program. Functions are the subprograms that perform specific task. Functions are the small
modules.
Types of Functions:
There are three types of functions in python:

Library Functions: These functions are already built in the python library.
Functions defined in modules: These functions defined in particular modules. When you want to use these
functions in program, you have to import the corresponding module of that function.
User Defined Functions: The functions those are defined by the user are called user defined functions.
Library Functions in Python:
These functions are already built in the library of python. For example: type( ), len( ), input( ) etc.
Functions defined in modules:
Functions of math module:
To work with the functions of math module, we must import math module in program.
import math
S. No. Function Description Example
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49) 7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3) 82
3 floor( ) Returns the lower integer >>>math.floor(81.3) 81
4 pow( ) Calculate the power of a number >>>math.pow(2,3) 8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-5.6) 5.6
6 exp( ) Returns the e raised to the power i.e. e3 >>>math.exp(3) 20.085536923187668
Function in random module:
randint( )- function generates the random integer values including start and end values.
Syntax: randint(start, end)- It has two parameters. Both parameters must have integer values.
Example:
import random n=random.randint(3,7) *The value of n will be 3 to 7.
User defined functions:
Syntax to create user defined function
def function_name([comma separated list of parameters]):
statements….
statements….
Key points to remember:
 Keyword def marks the start of function header
 Function name must be unique and follows naming rules same as for identifiers
 Function can take arguments. It is optional
 A colon(:) to mark the end of function header
 Function can contains one or more statement to perform specific task
 An optional return statement to return a value from the function.
 Function must be called/invoked to execute its code
 One or more valid python statements that make up the function body.
 Statements must have same indentation level
Example:
def display(name):
print("Hello " + name + " How are you?")
User defined function can be:
 Function with no arguments and no return
 Function with arguments but no return value
 Function with arguments and return value
 Function with no argument but return value
Function Parameters: functions has two types of parameters:
Formal Parameter: Formal parameters are written in the function prototype and function header of the
definition. Formal parameters are local variables which are assigned values from the arguments when the function
is called.
Actual Parameter: When a function is called, the values that are passed in the call are called actual parameters.
At the time of the call each actual parameter is assigned to the corresponding formal parameter in the function
definition.

Types of Arguments:
There are 4 types of Actual Arguments allowed in Python:
1. Positional arguments: are arguments passed to a function in correct positional order
2. Default arguments: we can provide default values for our positional arguments. In this case if we are
not passing any value then default values will be considered.
3. Keyword arguments: allows to call function with arguments in any order using name of the
arguments.
4. Variable length arguments: allow to call function with any number of arguments.
Calling the function:
Once we have defined a function, we can call it from another function, program or even the Python prompt. To
call a function we simply type the function name with appropriate parameters.
Syntax:
Function_name(parameter)
Example:
ADD(10,20)
The return statement:
The return statement is used to exit a function and go back to the place from where it was called. There are two
types of functions according to return statement:
a. Function returning some value
b. Function not returning any value
a. Function returning some value :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
Example-2 Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple print(S)
Output: (7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately print(s1, s2, s3)
Output:
7 7 11
b. Function not returning any value : The function that performs some operations but does not return any
value, called void function.
def message():
print("Hello")
m=message()
print(m)
Output: Hello
None
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 is not visible from outside. Hence, they have a local scope.
There are two types of scope for variables:
i) Local Scope
ii) Global Scope
Local Scope: Variable used inside the function. It cannot be accessed outside the function. In this scope, the
lifetime of variables inside a function is as long as the function executes. They are destroyed once we return
from the function. Hence, a function does not remember the value of a variable from its previous calls.
Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a variable is the period
throughout which the variable exits in the memory.
Example 1
Example 2:
def func2():
A=2
print("Value inside function:",A)
A=5
func2()
print("Value outside function:",A)
OUTPUT:
Value inside function: 2
Value outside function: 5
Here, we can see that the value of A is 5 initially. Even though the function func2() changed the value of A to 2,
it did not affect the value outside the function.
This is because the variable A inside the function is different (local to the function) from the one outside.
Although they have same names, they are two different variables with different scope.
On the other hand, variables outside of the function are visible from inside. They have a global scope.
We can read these values from inside the function but cannot change (write) them. In order to modify the value
of variables outside the function, they must be declared as global variables using the keyword global.

Short Answer Type Questions (1-Mark)


1. Name the built-in mathematical function / method that is used to return an absolute value of a number.
Ans: abs()
2. Find and write the output of the following python code:
def myfunc(a):
a=a+2
a=a*2
return a
print(myfunc(2))
Ans:8
3. What is the default return value for a function that does not return any value explicitly?
Ans: None
4. Name the keyword use to define function in Python.
Ans: def
5. Predict the output of following code snippet:
def function1(a):
a=a+’1’
a=a*2
function1(‘Hello’)
Ans: Hello1Hello1
6. Variable defined in function referred to _________variable.
Ans: local
7. Name the argument type that can be skipped from a function call.
Ans: default arguments
8. Positional arguments can be passed in any order in a function call. (True/False)
Ans: False
9. Which of the following is function header statement is correct.
a. def fun(x=1,y) b. def fun(x=1,y,c=2) c. def fun(a,y=3)
Ans: c. def fun(a,y=3)
10. Predict the output of following code snippet.
def printDouble(A):
print(2*A)
print(3)
Ans: 3
Short Answer Type Questions (2-Marks)
1. What is the difference between a Local Scope and Global Scope ? Also, give a suitable Python code to illustrate
both.
Ans: A name declared in top level segment ( main ) of a program is said to have global scope and can be used in
entire program.
A name declare in a function body is said to have local scope i.e. it can be used only within this function and the other
block inside the function.
Global=5
def printDouble(A):
Local=10
print(Local)
print(Global)
2. Define different types of formal arguments in Python, with example.
Ans: Python supports three types of formal arguments :
1) Positional arguments (Required arguments) - When the function call statement must match the number and order of
arguments as defined in the function definition. Eg. def check (x, y, z) :
2) Default arguments – A parameter having default value in the function header is known as default parameter. Eg.
def interest(P, T, R=0.10) :
3) Keyword (or named) arguments- The named arguments with assigned value being passed in the function call
statement. Eg. interest (P=1000, R=10.0, T = 5)
3. Observe the following Python code very carefully and rewrite it after removing all syntactical errors with each
correction underlined.
DEF result_even( ):
x = input(“Enter a number”)
if (x % 2 = 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
even ( )
Ans:
def result_even( ):
x = int(input(“Enter a number”))
if (x % 2 == 0) :
print (“You entered an even number”)
else:
print(“Number is odd”)
result_even( )
4. Differentiate between Positional Argument and Default Argument of function in python with suitable
example
Ans: Positional Arguments: Arguments that are required to be passed to the function according to their position in
the function header. If the sequence is changed, the result will be changes and if number of arguments are
mismatched, error message will be shown.
Example:
def divi(a, b):
print (a / b)
>>> divi(10, 2)
5.0
>>> divi (10)
Error
Default Argument: An argument that is assigned a value in the function header itself during the function
definition. When such function is called without such argument, this assigned value is used as default value and
function does its processing with this value.
def divi(a, b = 1):
print (a / b)
>>> divi(10, 2)
>>> 5.0
5. Ravi a python programmer is working on a project, for some requirement, he has to define a function with
name CalculateInterest(), he defined it as:
def CalculateInterest (Principal, Rate=.06,Time): # code
But this code is not working, Can you help Ravi to identify the error in the above function and what is the
solution.
Ans: In the function CalculateInterest (Principal, Rate=.06,Time) parameters should be default parameters from right to
left hence either Time should be provided with some default value or default value of Rate should be removed.
6. Predict the output of the following python code:
def guess(s):
n = len(s)
m=""
for i in range(0, n):
if (s[i] >= 'a' and s[i] <= 'm'):
m = m +s[i].upper()
elif (s[i] >= 'n' and s[i] <= 'z'):
m = m +s[i-1]
elif (s[i].isupper()):
m = m + s[i].lower()
else:
m = m +'#'
print(m)
guess("welcome2kv")
Ans: vELCcME#Kk
7. Differentiate between call by value and call by reference with a suitable example for each.
Ans: In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like
callvalue because you can not change the value of the immutable objects being passed to the function. Whereas
passing
mutable objects can be considered as call by reference because when their values are changed inside the function, then
it
will also be reflected outside the function.
8. Find and write the output of the following Python code:
def Show(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Show('HappyBirthday')
Ans: hAPPYbIRTHDAY
9. What is the meaning of return value of a function? Give an example to illustrate its meaning.
Ans: Return value of a function is the value which is being given back to the main program after the execution of
function.
e.g.
def Check():
return 100
10. Rewrite the following code in python after removing all syntax errors. Underline each correction done in the
code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
elseif i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
Ans:
def func(a): #def
s=m=n=0 #local variable
for i in range(0,a): #range function missing
if i%2==0:
s=s+i
elif i%5==0: #elif and colon
m=m+i
else:
n=n+i
print(s,m,n) #indentation
func(15)
Application Based Questions (3 Marks)
1. Write a function listchange(Arr)in Python, which accepts a list Arr of numbers , the function will replace the
even number by value 10 and multiply odd number by 5 .
Sample Input Data of the list is:
a=[10,20,23,45]
listchange(a,4)
output : [10, 10, 115, 225]
Ans:
def listchange(arr,n):
l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5
a=[10,20,23,45]
listchange(a)
print(a)
2. Write a function LShift(Arr,n) in Python, which accepts a list Arr of numbers and n is a numeric value by which all
elements of the list are shifted to left.
Sample Input Data of the list
Arr= [ 10,20,30,40,12,11], n=2
Output
Arr = [30,40,12,11,10,20]
Ans:
def LShift(Arr,n):
L=Arr[n::]
R=Arr[:n:]
Arr=L+R
print(Arr)
3. Write a function REP which accepts a list of integers and size of list and replaces elements having even values
with its half and elements having odd values with twice its value. eg: if the list contains
3, 4, 5, 16, 9
then the function should rearranged list as
6, 2,10,8, 18
Ans:
def REP (L, n):
for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
4. Write a function which accept the two lists, and returns a list having only those elements that are common
between both the lists (without duplicates) in ascending order.
Make sure your program works on two lists of different sizes. e.g.
L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
The output should be:
[1,2,3,5,8,13]
Ans: L1= [1,1,2,3,5,8,13,21,34,55,89]
L2= [20,1,2,3,4,5,6,7,8,9,10,11,12,13]
L3=[]
temp_L1=list(set(L1))
temp_L2=list(set(L2))
for i in temp_L1:
for j in temp_L2:
if i==j:
L3.append(i)
L3.sort()
print(L3)
5. Write a user defined function countwords() to accept a sentence from console and display the total number of
words present in that sentence.
For example if the sentence entered by user is:
“Living a life you can be proud of doing your best.” then the countwords() function should display the output
as:
Total number of words : 11
Ans:
def countwords():
sen = input(“Enter a line : ”)
z = sen.split ()
print ("Total number of words:", len(z))

You might also like