












Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The basic level topics are discussed in this chapter . Get more content on second chapter.
Typology: Study notes
1 / 20
This page cannot be seen from the preview
Don't miss anything!













Syllabus
Introduction, Variables, Assignments and
Statements, Functions
SIA GROUP
Learning Objectives
ÿ Introduction to a Program, The Process of Running a Python ÿ The Various Arithmetic Operators ÿ Variables and Variable Assignment in Python ÿ The Order of Evaluation and Various String Operations ÿ Functions and Calling a Function ÿ Adding and Defining New Functions ÿ About Variables and Parameters ÿ About Stack Diagrams ÿ Types of Functions Such as Fruitful Functions and Void Functions ÿ Use of Functions.
Introduction
Part-a Short QueStionS with SolutionS
Q1. What is Python?
Answer :
Python is a simple, high-level, interpreted, interactive, object oriented programming language when compared to other programming languages. It is very robust, elegant and a powerful language. It was designed to enhance the readability, extensibility and less unrequired variability of the ABC language. So, it is called as the successor of ABC language. It is also a very high-level language as it has higher level of abstraction than other languages. The first version of python was released in 1991 and later on various versions were released with many added features. The latest version of python is python 3.6.4.
Q2. What is meant by interpreter?
Answer :
Interpreter is a tool/program used for the execution of programs. It is a program that executes commands written in any language. It executes the source code either directly or converts it into a representation which is easily understood by the compiler.
In Python, interpreter is an execution environment which interprets the commands as soon as they are entered. It acts as a interface between the source code and the computer hardware. It enables the source code to be interpreted and executed quickly.
Q3. Outline the modes Python interpreter works.
Answer : Model Paper-I, Q1(a)
Python interpreter works in two modes. They are,
1. Interactive Mode
An interpreter mode allows the user to directly interact with the Python interpreter. That is, a user can directly write the programs in this mode.
2. Script Mode
A script mode allows the user to execute the programs/script files that are written and saved as .py files. It does not interact with the Python interpreter directly.
Q4. Define a variable and write down the rules for naming a variable.
Answer :
Variable can be defined as a storage location in memory. It stores data values of the programs and provides them whenever they are required within the program. Python does not require the variables to be declared and even the data type is not required to be specified. Rather only naming and assigning the values to it is enough. Python internally handles the variables according to the values assigned to them.
In general, a variable takes a meaningful name, containing alphabets, numbers and underscore( _ ). A variable must not begin with a number. Moreover, a variable name cannot be defined using special characters and keywords.
Q5. Discuss the various operators in python.
Answer : Model Paper-II, Q1(a)
An operator is defined as a symbol which performs manipulations on the value of operands. The various operators used in Python are as follows,
Q6. Write short notes on control flow and functions.
Answer : Model Paper-III, Q1(a)
Control Flow
In python, control flow is obtained by control statements. Control statements are the statements used to change the normal flow of program. Few control statement used in python are state, while, for, break, continue, pass etc.
Part-B^ eSSaY QueStionS^ with SolutionS
1.1 IntroductIon
1.1.1 What is a Program, running Python
Q11. What is a program? Write how python programs are run.
Answer : Model Paper-II, Q2(a)
Program
Program is a set of instructions developed from an algorithm. It is written in computer understandable language to accomplish certain task. Computers play a major role in solving a problem. This is because of the good communication that exists between computers and their corresponding users. In order to write a program, a process called ‘programming’ is required. But, before writing this, the problem to be solved should be analyzed and needs to be prepared by generating a step-by-step procedure. The sufficient details about the problem should be obtained. This process is referred to as ‘problem analysis’.
Running Python
Python is a simple, high level, interpreted, interactive, object-oriented programming language when compared to other programming languages. It is very robust, elegant and a powerful language. It's development started in 1989 by Guido Van Rossum. It was named after a TV show "Monty Python's Flying Circus". It was designed to enhance the readability, extensibility and less unrequired variability of the ABC language. So, it is called as the successor of ABC language. It is also a high-level language as it has higher level of abstraction than other languages. The first version of python was released in 1991 and later on various versions were released with many added features. The latest version of python is Python 3.6.4.
Python programs can be run in interactive and script mode.
1. Interactive Mode
Interpreters in Python can be used interactively. Running the programs interactively is very easy since it requires the programs statements to be written directly on the command line. These statements will be then evaluated there itself and the result is printed on the command line.
The steps to run python program interactively are as follows,
Step 1: Start the interactive interpreter interactively.
Step 2: Type the Python statement at the command prompt.
Step 3: Press Enter.
Each line at the command prompt is interpreted as soon as it is written. Then the interpreter displays a new prompt i.e., >>> for writing the next line. Then this line is evaluated. This process of writing a line and executing it immediately continues throughout the end of all the program statements.
Example
While writing the Python statement at the command prompt, the greater than symbols i.e., >>> denotes that a statement has to be written there. This is known as primary prompt.
The three dots i.e., … denotes that a multiple-line statement has to be written. This is known as secondary prompt.
Interpreter can then be exited after all the statements have been written and executed successfully.
2. Script Mode
For answer refer Unit-I, Q15.
1.1.2 Arithmetic operators, Value and types
Q12. List out different arithmetic operators used in python.
Answer : Model Paper-III, Q2(a)
Arithmetic Operators
These operators are used to perform various arithmetic operations like addition, division, multiplication, subtraction, etc. The various arithmetic operators used in Python are illustrated below,
(i) + (Addition)
This operator is used to add the values present on both the sides of the operator.
Example
8 + 10 = 18 (or)
x + y = 18 # x = 8, y = 10
(ii) – (Subtraction)
This operator is used to subtract one operand from another operand.
Example
8 – 10 = –2 (or)
x – y = –2 # x = 8, y = 10
(iii) * (Multiplication)
This operator is used to multiply the values present on both sides of the operators.
Example
8 * 10 = 80 (or)
x * y = 80 # x = 8, y = 10
(iv) / (Division)
This operator is used to divide one operand for another operand.
Example
8/10 = 0.8 (or)
x/y = 0.8 # x = 8, y = 10
1.2 VArIAbles, AssIgnments And stAtements
1.2.1 Assignment statements
Q14. Define variable. Write about assignment statements variable.
Answer : Model Paper-I, Q2(a)
Variable
Variable can be defined as a storage location in memory. It stores data values of the programs and provides them whenever they are required within the program. Python does not require the variables to be declared. Rather only naming and assigning the values to it is enough. Even the data type is not required to be specified. Python internally handles the variables according to the values assigned to them. Basically, a variable in a name refers to a value.
Example
>>> subject = ‘Python’ # subject is a variable >>> print(subject) Python In the above example, subject is a variable and it refers to a value ‘Python’. The print statement in the second line accepts a variable as input and displays the value “Python” as the output on the screen.
In general, a variable takes a meaningful name, containing alphabets, numbers and underscore( _ ). A variable must not begin with a number. Moreover variable name cannot be defined using special characters and keywords.
Example
The below declaration generates syntax error. >>> 1subject = ‘Python’ SyntaxError : invalid syntax >>> book@ = 250 SyntaxError : invalid syntax >>> class = ‘Python programming’ # class is a keyword SyntaxError = invalid syntax
Variable Assignment in Python
Variables in python are assigned by using an assignment or augmented assignment operator.
(a) Assignment Operator
In python, the main assignment operator is equal to (=) sign. Unlike other programming languages, this operator does not explicitly assign a value to a variable. In this language, objects are referenced.
(b) Augmented Assignment Operator
In python, augmented assignment refers to the use of combination of arithmetic operation and equal to (=) sign. The following example illustrates augmented assignment. i = i + 1 The above statement can also be written as follows, i + = 1
Multiple Assignment
In Python, multiple assignment can be done in two ways. They are as follows,
(i) Single object can be assigned to multiple variables.
Example
(ii) Multiple objects can be assigned to multiple variables within a single statement.
Example
1.2.2 script mode
Q15. Explain in brief about script mode.
Answer :
Python scripts can be written and executed in an easy manner. Initially type “Python” or “Python 3” in the command prompt to access python. With this python REPL (Read-Eval-Print-Loop) gets opened. User can enter the commands in it just like in command prompt. To exit from REPL type Ctrl-D. Besides this, the other way to execute the python script is discussed in the below steps,
Example
x= y= z=x+y print("The value of z is ", z)
Output
1.2.3 order of operations, string operations
Q16. What is order of operations followed while execution?
Answer : Model Paper-III, Q2(b)
If multiple operators are found in an expression then, the order of evaluation is based on the rules of precedence. Apart, from this, python follows certain mathematical rules for mathematical operators. The word PEMDAS is used to remember the rules.
Precedence of the operators is discussed below,
(a) Parentheses is used to evaluate an expression in sequence and it has the highest precedence. Therefore, the values which are in parentheses in an expression are evaluated first. Example: 3*(4– 1) is 9. Here, the operands within the parenthesis are evaluated first i.e., 4 – 1 = 3. Next the result is multiplied by 3 i.e., 3 * 3 = 9.
Output
(ii) String Repetition
Repetition is used to perform repetition of the specified string i.e., concatenating the string repeatedly. It uses ‘*’ operator for this purpose.
Syntax
string * number of times to be repeated
Example
Output
1.2.4 comments
Q18. Define comment. Explain how comments are declared in python with an example.
Answer :
Comments
Comments are simple statements written within a program inorder to make the program more understandable for the humans. These lines are neither read by the compilers nor by the interpreters. That is, a comment does not effect the execution of the program.
Generally, these lines provide a brief explanation of a particular line in a program. This enhances the readability of a program. Besides this, they allow a naive user/programmer to understand the logic behind the code easily and quickly.
A comment in Python is defined by using a hash symbol (#).
Syntax
Example
>>> a = b + 2 # Here, a and b are variables, b = 5 >>> print(a) # the value of a is printed as 5 + 2 = 7 7 In the above code, the statements defined in # symbol in line 1 and line 2 are comments.
Types of Comments
Comments are classified into two types which are as follows,
Inline comments are declared within the same line of the code. Example >>> x + = 1 # value of a is incremented by one. An inline comment specifies some additional information about the code. Example 2 d = 25 # distance in km/h i.e., kilometer/hour The above comment gives the details of the units of distance used in the code. Comments also provides a brief explanation about the variable. A variable name in programming can be declared using alphabets like a, b, c etc., with a comment beside inorder to make it more understandable. For example, v = 50 # velocity in m/sec Here, variable 'v' can be velocity, volume etc. Since a content is added after declaration so, it can be easily understood that 'v' refers to velocity.
2. Newline Comment
Newline comments are declared between the subsequent program lines. Example
>>> print(a)
1.3 FunctIons
1.3.1 Function calls, math Functions
Q19. Define function. How a function is called? Explain.
Answer : Model Paper-II, Q2(b)
Function
A function is defined as a block of code which can be used to perform an action. Functions in Python are similar to that of other programming languages. They organize program logic in a structural or procedural programming manner. They store the frequently separated code, inorder to be called whenever required and saves memory space from storing multiple copies of same data.
Python consists of various built-in functions such as print, input, etc. A function returns a value, some functions return non zero or zero value, while other functions return boolean values (true or false).
A function which does not return a value is a procedure. Procedures are special cases of a function 'void' as return type and their default return value is 'none'.
S.No. Function Description Example Output
math.radians(45) 0.
math.degrees(0.78539) 44.
math.pi 3.
math.trunc(7.94) math.trunc(math.pi)
math.log(10, 2) 3.
math.fmod(9, 2) 1.
math.hypot(3, 4) 5.
math.expml(2) 6.
1.3.2 composition, Adding new Functions, definitions and uses
Q21. Write short notes on composition.
Answer : Model Paper-I, Q2(b)
Function composition is the method of combining functions such that the output of the older function serves as the input to the newer function. That means, output of the first function can be passed as input to the second function and the output of second function can be passed as input to the third function and so on.
This type of combination is similar to performing math function f(g(x)). In this case, first the function g(x) is evaluated. Then the result of g(x) is taken as input to the function f(x).
Example
Output
In the above program, two functions are defined i.e., add and mul. These two functions are combined using "com" function. First add(x + 1) is evaluated i.e., 5 + 1 = 6 and the result 6 is obtained. This result is given as input to the function mul(x * 3). Upon evaluation of this function result 18 is obtained.
If three functions are to be combined, then the implementation is as follows,
Example 2
Output
In the above program, the function evaluation is similar to example 1. First add function is evaluated and its result i.e, 5 + 1 = 6 is given as input to the function mul (x * 3). This function obtains 6 * 3 = 18 as result. Finally this result is given as input to the function sub(x – 1) which obtains the result 18 – 1 = 17.
The above code contains two function definitions namely, print( ) and repeat( ). The execution of function definition is first like other statements. But the only effect is creation of function objects. The statements in function will not return until the function is called. The function definition will not generate any output. The user need to create a function before it is run. The function definition must be run before it is called. For example, move the last line of the code to top so that the function call will be displayed before all the definitions. Now, run the program and check the error messages. Move the function call to bottom again and then move the definition of print( ) after definition of repeat( ). Check the output of the code.
1.3.3 Flow of execution, Parameters and Arguments, Variables and Parameters are local
Q24. Write in short about flow of execution.
Answer :
Flow of execution of a Python code is defined as the order in which the statements of the code execute. In other words, the order of execution of statements is called the flow of execution.
The execution always starts from the initial line/statement of the Python code. Each statement is executed once starting from the first line till the end of the code. The statements that are present within the function are not executed until the function is called. Once the function name is called, the inner lines of the function get executed. Hence, a function call deviates the flow of execution of the code.
Whenever a function call is detected while executing the code, the program flow jumps to the body of the function and execute those lines. It then returns back to the line where it left and continues the execution from there. Python is accurate in terms of resuming or returning back to the appropriate line as soon as it executes any function. Moreover as soon as the code ends, the execution terminates and hence returns the output value.
Therefore, the code can be understood in a better manner if the flow of execution is followed while reading the code. Consider an example program to understand the flow of execution in a better way.
Example
Here, the flow of execution begins from line 6. That is, initially an integer is taken as input from the user. After that, the flow of execution moves to line 7 where the function call is detected. Then the flow of execution moves to the function definition in line 1. This function checks if the given number is odd or even by executing the lines defined within the function. That is, if the given number is 12 then if and else conditions are checked to know if the given number is odd or even. Finally, it prints the output with the help of print statement.
Q25. Discuss in brief about parameters and arguments.
Answer : Model Paper-III, Q3(a)
Parameters
A parameter is defined as a symbolic name given within the function header while defining the function. In simple terms, parameters are the input variables they are present in defining line of a function.
Syntax
def function_name(parameter(s)):
Example
def sum(a, b): In the above example, a and b are the parameters of the function 'sum'.
Argument
An argument is defined as the value that is substituted for the parameter. It is present within the input function call.
Syntax
function_name(argument(s))
Example
sum(25, 30) In the above example, 25 and 30 are the arguments that are substituted for the parameters a and b (of the function 'sum' defined above).
The parameter for a function is defined once in the code, whereas the arguments for that parameter can be substituted multiple times.
Example
>>> def sum(a, b) : # parameters a and b are defined once. c = a + b print(c) >>> sum(5, 10) # 5 and 10 are arguments 15 >>> sum(25, 30) # 25 and 30 are arguments 55 >>> sum(0, 20) # 0 and 20 are arguments 20 In the above example, the parameters a and b for the function 'sum' is defined once and the arguments for that parameters are substituted multiple times.
Q26. Are the variables and parameters local? Justify.
Answer :
A variable that is created inside a function is local to that function. That means, the variable exists only inside the function. Consider the below example.
def fun(val1, val2): x = val1 + val return x The above function accepts two arguments, concatenates them and then prints the result. >>> a = 'xyz' >>> b = 'pqr' >>> fun (a, b) xyz pqr The variable x gets destroyed when the function fun( ) terminates. Trying to print it will generate an exception.
_ main _
fun
printf( )
a → 'x y z' b → 'p q r'
val 1 → 'xyz' val 2 → 'pqr' x → 'xyz pqr'
Harry → 'xyz pqr'
Figure: Stack Diagram >>> print (x) NameError: name 'x' is not defined. The parameters are also local. Incase of the function printf( ) for example, there is no such thing as Harry.
>>> result = print('xyz') xyz
xyz
>>> print (result)
None
The value 'None' here has same meaning of None. It is a special value and has its own type. >>> type (None)
Q29. Illustrate the need for functions.
Answer :
Functions are needed in Python programming for following reasons,
If functions are used within the Python code, they minimizes the code duplications. That is, instead of defining same code multiple times within a program, a user can make use of functions. This reduces the flow of errors in a program and also saves the time of the user. Hence, to reduce the duplication of code, Python functions are useful/necessary.
2. Helps in Splitting Difficult Tasks
Functions enables a user to divide difficult/complex tasks or procedures into smaller parts. Here, each smaller part/block becomes a function. This makes the process of debugging simpler and easier.
3. Hides the Implementation Details
Functions hides the implementation details from users. This makes the program simple to read and understand. Hence, hiding the implementation details using functions saves the time of the reader.
4. Improves Readability
Functions are included in Python to improve the readability of the code.
ExErcisE QuEstions
important QuEstions
Short QueStionS
eSSaY QueStionS