Module 1
Module 1
Variables, Keywords
Statements and Expressions
Operators, Precedence and Associativity Data Types, Indentation,
Comments
Reading Input, Print Output
Type Conversions, The type( ) Function and Is Operator Control Flow
Statements
— The if Decision Control Flow Statement,
— The if…else Decision Control Flow Statement
— The if…elif…else Decision Control Statement
— Nested if Statement
— The while Loop
— The for Loop
— The continue and break Statements
Built-In Functions, Commonly Used Modules Function Definition and Calling
the Function The return Statement and void Function Scope and Lifetime of
Variables
Default Parameters, Keyword Arguments *args and **kwargs,
Command Line Arguments
Introduction
Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.
Easy-to-read − Python code is more clearly defined and visible to the eyes.
A broad standard library − Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
Interactive Mode − Python has support for an interactive mode which allows interactivetesting
and debugging of snippets of code.
Portable − Python can run on a wide variety of hardware platforms and has the sameinterface
on all platforms.
Databases − Python provides interfaces to all major commercial databases.
Scalable − Python provides a better structure and support for large programs than other
scripting languages.
Python has rich set of libraries for various purposes like large-scale data processing, predictive
analytics, scientific computing etc. Based on one’s need, the required packages can be
downloaded. But there is a free open source distribution Anaconda, which simplifies package
management and deployment. Hence, it is suggested for the readers to install Anaconda from
the below given link, rather than just installing a simple Python.
https://anaconda.org/anaconda/python
Successful installation of anaconda provides you Python in a command prompt, the default
editor IDLE and also a browser-based interactive computing environment known as Jupyter
notebook.
Hence these high-level programming language has to be translated into machine language
using translators such as : (1) interpreters and (2) compilers.
The difference between an interpreter and a compiler is given below:
Interpreter Compiler
Programming language like Python, Ruby Programming language like C, C++ use
use interpreters. compilers.
Writing a program
Program can be written using a text editor.
To write the Python instructions into a file, which is called a script. By convention, Python
scripts have names that end with .py .
To execute the script, you have to tell the Python interpreter the name of the file. In acommand
window, you would type python hello.py as follows:
$ cat hello.py
print('Hello world!')
$ python hello.py
Hello world!
The “$” is the operating system prompt, and the “cat hello.py” is showing us that the file
“hello.py” has a one-line Python program to print a string. We call the Python interpreter and
tell it to read its source code from the file “hello.py” instead of prompting us for lines of Python
code
— Interpreter
Compilation
The program is converted into byte code. Byte code is a fixed set of instructions that represent
arithmetic, comparison, memory operations, etc. It can run on any operating system and
Interpreter
The next step involves converting the byte code (.pyc file) into machine code. This step is
necessary as the computer can understand only machine code (binary code). Python Virtual
Machine (PVM) first understands the operating system and processor in the computer and then
converts it into machine code. Further, these machine code instructions are executed by processor
and the results are displayed.
Flow
Controls There are some low-level conceptual patterns that we use to construct programs. These constructs
are not just for Python programs, they are part of every programming language from machine language up to
the high-level languages. They are listed as follows: Sequential execution: Perform statements one after
another in the ordertheyare encountered in the script.
Conditional execution: Check for certain conditions and then execute or skip a sequence of
statements. (Ex: statements with if-elfi-else)
Repeated execution: Perform some set of statements repeatedly, usually with some
variation. (Ex: statements with for, while loop)
Reuse: Write a set of instructions once and give them a name and then reuse those instructions as
needed throughout your program. (Ex: statements in functions)
A Python 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, Manpower and manpower are two different
identifiers in Python.
Here are naming conventions for Python identifiers
— Class names start with an uppercase letter. All other identifiers start with a lowercase letter.
— Starting an identifier with a single leading underscore indicates that the identifier is private.
The type of a variable is the type of the value it refers to above example >>> type(message)
<class 'str'>
#type refers to string
>>> type(n)
<class 'int'>
#type refers to integer
>>> type(pi)
<class 'float'>
#type refers to float
Rules to follow when naming the variables.
— Variable names can contain letters, numbers, and the underscore. — Variable
names cannot contain spaces and other special characters. — Variable names cannot
start with a number.
— Case matters—for instance, temp and Temp are different.
— Keywords cannot be used as a variable name.
Keywords
Keywords are a list of reserved words that have predefined meaning. Keywords are special vocabulary
and cannot be used by programmers as identifiers for variables, functions, constants or with any
identifier name. Attempting to use a keyword as an identifier name will cause an error. The following
table shows the Python keywords.
and del from None True def lambda
as elif global nonlocal Try raise returnassert else if not While finally break except import or with is
Statements and
Expressions
Statement
A statement is a unit of code that the Python interpreter can execute. We have
seen two kinds of statements:
— assignment statement: We assign a value to a variable using the assignment statement (=).
An assignment statement consists of an expression on the right-hand side and a variable to
store the result. In python ,there is special feature for multiple assignments, where more than
one variable can be initialized in single statement.
Ex: str=”google”
x = 20+y
a, b, c = 2, “B”, 3.5
print statement : print is a function which takes string or variable as a argument to display it on the
screen.
Following are the examples of statements –
>>> x=5
#assignment statement
#assignment statement
>>> x=5+3
#printing statement
>>> print(x)
end : The print function will automatically advance to the next line. For instance, the following will
print on two lines:
code output
print("A")
print("B")
print("C", end=" ")
print("E")
Expressions
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. If you type an expression in interactive
mode, the interpreter evaluates it and displays the result: >>> x=5
>>> x+1
6
Operators, Precedence and Associativity Operators are special symbols that represent
computations like addition and multiplication. The values the operator is applied to are called operands.
Here is list of arithmetic operators
Operator Meaning Example
+ Addition Sum= a+b
- Subtraction Diff= a-b
Division a=2
/ b=3
div=a/b
(div will get a value 1.3333333)
F = a//b
// Floor Division – A= 4//3 (X will get a value 1)
returns only integral
part of qotient after
division A= a %b
(Remainder after dividing a by b)
% Modulus – remainder after
Division
** Exponent E = x** y
(means x to the power of y)
Relational or Comparison Operators: are used to check the relationship (like less than, greater than
etc) between two operands. These operators return a Boolean valueeither True or False.
Assignment Operators: Apart from simple assignment operator = which is used for assigning
values to variables, Python provides compound assignment operators. For example,
statements Compound
statement
x=x+y x+=y
y//=2
y=y//2
Logical Operators: The logical operators and, or, not are used for comparing or negating the logical
values of their operands and to return the resulting logical value. The values of the operands on
which the logical operators operate evaluate to either True or False. The result of the logical
operator is always a Boolean value, True or False.
True
True
>>> not x
False
Precedence and Associativity (Order of operations) When an expression contains more than one
operator, the evaluation of operators depends on the precedence of operators.
The Python operators follow the precedence rule (which can be remembered as PEMDAS) as
given below :
— Parenthesis have the highest precedence in any expression. The operations within parenthesis
will be evaluated first.
— Exponentiation has the 2nd precedence. But, it is right associative. That is, if there are two exponentiation
operations continuously, it will be evaluated from right to left (unlike most of other operators which are
evaluated from left to right). For example
— Multiplication and Division are the next priority. Out of these two operations, whichever comes first
in the expression is evaluated.
— Addition and Subtraction are the least priority. Out of these two operations, whichever appears first in
the expression is evaluated i.e., they are evaluated from left to right .
Example : x = 1 + 2 ** 3 / 4 * 5
Numbers
Integers, floating point numbers and complex numbers fall under Python numbers category. They
are defined as int, float and complex class in Python. Integers can be of any length; it is only
limited by the memory available. A floating-point number is accurate up to 15 decimal places.
Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is floating point
number. Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.
Boolean
Booleans may not seem very useful at first, but they are essential when you start using conditional
statements. Boolean value is, either True or False. The Boolean values, True and False are treated
as reserved words.
Module 1 [22MCA31] Data Analytics using Python
Strings
A string consists of a sequence of one or more characters, which can include letters, numbers, and other types
of characters. A string can also contain spaces. You can use single quotes ordouble quotes to represent
strings and it is also called a string literal. Multiline strings can bedenoted using triple quotes, ''' or " " ". These
are fixed values, not variables that you literallyprovide in your script.
For example,
1. >>> s = 'This is single quote string'
2. >>> s = "This is double quote string"
3. >>> s = '''This
is Multiline
string'''
List
A list is formed(or created) by placing all the items (elements) inside square brackets [ ],separated
by commas.It can have any number of items and they may or may not be of differenttypes (integer,
float, string, etc.).
Example : List1 = [3,8,7.2,"Hello"]
Tuple
A tuple is defined as an ordered collection of Python objects. The only difference between
tupleand list is that tuples are immutable i.e. tuples can’t be modified after it’s created. It
isrepresented by tuple class. we can represent tuples using parentheses ( ). Example: Tuple =
(25,10,12.5,"Hello")
Dictionary
Dictionary is an unordered collection of data values, which is used to store data values like amap, which,
unlike other Data Types that hold only a single value as anelement, aDictionary consists of key-value pair.
Key-value is provided within the dictionary to form itmore optimized. In the representation of a dictionary data
type, each key-value pair during aDictionary is separated by a colon: whereas each key’s separated by a
‘comma’. Example: Dict1 = {1 : 'Hello' , 2 : 5.5, 3 : 'World' }
None
None is another special data type in Python. None is frequently used to represent the absenceof a
value. For example, >>> money = None
Any statements written under another statement with the same indentation is interpreted tobelong to the same
code block. If there is a next statement with less indentation to the left, then it just means the end of the
previous code block.
In other words, if a code block has to be deeply nested, then the nested statements need to beindented
further to the right. In the above diagram, Block 2 and Block 3 are nested underBlock 1. Usually, four
whitespaces are used for indentation and are preferred over tabs. Incorrect indentation will result in
Indentation Error.
Comments
As programs get bigger and more complicated, they get more difficult toread. Formalprogramming
languages are many, and it is often difficult to look at a piece of code and figureout what it is doing, or
why.
For this reason, it is a good idea to add notes to your programs to explain in natural languagewhat
the program is doing. These notes are called comments, and in Python they start withthe #
symbol:
Ex1. #This is a single-line comment
Ex2. ''' This is a
multiline
comment '''
Reading Input
Python provides a built-in function called input that gets input from the keyboard. When this
function is called, the program waits for the user input. When the user press the Enter key, the
program resumes and input returns user value as a string.
For example
>>> inp = input()
Welcome to world of python
>>> print(inp)
Welcome to world of python
It is a good idea to have a prompt message telling the user about what to enter as a value. You
can pass that prompt message as an argument to input function.
>>>x=input('Please enter some text:\n')
Please enter some text:
Roopa
>>> print(x)
Roopa
The sequence \n at the end of the prompt represents a newline, which is a special characterthat causes a
line break. That’s why the user’s input appears below the prompt. If you expect the user to type an integer,
you can try to convert the return value to int using the int() function:
Example1:
>>> prompt = 'How many days in a week?\n'
>>> days = input(prompt)
How many days in a week?
7
>>> type(days)
<class 'str'>
Example 2:
>>> x=int(input('enter number\n')) enter
number
12
>>> type(x)
<class 'int'>
Print Output
Format operator
The format operator, % allows us to construct strings, replacing parts of the strings with thedata
stored in variables.
When applied to integers, % is the modulus operator. But when the first operand is a string, % is the format
operator.
For example, the format sequence “%d” means that the operand should be formatted as
aninteger (d stands for “decimal”):
Example 1:
>>> camels = 42
>>>'%d' % camels
'42'
A format sequence can appear anywhere in the string, so you can embed a value in asentence:
Example 2 :
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
If there is more than one format sequence in the string, the second argument has to be atuple.
Each format sequence is matched with an element of the tuple, in order. The following example
uses “%d” to format an integer, “%g” to format a floating point number, and “%s” to format a string:
Example 3:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
Format function
format() : is one of the string formatting methods in Python3, which allows multiplesubstitutions and
value formatting. This method lets us concatenate elements within a stringthrough positional
formatting.
Two types of Parameters:
— positional_argument
— keyword_argument
Positional argument: It can be integers, floating point numeric constants, strings,
charactersand even variables.
Keyword argument : They is essentially a variable storing some value, which is passed as parameter.
".format("RNSIT","EC”))
Reverse the index >>>print("{1} department {0} college numbers with the
Keyword arguments are print("EC department {0} ‘D’ section {college}" called by their keyword
.format("6", college="RNSIT"))
name
EC department 6 ‘D
f-strings
Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal that is
prefixed with “f”. These strings may contain replacement fields, which are expressions enclosed
within curly braces {}. The expressions are replaced with their values.
Example : >>>a=10
>>>print(f”the value is {a}”)
the value is 10
Is Operator
If we run these assignment statements:
a = 'banana'
b = 'banana'
Figure: (a)
We know that a and b both refer to a string, but we don’t know whether they refer to thesame
string. There are two possible states, shown in Figure (a).
In one case, a and b refer to two different objects that have the same value. In the second case,
they refer to the same object. That is, a is an alias name for b and viceversa. In other words,
these two are referring to same memory location.
To check whether two variables refer to the same object, you can use the is operator.
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
When two variables are referring to same object, they are called as identical objects. When two
variables are referring to different objects, but contain a same value, they are known as equivalent objects.
>>>s1=input(“Enter a string:”)
>>>s2= input(“Enter a string:”)
>>>s1 is s2
False
>>>s1 == s2
True
If two objects are identical, they are also equivalent, but if they are equivalent, they are not
necessarily identical.
A conditional statement gives the developer to ability to check conditions and change the
behaviour of the program accordingly. The simplest form is the if statement: 1) The if Decision
Control Flow Statement
Syntax,
if condition:
statement 1 statement 2
……………..
statement n
x=1
if x>0:
print("positive
number")
Output:
positive number
The Boolean expression after the if keyword is called the condition. The if statement consists of
a header line that ends with the colon character (:) followed by an indented block. Statements like
this are called compound statements because they stretch across more than one line.
If the logical condition is true, then the block of statements get executed. If the logical condition is
false, the indented block is skipped.
2) The if…else Decision Control Flow Statement (alternative execution) A second form of the if statement
is alternative execution, in which there are two possibilities and the condition determines which one gets
executed is as shown in flowchart below. The syntax looks like this:
Syntax:
if condition :
statements
else :
statements
x=6
if x%2 == 0:
print('x is even')
else :
print('x
is
odd') Figure : if-Then-Else Logic
3) The if…elif…else Decision Control Statement (Chained conditionals) If there are more than two
possibilities and we need more than two branches. One way to express a computation like that is a chained
conditional. elif is an abbreviation of “else if.” Again, exactly one branch will be executed is as shown in flowchart
below.
Output:
X is less than y
4) Nested if Statement
The conditional statements can be nested. That is, one set of conditional statements can be
nested inside the other.
Let us consider an example, the outer conditional statement contains two branches.
Example Output:
x=3 x is less than y
y=4
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Pag
Module 1 [22MCA31] Data Analytics using Python
Nested conditionals make the code difficult to read, even though there are properindentations.
Hence, it is advised to use logical operators like and to simplify the nestedconditionals.
If Python detects that there is nothing to be gained by evaluating the rest of alogicalexpression, it stops its
evaluation and does not do the computations in the rest of the logicalexpression. When the evaluation of a
logical expression stops because the overall value isalready known, it is called short-circuiting the
evaluation.
However ,if the first part of logical expression results in True, then the second part has to
beevaluated to know the overall result. The short-circuiting not only saves the
computationaltime, but it also leads to a technique known as guardian pattern.
Consider the below examples:
Example1 Example 2
Example 3>>> x = 6
>>> x = 6
>>> y = 2 >>> y = 0
>>> x = 1
>>> x >= 2 and
>>> x >= 2 and (x/y) > 2
(x/y) > 2 >>> y = 0
True
Traceback (most recent call
>>> x >= 2 and
last):
(x/y) > 2
ZeroDivisionError: division
False
by zero
Example 2
>>> x = 6
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False
Example 3
>>> x >= 2 and (x/y) > 2 and y != 0 Traceback
(most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
In the first logical expression, x >= 2 is False so the evaluation stops at first condition itself. In the second
logical expression, x >= 2 is True but y != 0 is False so it never reach thecondition (x/y).
In the third logical expression, the y!= 0 is placed after the (x/y)>2 condition so
theexpression fails with an error.
Pag
In the second expression, we say that y != 0 acts as a guard to insure that we only execute (x/y)
if y is non-zero.
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many
programming problems. Iteration and conditional execution form the basis for algorithm construction.
Also notice that, variable i is initialized before starting the loop and it is incremented inside the loop.
Such a variable that changes its value for every iteration and controls the total execution of the loop
is called as iteration variable or counter variable. If the count variable is not updated properly within
the loop, then the loop may enter into infinite loop.
Here, the condition is always True, which will never terminate the loop. Sometimes, the condition is
given such a way that it will never become false and hence by restricting the program control to
go out of the loop. This situation may happen either due to wrong condition or due to not updating
the counter variable.
Hence to overcome this situation, break statement is used. The break statement can be used to
break out of a for or while loop before the loop is finished.
Here is a program that allows the user to enter up to 10 numbers. The user can stop early by
entering a negative number.
All the lines are printed except the one that starts with the hash sign because when the continue is
executed, it ends the current iteration and jumps back to the while statement to start the next
iteration, thus skipping the print statement.
Definite loops using for
Sometimes we want to loop through a set of things such as a list of words, the lines in a file, or a
list of numbers. When we have a list of things to loop through, we can construct a definite loop
using a for statement.
Page 25
for statement loops through a known set of items so it runs through as many iterations as there
are items in the set.
There are two versions in for loop:
— for loop with sequence
— for loop with range( ) function
—In the example, the variable friends is a list of three strings and the for loop goes through the
list and executes the body once for each of the three strings in the list. —name is the iteration
variable for the for loop. The variable name changes for each iteration
of the loop and controls when the for loop completes. The iteration variable steps successively
through the three strings stored in the friends variable. The for loop can be used to print (or
extract) all the characters in a string as shown below :
ello
The start and end indicates starting and ending values in the sequence, where end is
excluded in the sequence (That is, sequence is up to end-1). The default value of start is 0.
4 2
for i in range(5,0,-1): 5 print(i) 3 print('Blast off!!') 1 Blast off !!
Function types
Built in functions
User defined functions
Built-in functions
Python provides a number of important built in functions that we can use without needing to
provide the function definition.
Built-in functions are ready to use functions.
The general form of built-in functions: function_name(arguments)
An argument is an expression that appears between the parentheses of a function call and each
argument is separated by comma .
The function randint() takes the parameters low and high, and returns an integer between low and high
(including both).
>>> import random
>>> random.randint(5,10)
10
>>> random.randint(5,10)
6
>>> random.randint(5,10)
7
To choose an element from a sequence at random, you can use choice():
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
Function Definition and Calling the Function Python facilitates programmer to define
his/her own functions.
The function written once can be used wherever and whenever required. The syntax of
user-defined function would be:
def fname(arg_list): Here,
statement_1 def : is a ke
statement_2 fname : is a
arg_list : is
……………
inputs to th
statement_n
The
return value statements
is a keywo
Pag
The first line in the function def fname(arg_list) is known as function header/definition. The
remaining lines constitute function body.
The function header is terminated by a colon and the function body must be indented. To come out of
the function, indentation must be terminated. Unlike few other programming languages like C, C++ etc,
there is no main() function or
specific location where a user-defined function has to be called. The programmer has to
invoke (call) the function wherever required. Consider a simple example of user-defined
function –
Function calls
A function is a named sequence of instructions for performing a task. When we define a
function we will give a valid name to it, and then specify the instructions for performing required task.
Then, whenever we want to do that task, a function is called by its name.
Consider an example,
>>> type(33)
<class 'int'>
Here, type function is called to know the datatype of the value. The expression in parenthesis is
called the argument of the function. The argument is a value or variable that we are passing into
the function as input to the function.
It is common to say that a function “takes” an argument and “returns” a result. The result iscalled
the return value.
The return Statement and void Function A function that performs some task, but do not return
any value to the calling function is known as void function. The examples of user-defined functions
considered till now are void functions.
The function which returns some result to the calling function after performing a task is known as
fruitful function. The built-in functions like mathematical functions, random
P
number generating functions etc. that have been considered earlier are examples for fruitful
functions.
One can write a user-defined function so as to return a value to the calling function as shown in
the following example.
— In the above example, The function addition() take two arguments and returns their sum to the
receiving variable x.
— When a function returns something and if it is not received using a some variable, the return value will
not be available later.
When we are using built –in functions, that yield results are fruitful functions. >>>math.sqrt(2)
1.7320508075688772
The void function might display something on the screen or has some other effect.
theyperform an action but they don’t have return value.
Consider an example
>>> result=print('python')
python
>>> print(result)
None
>>> print(type(None))
<class 'NoneType'>
The scope of a variable determines the portion of the program where you can access a particular identifier.
There are two basic scopes of variables in Python
— Global variables
— Local variables
Global vs. Local variables
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.
sum( 10, 20 ); # Now you can call sum function print("Outside the function global total
: ", total)
Output :
Inside the function local total : 30
Outside the function global total : 0
Default Parameters
For some functions, you may want to make some parameters optional and use default values in
case the user does not want to provide values for them. This is done with the help of default
argument values.
Default argument values can be specified for parameters by appending to the parameter name in the function
definition the assignment operator ( = ) followed by the default value.
ge 33
How It Works
The function named say is used to print a string as many times as specified. If we don't supply a
value, then by default, the string is printed just once. We achieve this by specifying a default
argument value of 1 to the parameter times . In the first usage of say , we supply only the string and
it prints the string once. In the second usage of say , we supply both the string and an argument 5
stating that we want to say the string message 5 times.
Keyword Arguments
If you have some functions with many parameters and you want to specify only some of them, then
you can give values for such parameters by naming them - this is called keyword arguments - we
use the name (keyword) instead of the position to specify the arguments to the function.
There are two advantages
— one, using the function is easier since we do not need to worry about the order of the arguments. — Two, we can
give values to only those parameters to which we want to, provided that the other parameters have default argument
values.
func(3, 7)
func(25, c=24)
func(c=50, a=100)
Output:
a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50
How It Works
The function named func has one parameter without a default argument value, followed by two
parameters with default argument values. In the first usage, func(3, 7) , the parameter a gets the
value 3 , the parameter b gets the value 7 and c gets the default value of 10 . In the second usage
func(25, c=24) , the variable a gets the value of 25 due to the position of the argument. Then, the
parameter c gets the value of 24 due to naming i.e. keyword arguments. The variable b gets the
default value of 5 . In the third usage func(c=50, a=100) , we use keyword arguments for all
specified values. Notice that we are specifying the value for parameter c before that for a even
though a is defined before c in the function definition.
*args and **kwargs, Command Line Arguments Sometimes you might want to define a function
that can take any number of parameters, i.e. variable number of arguments, this can be achieved by
using the stars. *args and **kwargs are mostly used as parameters in function definitions. *args
and**kwargs allows you to pass a variable number of arguments to the calling function. Here
variable number of arguments means that the user does not know in advance about how many
arguments will be passed to the called function.
*args as parameter in function definition allows you to pass a non-keyworded, variable length tuple
argument list to the called function.
**kwargs as parameter in function definition allows you to pass keyworded, variable length
dictionary argument list to the called function. *args must come after all the positional parameters and
**kwargs must come right at the end
Note: statement blocks of the function definition * and ** are not used with args and kwargs.
if len(argv) < 3:
print('Supply range of values')
else:
for n in range(int(argv[1]), int(argv[2]) + 1):
print(n, sqrt(n))
Output:
C:\Code>python sqrtcmdline.py 2 5 2 1.4142135623730951
3 1.7320508075688772
4 2.0
5 2.23606797749979
Pa
Question Bank
Q.
No. Questions
1 Explain the features of python.
2 Give the comparison between Interpreter and compiler
3 Define python? List the standard data types of python? 4 Explain Type conversion in
Python with examples.
5 Write a short note on data types in Python.
6 Differentiate between local and global variables with suitable examples.
Write short notes on :
i)Variables and statements
7
ii)Expressions
iii) String and Modules operator
8
Explain with example how to read input from user in python 9
Explain the different types of arithmetic operators with example.
10 Discuss operator precedence used in evaluating the
11
expression Briefly explain the conditional statements
available in Python. 12 Explain the syntax of for loop with an
example
13 When to use nested condition in programming? Discuss with an
example. 14 Explain the fruitful and void functions? Give examples. 15
With an example, Demonstrate effective coding with functions in Python.
16 Explain the working of python user defined functions along with its
syntax.
Explain the following terms
i)Boolean and logical expression
17
ii) Condition execution and alternative execution with
syntax iii)Chained conditions
iv)Short circuit evaluation of logical expression
18
Illustrate the three functions of random numbers with
19
example List and explain all built in math functions with
20
example Write a note on short circuit evaluation for logical
expression Predict the output for following expression:
i)-11%9
21 *10/5 iv)
ii) 7.7//7 5*2**1
iii)(200-7)
22
What is the purpose of using break and continue?
23 Differentiate the syntax of if...else and if...elif...else with an example.
22
Create a python program for calculator application using functions
23
Define function. What are the advantages of using a function?
24
Differentiate between user-defined function and built-in functions.
25
Explain the built-in functions with examples in Python.
26 Explain the advantages of *args and **kwargs with examples.