Q1 Why Should You Learn To Write Programs ?
Q1 Why Should You Learn To Write Programs ?
MODULE 1
Steve Jobs once said, "Everybody in this country should learn how to program a computer...
because it teaches you how to think."
Computer programming is an enormously flexible tool that you can use to do amazing things
that are otherwise either manual and laborsome or are just impossible. If you're using a
smartphone, a chat app or if you're unlocking your car with the push of a button, then you
must know that all these things are using some kind of programming. You're already
immersed in the programs of different types. In fact, software is running your life. What if
you learn and start running these programs according to your will?
Features Applications
It is also used for automation and for performing a lot of other tasks.
Q5 What is a Program ?
In computing, a program is a specific set of ordered operations for a computer to perform.
In the modern computer that John von Neumann outlined in 1945, the program contains a
one-at-a-time sequence of instructions that the computer follows. Typically, the program is
put into a storage area accessible to the computer. The computer gets one instruction,
performs it, and then gets the next instruction. The storage area or memory can also contain
the data that the instruction operates on.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
While the specific rules of a programming language differ from one language to another, the
underlying foundation upon which all programming languages are built is pretty much the
same. There is a hierarchy that all languages follow. This hierarchy is:
You can verbalize this hierarchy like this: "Programs consist of one or more statements.
Statements consist of one or more expressions. Expressions consist of one or more operands
in conjunction with one or more operators." Therefore, to write a program you must
understand operands and operators.
Q6 what is compiler?
The compiler derives its name from the
way it works, as looking at the entire
piece of source code and collecting and
reorganizing the instructions. It translates
high-level instructions directly into
machine language. Compiled programs
generally run faster. The machine code
which typically stored in a file is also
referred as binary code and can be
directly executed by the machine after
linking. Examples of compiled programming languages are C, C++, C#, Objective-C,
SWIFT, and Fortran.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Q7 what is interpreter?
In contrast, an interpreter directly executes instructions written in a programming or
scripting language without previously converting them to an object code or machine code.
That means you write the program using a text editor or something similar, and then instruct
the interpreter to run the program. It takes the program one line at a time and translates each
line before executing it. It translates the first line and runs it and then the second line so on.
Examples of interpreted languages are Perl, Python, Ruby, PHP, JAVA, R, Powershell and
Matlab.
Both compilers and interpreters covert source code which refers text files into machine
language. Both may generate a parse tree and may generate immediate instructions. But
between these translators, there has some technical and processing difference.
Interactive Mode: The interpreter operates somewhat like the Unix shell: when called with
standard input connected to a tty device, it reads and executes commands interactively; when
called with a file name argument or with a file as standard input, it reads and executes a
script from that file.
When commands are read from a tty, the interpreter is said to be in interactive mode. In this
mode it prompts for the next command with the primary prompt, usually three greater-than
signs (>>>); for continuation lines it prompts with the secondary prompt, by default three
dots (...). The interpreter prints a welcome message stating its version number and a
copyright notice before printing the first prompt:
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
and, as, assert, break, class, continue, def, del, elif, else, except,
False, finally, for, from, global, if, import, in, is, lambda, None,
nonlocal, not, or, pass, raise, return, True, try, while, with, Yield
Python allows you to assign a single value to several variables simultaneously. For example-
a = b = c = 1
a, b, c = 1, 2, "john"
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
In many programming languages, variables are statically typed. That means a variable is
initially declared to have a specific data type, and any value assigned to it during its lifetime
must always have that type.Variables in Python are not subject to this restriction. In Python,
a variable may be assigned a value of one type and then later re-assigned a value of a
different type:
var = 23.5; print(var)
var = "Now I'm a string";
print(var)
The name of the variable can only begin with an underscore or a letter (a-z, A-
Z) which can be followed by letters, numbers (0-9) and underscores. For
example: user_name, count, __name, pw123, etc.
All the python identifiers including variable names are case-sensitive. That is,
userName and username are two different variables.
Variable names can not contain punctuation characters like &, %, *, etc.
Python keywords or reserved words can not be used as variable names. Here is
a list of all the python keywords.
Variables are defined inside a function have local scope whereas those are defined in a
module have global scope. In this example, variable m is a global variable. You can refer
to it in any functions within the script. Its lifespan lasts during program execution.
Variable n is a local variable because it is defined within the f1() function. Its lifespan
begins when entering into the f1() function and ends when the f1() function completes.
You cannot refer to the n variable outside the f1() function.
m = 30 # global variable
def f1():
m = 20
print(m)
print(m)
f1()
What will display in the output? In this example, a global variable and local variable share
the same name. When you call the print(m) function, Python searches for the m variable
within its scope therefore the global variable m is referred to. However, when you
call the f1() function, Python will use local variable m inside the function. The rule is that,
when looking for a variable, Python searches the local scope first. If the variable is not found
within the local scope, it continue to search in the global scope. If the variable still not found,
it raises a NameError exception. Python provides the global keyword to help you refer to
global variables explicitly inside a function.
m = 30 # global variable
def f1():
global m
m = 20 # change global variable
f1()
print(m)
“Confusingly, evaluating an expression is not quite the same thing as printing a value. When the Python
interpreter displays the value of an expression, it uses the same format you would use to enter a value. In the
case of strings, that means that it includes the quotation marks. But if you use a print statement, Python
displays the contents of the string without the quotation marks.”
Operators and operands: Operators are special symbols that represent computations like
addition and multiplication. The values the operator is applied to are called operands. The
operators +, -, *, /, and ** perform addition, subtraction, multiplication, division, and
exponentiation, as in the examples given in the below topic.
Parentheses have the highest precedence and can be used to force an expression
to evaluate in the order you want. Since expressions in parentheses are
evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use
parentheses to make an expression easier to read, as in (minute * 100) /60, even
if it doesn’t change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3, not 4, and
3*1**3 is 3, not 27.
Multiplication and Division have the same precedence, which is higher than
Addition and Subtraction, which also have the same precedence. So 2*3-1 is 5,
not 4, and 6+4/2 is 8, not 5.
Operators with the same precedence are evaluated from left to right. So the
expression 5-3-1 is 1, not 3, because the 5-3 happens first and then 1 is
subtracted from 2.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Logic errors
A logic error is when your program has good syntax but there is a mistake in the
order of the statements or perhaps a mistake in how the statements relate to one
another.
A good example of a logic error might be, “take a drink from your water bottle, put
it in your backpack, walk to the library, and then put the top back on the bottle.”
Semantic errors
A semantic error is when your description of the steps to take is syntactically
perfect and in the right order, but there is simply a mistake in the program.
The program is perfectly correct but it does not do what you intended for it to do
When a logical expression (expression involving operands and, or, not) is being evaluated,
it will be processed from left to right. For example, consider the statements -
x= 10
y=20
if x<10 and x+y>25:
#do something
Here, the expression x<10 and x+y>25 involves the logical operator and. Now, x<10 is
evaluated first, which results to be False. As there is an and operator, irrespective of the
result of x+y>25, the whole expression will be False. In such situations, Python ignores the
remaining part of the expression. This is known as short-circuiting the evaluation. When
the first part of logical expression results in True, then the second part has to be evaluated
to know the overall result.
The short-circuiting not only saves the computational time, but it also leads to a technique
known as guardian pattern. Consider following sequence of statements –
>>> x=5
>>> y=0
>>> x>=10 and (x/y)>2
False
>>> x>=2 and (x/y)>2
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Here, when we executed the statement x>=10 and (x/y)>2, the first half of logical expression
itself was False and hence by applying short-circuit rule, the remaining part was not
executed at all. Whereas, in the statement x>=2 and (x/y)>2, the first half is True and the
second half is resulted in runtime-error. Thus, in the expression x>=10 and (x/y)>2, short-
circuit rule acted as a guardian by preventing an error.
if BOOLEAN EXPRESSION:
STATEMENTS
The boolean expression after the if statement is called the condition. If it is true, then all
the indented statements get executed. What happens if the condition is false, and food is not
equal to 'spam'? In a simple if statement like this, nothing happens, and the program
continues on to the next statement.
Here is an example:
food = 'spam'
if food == 'spam':
print('Ummmm, my favorite!')
print('I feel like saying it 100 times...')
print(100 * (food + '! '))
The if else statement: It is frequently the case that you want one thing to happen when a
condition it true, and something else to happen when it is false. For that we have the if else
statement.
if food == 'spam':
print('Ummmm, my favorite!')
else:
print("No, I won't have it. I want spam!")
Here, the first print statement will execute if food is equal to 'spam', and the print statement
indented under the else clause will get executed when it is not.
if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Each statement inside the if block of an if else statement is executed in order if the
boolean expression evaluates to True. The entire block of statements is skipped if the
boolean expression evaluates to False, and instead all the statements under the else clause
are executed. There is no limit on the number of statements that can appear under the two
clauses of an if else statement, but there has to be at least one statement in each block.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Sometimes 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:
if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C
elif is an abbreviation of else if. Again, exactly one branch will be executed. There is
no limit of the number of elif statements but only a single (and optional) final else
statement is allowed and it must be the last branch in the statement:. Each condition is
checked in order. If the first is false, the next is checked, and so on. If one of them is true,
the corresponding branch executes, and the statement ends. Even if more than one condition
is true, only the first true branch executes.
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
elif choice == 'c':
print("You chose 'c'.")
else:
print("Invalid choice.")
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Nested conditionals:
One conditional can also be nested within another. The outer conditional contains two
branches. The second branch contains another if statement, which has two branches of its
own. Those two branches could contain conditional statements as well. Although the
indentation of the statements makes the structure apparent, nested conditionals very quickly
become difficult to read. In general, it is a good idea to avoid them when you can.Logical
operators often provide a way to simplify nested conditional statements. For example, we
can rewrite the following code using a single conditional:
if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C
randomList = ['a', 0, 2]
In this program, we loop until the user enters an integer that has a valid reciprocal. The
portion that can cause exception is placed inside try block.
If no exception occurs, except block is skipped and normal flow continues. But if any
exception occurs, it is caught by the except block.
Here, we print the name of the exception using ex_info() function inside sys module and
ask the user to try again. We can see that the values 'a’ causes ValueError and '0' causes
ZeroDivisionError.
First try clause is executed i.e. the code between try and except clause.
If there is no exception, then only try clause will run, except clause is finished.
If any exception occured, try clause will be skipped and except clause will run.
If any exception occurs, but the except clause within the code doesn’t handle it, it
is passed on to the outer try statements. If the exception left unhandled, then the
execution stops.
A try statement can have more than one except clause
A try statement may have more than one except clause for different exceptions. But at
most one except clause will be executed.
Our next example shows a try clause, in which we open a file for reading, read a line from
this file and convert this line into an integer. There are at least two possible exceptions:
an IOError
ValueError
Just in case we have an additional unnamed except clause for an unexpected error:
import sys
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except IOError as e:
errno, strerror = e.args
print("I/O error({0}): {1}".format(errno,strerror))
# e can be printed directly without using .args:
# print(e)
except ValueError:
print("No valid integer in line.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
An except clause may name more than one exception in a tuple of error names, as we see in the
following example:
try:
f = open('integers.txt')
s = f.readline()
i = int(s.strip())
except (IOError, ValueError):
print("An I/O error or a ValueError occurred")
except:
print("An unexpected error occurred")
raise
Raising Exceptions
In Python programming, exceptions are raised when corresponding errors occur at run
time, but we can forcefully raise it using the keyword raise.
We can also optionally pass in value to the exception to clarify why that exception was
raised.
raise KeyboardInterrupt
raise MemoryError("This is an argument")
try:
a = int(input("Enter a positive integer: "))
if a <= 0:
raise ValueError("That is not a positive number!")
except ValueError as ve:
print(ve)
try:
f = open("test.txt",encoding = 'utf-8')
# perform file operations
finally:
f.close()
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Syntax of Function:
def function_name(parameters):
"""docstring"""
statement(s)
Example of a function:
def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
Docstring:
The first string after the function header is called the docstring and is short for documentation
string. It is used to explain in brief, what a function does. Although optional, documentation
is a good programming practice. Unless you can remember what you had for dinner last
week, always document your code. In the above example, we have a docstring immediately
below the function header. We generally use triple quotes so that docstring can extend up to
multiple lines. This string is available to us as __doc__ attribute of the function. For
example: Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
# This function greets to the person passed into the name parameter
def absolute_value(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num
# Output: 2
print(absolute_value(2))
# Output: 4
print(absolute_value(-4))
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Types of Functions
Basically, we can divide functions into the following two types:
Functions that readily come with Python are called built-in functions. If we use functions
written by others in the form of library, it can be termed as library functions. All the other
functions that we write on our own fall under user-defined functions. So, our user-defined
function could be a library function to someone else.
Python Built-in Function: The Python interpreter has a number of functions that are always
available for use. These functions are called built-in functions. For example, print() function
prints the given object to the standard output device (screen) or to the text stream file. In
Python 3.6 (latest version), there are 68 built-in functions. They are listed below
alphabetically along with brief description.
University Questions
Q1 Explain the following: i) Skills necessary for a programmer ii) Interactive Mode iii)
Short Circuit Evaluation of Expression
Q2 Mention the three types of errors encountered during programming. Explain the basic
building block of python
Q3 Describe Python language support for arithmetic operators.
Q4 List and give syntax of all python supported conditional statements along with usage and
example.
Q5 Differentiate between argument and parameter, illustrate the flow of execution of a
python function with an example program.
Q6 List any five features of python programming Language.
Q7 What is the role of a programmer ? List two skills required to be a programmer.
Q8 Explain chained and nested conditional execution statements along with syntax and flow
chart
Q9 what are python words and sentences? Explain with an example for each.
Q10 Differentiate between a complier and an interpreter ?
Q11. Explain Modular Operator and in python
Q12 List the rules to declare a variable in python. Demonstrate at least three different types
of variable uses with an example program.
Q13 Explain the rules of precedence used by python to evaluate an expression
Q14 How dose python handles exceptions? Explain with an example.
Q15 Explain the concept of short circuit evaluation of logical expression in python.
Q16 Explain in detail the building blocks of a program. State the need for functions in python
Q17 Explain break and continue statements with examples in python. Write Pythonic code
that iteratively prompts the user for input. It should continue until the user enters “done” and
then return the average value.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
Excise Programs :
P1. Write a python program to check whether a number is prime or not using while loop
and print appropriate messages.
P2. Write a function called “palindrome” that takes a string argument and returns True if it
is a palindrome and false otherwise. Use built-in function to check the length of a string.
Prompt the user for the input.
P3. Write a program to prompt the user for a score between 0.0 and 1.0. if the score is out
of range print an error. If the score is between 0.0 and 1.0, print a grade using the following
table
Score >=0.9 >=0.8 >=0.7 >=0.6 <0.6
Grade A B C D F
P4. With an example program calculate 𝐹𝑛 = 22𝑛 + 1 where vaule of n is provided by the
user on prompt
P5. Predict the out put and justify your answer i) -11%9 (ii) 7.7//7 (iii) (200-70)*10/5
(iv) not “false” (v) 5*1**2
P6. Write a python code to convert given Celsius to Fahrenheit.
P7. Write a python code to calculate student result based on 2 exam, 1 sport and 2 activities
conducted in a college with weightage of 20% for sports and 20% for activities for 50 marks.
P8. Write python programs to i) Find largest of three numbers ii) Check whether the given
year is leap or not with function
P9. Write a single user defined function named “Solve” that returns the remainder and
Quotient on division of two numbers accepted from the user. Print the Remainder and
Quotient separately on the console.
P10. Write a python program to find the best of the two test average out of three test marks
accepted from the user.
P11. Write a python code to check whether a given number is +ve, –ve or zero.
P12. Use try and except so that your program handles non-numeric input gracefully by
printing a message and exits the program
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
P1. Predict the out put and justify your answer i) -11%9 (ii) 7.7//7 (iii) (200-70)*10/5
(iv) not “false” (v) 5*1**2
To understand this example, you should have the knowledge of the following Python
programming topics:
Basic Python operators
Operator Precedence
print(-11%9) # r = n % a; if (r > 0) r += a;
print(7.7//7)
print((200-70)*10/5)
print(not False)
print(5*1**2)
7
1.0
260.0
True
5
P4. Write a python program to find the best of the two test average out of three test
marks accepted from the user
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
To understand this example, you should have the knowledge of the following Python
programming topics:
Python Data Types
Python Input, Output
Python Operators
P5 Write a python code to Check whether the given year is leap or not with function
To understand this example, you should have the knowledge of the following Python
programming topics:
Python Operators
Python if...else Statement
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
P6. Write a python program to check whether a number is prime or not using while
loop and print appropriate messages.
To understand this example, you should have the knowledge of the following Python
programming topics:
Python if...else Statement
Python for Loop
Python break and continue
Proper indentation
digging deep enough, it’s also possible to relate the completion clause
The while loops and The if statements are the boolean value of an expression, Whereas
The try statement and The for loops statements are checking whether or not a section of
code was aborted before completing normally
In Python the for loop and while loop also have an else clause which most of us are
unfamiliar with. The else clause executes after the loop completes normally. This means that
the loop did not encounter a break statement inside the loop.
The common construct is to run a loop and search for an item. If the item is found, we break
out of the loop using the break statement. There are two scenarios in which the loop may
end. The first one is when the item is found and break is encountered. The second scenario
is that the loop ends without encountering a break statement. Now we may want to know
which one of these is the reason for a loop’s completion. One method is to set a flag and then
check it once the loop ends. Another is to use the else clause.
P7. Write a function called “palindrome” that takes a string argument and returns
True if it is a palindrome and false otherwise. Use built-in function to check the
length of a string. Prompt the user for the input.
To understand this example, you should have the knowledge of the following Python
programming topics:
Python if...else Statement
Python Strings
Python String Methods
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
P8. Write a program to prompt the user for a score between 0.0 and 1.0. if the score
is out of range print an error. If the score is between 0.0 and 1.0, print a grade using
the following table
Score >=0.9 >=0.8 >=0.7 >=0.6 <0.6
Grade A B C D F
To understand this example, you should have the knowledge of the following Python
programming topics:
Python Operators
Python if...else Statement
# initialize sum
sum = 0
P10. Use try and except so that your program handles non-numeric input gracefully
by printing a message and exits the program
To understand this example, you should have the knowledge of the following Python
programming topics:
Python try - except Statement
Python operators
Python if else Statement
h = input('Enter Hours:')
r = input('Enter Rate:')
try:
hours = float(h)
rate = float (r)
if hours <= 40:
pay = hours * rate
else:
pay = ((hours - 40) * (1.5 * rate)) + (40 * rate)
print ('Pay ='), pay
except:
print('Error, please enter numeric input')
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College
P11. Program for Sum of the digits of a given number using function
To understand this example, you should have the knowledge of the following Python
programming topics:
Python Operators
Python function
While loop
def getSum(n):
sum = 0
# Single line that calculates sum
while(n > 0):
sum += int(n%10)
n = int(n/10)
return sum
# Driver code
n = 687
print(getSum(n))
P13. Write python programs to Find largest of three numbers using a function
To understand this example, you should have the knowledge of the following Python
programming topics:
Python if...else Statement
Python Function Definition, Function Call, Argument passing
num1 = 10
num2 = 44
num3 = 12
def Largest(num1,num2,num3):
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
Largest(num1,num2,num3)
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
bubbleSort(arr)
avg=0
for i in range(Num_A):
avg+=arr[i]
print("Average of {} tests is {}".format(Num_A,avg/Num_A))