0% found this document useful (0 votes)
34 views

Q1 Why Should You Learn To Write Programs ?

Uploaded by

T R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views

Q1 Why Should You Learn To Write Programs ?

Uploaded by

T R
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

PAP 15cs664: Prepared By G.V. Bhat, Prof.

Dept of ECE, Canara Engineering College

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?

Q1 Why should you learn to write programs ?


Coding develops structured and creative thinking
When programmers are given a problem to solve, they don't just start to code right away.
Problems are not solved that way. When you see a problem, you need to break it down into
workable pieces and then get on it. Do non-programmers ever approach to a problem like
this? Rare! When you start learning to program, you develop the habit of working your way
out in a very structured format. You gradually program your brain to break every problem
down to bits and understand better. You start thinking logically, and this gives rise to more
creative solutions you've ever given.
Programming will certainly and will drastically improve you way of thinking. Programming
will enhance ones logical and reasoning ability. Therefore, if you have interest in
Mathematics, Reasoning, Logic, Problem solving then programming is here to be with you.

Programming makes things easier for you


A simple computer program is capable of turning things around as you want. Something that
works on pushing buttons can be programmed to do so on a tap on your smartphone or when
you double clap. Yeah, you can switch on/off your electrical appliances using your
smartphones. Something that requires your input repeatedly, just like the online forms where
you have to fill your First Name, Second Name, Email and other information, can be
programmed to have your opinion once and it could literally fill out your forms with a single
click. Yes, it’s possible. Something as simple as working on Excel Sheets can make you go
crazy because of the manual labor it requires.

Learning to program teaches you persistence


When you learn computer programming, you start seeing problems in the light of solutions.
Your brain starts functioning like that. When you encounter a problem after learning to
program, you start envisioning the possible ways to solve it. You may even foresee some
good results out of it. However hard the problem might seem, you become determined to act
on it anyhow. You transform yourself into a solution-driven individual.

Learning to program for career growth


Now lets talk about the market, you might also be interested to know that the most paid jobs
of today's world is in Computer Science field. And to be in the computer science field you
should and must have knowledge of programming.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

Q2 Why Learn python? (Python & It’s Features)


Python is an open source scripting language, created by Guido van Rossum in 1989. It is an
interpreted language with dynamic semantics and is very easy to learn. Some cool features
and applications of Python include.

Features Applications

It is also used for automation and for performing a lot of other tasks.

Q3 What are the Skills necessary for a programmer


A programmer must have skills to look at the data/information available about a problem,
analyze it and then to build a program to solve the problem. The skills to be possessed by a
good programmer includes –
Thorough knowledge of programming language: One needs to know the vocabulary
and grammar (technically known as syntax) of the programming language. This will help
in constructing proper instructions in the program.
Skill of implementing an idea: A programmer should be like a ‘story teller’. That is, he
must be capable of conveying something effectively. He/she must be able to solve the
problem by designing suitable algorithm and implementing it. And, the program must
provide appropriate output as expected.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

Q4 Explain the Computer Hardware Architecture


The Central Processing Unit (or CPU) is the part of the computer that is built to be
obsessed with “what is next?” If your computer is rated at 3.0 Gigahertz, it means that
the CPU will ask “What next?” three billion times per second. You are going to have to
learn how to talk fast to keep up with the CPU.
The Main Memory is used to
store information that the CPU
needs in a hurry. The main
memory is nearly as fast as the
CPU. But the information stored
in the main memory vanishes
when the computer is turned off.
The Secondary Memory is also
used to store information, but it is
much slower than the main
memory. The advantage of the
secondary memory is that it can
store information even when there is no power to the computer. Examples of
secondary memory are disk drives or flash memory (typically found in USB sticks
and portable music players).
The Input and Output Devices are simply our screen, keyboard, mouse, microphone,
speaker, touchpad, etc. They are all of the ways we interact with the computer.
Network: These days, most computers also have a Network Connection to retrieve
information over a network. We can think of the network as a very slow place to store and
retrieve data that might not always be “up”. So in a sense, the network is a slower and at
times unreliable form of Secondary Memory. While most of the detail of how these
components work is best left to computer builders, it helps to have some terminology so we
can talk about these different parts as we write our programs.

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

Q6 what are the Basic Building Blocks of a Programming


Language
input Get data from the “outside world”. This might be reading data from a file, or
even some kind of sensor like a microphone or GPS. In our initial programs, our
input will come from the user typing data on the keyboard.
output Display the results of the program on a screen or store them in a file or
perhaps write them to a device like a speaker to play music or speak text.
sequential execution Perform statements one after another in the order they are
encountered in the script.
conditional execution Check for certain conditions and then execute or skip a
sequence of statements.
repeated execution Perform some set of statements repeatedly, usually with some
variation.
reuse Write a set of instructions once and give them a name and then reuse those
instructions as needed throughout your program.

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:

Programs Statements Expressions Operands and Operators

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

Q8 differentiate between a compiler and an interpreter


The basic difference is that a compiler system, including a (built-in or separate) linker,
generates a stand-alone machine code program, while an interpreter system instead
performs the actions described by the high-level program.
Compiler takes the entire program as input, where interpreter takes single instruction as
input.
Interpreter translates program one statement at a time. But compiler scans the entire
program and translates it as a whole into machine code.
Compiler process consumes more memory than interpreter.
In case of Python, the programs are first compiled into an intermediate form (byte code),
then interpreted by the interpreter.
Compiled programs generally run faster than interpreted programs.
The program need not be compiled every time. in interpreter, every time higher level
program is converted into lower level program.
Errors are displayed after the entire compiled program is checked, where errors are
displayed for every instruction interpreted.
But compiler is a time-consuming process, where interpreter can immediately execute
high-level programs.
Every high-level programming language comes with a compiler. However, BASIC and
LISP are specially designed to be executed by an interpreter.

Q9 what are Words and Sentences


Every programming language has its own constructs to form syntax of the language. Basic
constructs of a programming language includes set of characters and keywords that it
supports. The keywords have special meaning in any language and they are intended for
doing specific task. Python has a finite set of keywords as given below

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

Q10 Explain Variables In Python:


Variables are nothing but reserved memory locations to store values. This means that when
you create a variable you reserve some space in memory. In Python you don’t need to declare
variables before using it, unlike other languages like Java, C etc., i.e. Python variables do
not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables.
Example: S = 10; print(S). This will assign value ‘10’ to the variable ‘S’ and will print
it. Try it yourself.

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)

Q11 What are the general Variable Naming Rules in


Python?
You should be aware of certain rules when naming your variables. They are:

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.

Q12 What is actually happening when you make a


variable assignment?

This is an important question; It is also called as Object Reference in Python,


because the answer differs somewhat from what you’d find in many other
programming languages. Python is a highly object-oriented language. In fact,
virtually every item of data in a Python program is an object of a specific type or
class. (This point will be reiterated many times over the course.

Q13 What is scope and Variable scopes?


Scope of a variable is a context in the program in which variable name is valid and can be
referred to. Variable scope is also known as variable visibility. In Python, variables can
have either have local or global scope.
m = 30 # global variable
def f1(x):
n = 2 # local variable
x = n * x
print(x)
f1(m)
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

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)

Q14 What are the different Python Operators ?


Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

Arithmetic operators in Python


Operator Meaning Example
x+y
+ Add two operands or unary plus
+2
x-y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
Modulus - remainder of the division of left operand by the x % y (remainder of
%
right x/y)
Floor division - division that results into whole number
// x // y
adjusted to the left in the number line
Exponent - left operand raised to the power of right
**
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

Comparision operators in Python


Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than or equal
>= x >= y
to the right
Less than or equal to - True if left operand is less than or equal to the
<= right

Logical operators in Python


Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not x
not True if operand is false (complements the operand)

Bitwise operators in Python


Operator Meaning Example
x& y = 0 (0000
& Bitwise AND
0000)
x | y = 14 (0000
| Bitwise OR
1110)
~x = -11 (1111
~ Bitwise NOT
0101)
x ^ y = 14 (0000
^ Bitwise XOR
1110)
x>> 2 = 2 (0000
>> Bitwise right shift
0010)
x<< 2 = 40
<< Bitwise left shift (0010 1000)

Assignment operators in Python


Operator Example Equivatent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

Q15 What are Expressions, Statements Operators and


Operands
Statement: A statement is an instruction that the Python interpreter can execute. We have
seen two kinds of statements: print and assignment. When you type a statement on the
command line, Python executes it and displays the result, if there is one. The result of a print
statement is a value. Assignment statements don't produce a result. A script usually contains
a sequence of statements. If there is more than one statement, the results appear one at a time
as the statements execute.

Expression: An expression is a combination of values, variables, and operators. If you type


an expression on the command line, the interpreter evaluates it and displays the result.
Although expressions contain values, variables, and operators, not every expression contains
all of these elements. A value all by itself is considered an expression, and so is a variable.

“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.

Q16 What is the importance of Order of operations


When more than one operator appears in an expression, the order of evaluation depends on
the rules of precedence. For mathematical operators, Python follows mathematical
convention. The acronym PEMDAS is a useful way to remember the rules:

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

Q17 Mention the three types of errors encountered during


programming
Syntax errors
These are the first errors you will make and the easiest to fix.
A syntax error means that you have violated the “grammar” rules of Python.
Python does its best to point right at the line and character where it noticed it was
confused.
The only tricky bit of syntax errors is that sometimes the mistake that needs fixing
is actually earlier in the program than where Python noticed it was confused.
So the line and character that Python indicates in a syntax error may just be a
starting point for your investigation.

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

Q18 What is Short-Circuit Evaluation of Logical


Expressions explain with example

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

Traceback (most recent call last):


File "<pyshell#3>", line 1, in <module>
x>=2 and (x/y)>2
ZeroDivisionError: division by zero

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.

Q19 what are the Conditional-Execution / Decision Making


options available in python ?
The if statement: In order to write useful programs, we almost always need the ability to
check conditions and change the behaviour of the program accordingly. Conditional
statements give us this ability. The simplest form is the if statement, which has the general
form:

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 + '! '))

A few important things to note about if statements:


1. The colon (:) is significant and required. It separates the header of the compound
statement from the body.
2. The line after the colon must be indented. It is standard in Python to use four spaces for
indenting.
3. All lines indented the same amount after the colon will be executed whenever the
BOOLEAN_EXPRESSION is true.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

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.

The syntax for an if else statement looks like this:

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

Q20 Explain chained and nested conditional execution


statements along with syntax and flow chart?
Chained conditionals:

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

if 0 < x: # assume x is an int here


if x < 10:
print("x is a positive single digit.")

Q21 What are exceptions in Python? How dose python


handles exceptions? Explain with an example.

Python Exception Handling - Try, Except and Finally


Python has many built-in exceptions which forces your program to output an error when
something in it goes wrong. When these exceptions occur, it causes the current process to
stop and passes it to the calling process until it is handled. If not handled, our program will
crash.
For example, if function A calls function B which in turn calls function C and an exception
occurs in function C. If it is not handled in C, the exception passes to B and then to A.
If never handled, an error message is spit out and our program come to a sudden, unexpected
halt.

Catching Exceptions in Python


In Python, exceptions can be handled using a try statement. A critical operation which can
raise exception is placed inside the try clause and the code that handles exception is written
in except clause. It is up to us, what operations we perform once we have caught the
exception. Here is a simple example.

# import module sys to get the type of exception


import sys
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

randomList = ['a', 0, 2]

for entry in randomList:


try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!",sys.exc_info()[0],"occured.")
print("Next entry.")
print()
print("The reciprocal of",entry,"is",r)

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.

Catching Specific Exceptions in Python


In the above example, we did not mention any exception in the except clause.
This is not a good programming practice as it will catch all exceptions and handle every case
in the same way. We can specify which exceptions an except clause will catch.
A try clause can have any number of except clause to handle them differently but only one
will be executed in case an exception occurs.
We can use a tuple of values to specify multiple exceptions in an except clause. Here is an
example pseudo code.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

How try() works?

 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

while n < 1000:


try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")

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)

Defining Clean-up Actions: try...finally


The try statement in Python can have an optional finally clause. This clause is executed
no matter what, and is generally used to release external resources.
For example, we may be connected to a remote data center through the network or working
with a file or working with a Graphical User Interface (GUI).
In all these circumstances, we must clean up the resource once used, whether it was
successful or not. These actions (closing a file, GUI or disconnecting from network) are
performed in the finally clause to guarantee execution.

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

Q22 what are Functions


In Python, function is a group of related statements that perform a specific task. Functions help
break our program into smaller and modular chunks. As our program grows larger and larger,
functions make it more organized and manageable. Furthermore, it avoids repetition and makes
code reusable.

Syntax of Function:
def function_name(parameters):
"""docstring"""
statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

Example of a function:

def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")

How to call a function in python?


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. >>> greet('Paul')

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

The return statement:


The return statement is used to exit a function and go back to the place from where it was
called. Syntax of return: return [expression_list]
This statement can contain expression which gets evaluated and the value is returned. If
there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object. For example:
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value.
Example of return

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:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.

User-defined functions in Python: Functions that we define ourselves to do certain specific


task are referred as user-defined functions. The way in which we define and call functions
in Python are already discussed.

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.

Advantages of user-defined functions

3. User-defined functions help to decompose a large program into small segments,


which makes program easy to understand, maintain and debug.
4. If repeated code occurs in a program. Function are used to include those codes
and execute when needed by calling that function.
5. Programmers working on large project can divide the workload by making
different functions.

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.

Differentiate between argument and parameter, illustrate with an


example program

Parameter is variable defined in function definition, while argument is actual value


passed to the function. To understand the difference, let’s first see an example function and
its usage:

fun randomString(length: Int): String {


// ....
}randomString(10)

in this example length is a parameter, and 10 (used in function call) is an argument.


Here are common definitions: Parameter is variable defined in function declaration.
Argument is the actual value of this variable that get passed to the function.
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

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

P2. With an example program calculate 𝑭𝒏 = 𝟐𝟐𝒏 + 𝟏 where vaule of n is provided


by the user on prompt
To understand this example, you should have the knowledge of the following Python
programming topics:
 Basic Python operators
 Operator Precedence
n = int(input("enter the n value"))
fn= ((2)**(2*n))+1
print (fn)

P3. Write a python code to convert given Celsius to Fahrenheit.


To understand this example, you should have the knowledge of the following Python
programming topics:
 Python Data Types
 Python Input, Output and Import
 Python Operators

# input the value in celsius


celsius = float(input('enter the tmp in Celsius: '))
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree
Fahrenheit'%(celsius,fahrenheit))

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

inp = input("Enter marks separated by space ")


marks = inp.split()

avg1 = ( int(marks[0]) + int(marks[1]) )/2


avg2 = ( int(marks[1]) +int(marks[2]) )/2
avg3 = ( int(marks[0]) + int(marks[2]) )/2

print (max(avg1, avg2, avg3))

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

# To get year (integer input) from the user


year = int(input("Enter a year: "))

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

# To take input from the user


num = int(input("Enter a number: "))

# prime numbers are greater than 1


if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")

# if input number is less than


# or equal to 1, it is not prime
else:
print(num,"is not a prime number")

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

# Program to check if a string is palindrome or not


my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

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

score =float(input("enter a score:"))


s = float(score)
if 0.0 <= s <= 1.0:
if s >= 0.9:
result = "A"
print (result)
elif 0.8 <= s < 0.9:
result = "B"
print (result)
elif 0.7 <= s < 0.8:
result = "C"
print (result)
elif 0.6 <= s < 0.7:
result = "D"
print (result)
else:
result = "F"
print (result)
else:
print ("Error: score out of range")
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

P9 Write a Python Program to Check if a given three-digit number is an Armstrong


Number
To understand this example, you should have the knowledge of the following Python
programming topics:
 Python Operators
 Python if...else Statement
 While loop

# take input from the user


num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

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))

P12. Write a python code to find Factorial of a Number using Recursion


To understand this example, you should have the knowledge of the following Python
programming topics:
 Python if...else Statement
 Python Functions
 Python Recursion
# Factorial of a number using recursion
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))
PAP 15cs664: Prepared By G.V. Bhat, Prof. Dept of ECE, Canara Engineering College

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

print("The largest number is", largest)

Largest(num1,num2,num3)

P14. Write python programs to for bubble sort

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):

# traverse the array from 0 to n-i-1


# Swap if the element found is greater
# than the next element
if arr[j] < arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]

Num_T = int(input('enter the number of tests'))


Num_A = int (input('enter the number of tests for avrege'))
arr=[]
for i in range(Num_T):
arr.append(float(input("enter the {} test marks".format(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))

You might also like