[go: up one dir, main page]

0% found this document useful (0 votes)
4 views32 pages

PAP_module-1

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views32 pages

PAP_module-1

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

Page 1

Module-1 PAP 18EC643


Q1. What are the salient features of python? (5Marks)
1. Easy to Code and learn
Python is a very high-level programming language, easy to learn. However, learning the
basic Python syntax is very easy, as compared to other popular languages like C, C++, and
Java.
2. Easy to Read (Expressive language)
Python code looks like simple English words. There is no use of semicolons or brackets, and
the indentations define the code block. More readable and understandable.
3. Free and Open-Source
Python is developed under an OSI-approved open-source license. Hence, it is completely free
to use, even for commercial purposes. It doesn't cost anything to download Python or to
include it in your application.
4. Robust Standard Library
Python has an extensive standard library available to use. This means that programmers don’t
have to write their code for every single thing unlike other programming languages. There
are libraries for image manipulation, databases, unit-testing, expressions and a lot of other
functionalities.
5. Interpreted language
When a programming language is interpreted, it means that the source code is executed line
by line, and not all at once. Programming languages such as C++ or Java are not interpreted,
and hence need to be compiled first to run them. There is no need to compile Python because
it is processed at runtime by the interpreter.
6. Portable (cross platform language)
Python is portable in the sense that the same code can be used on different machines. Python
program can be run on Windows or Linux.
7. Object-Oriented and Procedure-Oriented
A programming language is object-oriented if it focuses design around data and objects,
rather than functions and logic. On the contrary, a programming language is procedure-
oriented if it focuses more on functions (code that can be reused). One of the critical Python
features is that it supports both object-oriented and procedure-oriented programming.
8. Extensible
A programming language is said to be extensible if it can be extended to other languages.
Python code can also be written in other languages like C++, making it a highly extensible
language.
9. Expressive
Python needs to use only a few lines of code to perform complex tasks. For example, to
display Hello World, you simply need to type one line - print(“Hello World”). Other
languages like Java or C would take up multiple lines to execute this.
10. Support for GUI
One of the key aspects of any programming language is support for GUI or Graphical User
Interface. A user can easily interact with the software using a GUI.
11. Dynamically Typed
Many programming languages need to declare the type of the variable before runtime. With
Python, the type of the variable can be decided during runtime. This makes Python a
dynamically typed language.
Q2. Explain computer hardware and architecture with neat diagram. (6Marks)

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 2

1. The Central Processing Unit (or CPU)


A CPU is responsible for handling the processing of logical and mathematical operations and
executing instructions that it is given

2. The Secondary Memory


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

3. Input and Output devices


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.

4. Computer Networks
Computer networking refers to interconnected computing devices that can exchange da and
share resources with each other.

Q3. Explain the Skills necessary for programmer (5marks)


First, you need to know the programming language (Python) - you need to know the vocabulary
and the grammar. You need to be able to spell the words in this new language properly and
know how to construct well-formed “sentences” in this new language.
Second, you need to “tell a story”. In writing a story, you combine words and sentences to
convey an idea to the reader. There is a skill and art in constructing the story, and skill in story
writing is improved by doing some writing and getting some feedback. In programming, our
program is the “story” and the problem you are trying to solve is the “idea”.
----------------------------------------------------------------------------------------------------------------
Q4. Explain the types of errors with examples. (6 marks)
Syntax errors
These are the first errors you will make and the easiest to fix. A syntax error means the
statements that have violated the “grammar” rules of Python.
Python point right at the line and character where it noticed it was confused.
Example:
# initialize the amount variable
amount = 100
# check that if amount greater than 2999
if(amount>2999)
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 3

print("amount is greater than 2999")


output: if(amount>2999)
^
SyntaxError: invalid syntax

Logic errors
A logic error is when the 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. The order of the
statement is not proper.
Example:
# initialize the marks variable
marks = 10000
# perform division with 0
a = marks / 0
print(a)
output: ZeroDivisionError: division by zero

Semantic errors
A semantic error when the program 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.
Example:
num1 = input('Enter a number:')
num2 = input('Enter another number:')
sum = num1 + num2
print('The sum of', num1, 'and', num2, 'is', sum)

output: Enter a number 4


Enter another number 5
'The sum of', 4, 'and', 5, 'is', 45

The program contains a semantic error. The error is that the program performs concatenation
instead of addition, because the programmer failed to write the code necessary to convert the
inputs to integers.
Q5. Define high level language and machine language. List out the differences between
Compiler and Interpreter. (8/6 marks)
High-level language A programming language like Python that is designed to be easy for
humans to read and write.

1. Compiler:
It is a translator which takes input i.e., High-Level Language, and produces an output of low-
level language i.e., machine or assembly language.
A compiler is more intelligent than an assembler it checks all kinds of limits, ranges, errors,
etc.
But its program run time is more and occupies a larger part of memory. It has a slow speed
because a compiler goes through the entire program and then translates the entire program into
machine codes.

Fig1. Compiler process


Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 4

2. Interpreter:
An interpreter is a program that translates a programming language into a comprehensible
language. –
It translates only one statement of the program at a time.
Interpreters, more often than not are smaller than compilers.

Fig2. Interpreter process

Sl.no Compiler Interpreter

The compiler scans the whole Translates the program one statement at a
1. program in one go. time.

As it scans the code in one go, the


errors (if any) are shown at the end Considering it scans code one line at a
2. together. time, errors are shown line by line.

Due to interpreters being slow in


The main advantage of compilers is executing the object code, it is preferred
3. its execution time. less.

It converts the source code into object It does not convert source code into object
4. code. code instead it scans it line by line

It does not require source code for


5 later execution. It requires source code for later execution.

Execution of the program takes place


only after the whole program is Execution of the program happens after
6 compiled. every line is checked or evaluated.

The machine code is stored in the disk


7 storage. Machine code is nowhere stored.

Compilers more often take a large


amount of time for analysing the In comparison, Interpreters take less time
8 source code. for analysing the source code.

9. It is more efficient. It is less efficient.

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 5

Sl.no Compiler Interpreter

10. CPU utilization is more. CPU utilization is less.

Any change in source program after Any change in source program during the
the compilation requires recompiling translation does not require’s retranslation
11. of entire code. of entire code.

Compiler Takes Entire program as Interpreter Takes Single instruction as


12. input input.

Object code is permanently saved for


13. future use. No object code is saved for future use.

Python, Ruby, Perl, SNOBOL, MATLAB,


C, C++, C#, etc are programming etc are programming languages that are
Eg. languages that are compiler-based. interpreter-based.

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 6

Chapter-1 Python Basics


Q1. Explain keywords, variable names with rules, operators, operands and order of
operations in python with examples. (8marks)
Rules for Python Variable Names
1. A variable name can be only one word.
2. A variable name must start with a letter or the underscore character A variable name
cannot start with a number
3. A variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _)
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
Keywords
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers
Python reserves 33 keywords:

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

import keyword
# printing all keywords at once using "kwlist()"
print ("The list of keywords is : ")
print(keyword.kwlist)

Operators and operands


Operators are used to perform operations on variables and values. The values the operator is
applied to are called operands.

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 7

Operator Description Syntax

** Power: Returns first raised to power second x ** y

Modulus: returns the remainder when the first operand is


% x%y
divided by the second

// Division (floor): divides the first operand by the second x // y

/ Division (float): divides the first operand by the second x/y

* Multiplication: multiplies two operands x*y

– Subtraction: subtracts two operands x–y

+ Addition: adds two operands x+y

The floor() function(//):


floor () method in Python returns the floor of x i.e., the largest integer not greater than
x.
Example
>>x=17
>>x//2
>>8
Order of Operations
Order of operations means if an arithmetic expression is given that contains many operators
such as multiplication, addition division, the calculation is done in a certain order which is
given by PEMDMSA.
P: Parentheses
E: Exponentiation
M: Modulus
D: Division
M: Multiplication
S: Subtraction
A: Addition

Problems
Ex1: Solve 2+7×8-5
Solution: 53
Ex2: Find the value of the expression: (8 × 6 – 7) + 65
Solution: 106
Ex3: Evaluate 8/4 × 6/3 × 7 + 8 – (70/5 – 6)
Solution:
Evaluate 8/ 4 × 6/3 × 7 + 8 – (70/5 – 6 )
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 8

We can rewrite the expression as


(8/4 × 6/3 × 7 + 8) – (70/5 – 6)
Now we will solve the respective brackets,
(2 × 2 × 7 + 8) – (14 – 6)
(4 × 7 + 8) – (8)
(28 + 8) – (8)
(36) – (8)
28
Ex4:
Evaluate 16 - 2 * 5 // 3 + 1
16 - 2 * 5 // 3 + 1
16 - 10 // 3 + 1
16 - 3 + 1
13 + 1
14

Ex5:
Evaluate 2 ** 2 ** 3 * 3
2 ** 2 ** 3 * 3
2 ** 8 * 3
256 * 3
768
Q2. Explain the built-in data types in python with example. (6 marks)
Data type Examples
Integers -2, -1, 0, 1, 2, 3, 4, 5
Floating-point numbers -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Q3. Explain String concatenation and replication with example. (4 marks)


1. The ‘+ ‘is used on two string values, it joins the strings as the string concatenation
operator.
Example
x=’Alice’
y=’Bob’
print(x+y)
output: AliceBob
2. The * operator is used on one string value and one integer value; it becomes the string
replication operator.
Example:
x=’Alice’
print(x * 5)
output: AliceAliceAliceAliceAlice

Q4. Explain string concatenation and replication


String Concatenation
String concatenation means add strings together. The + operator is used to add a variable to
another variable:
Example

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 9

x = "Python is "
y = "awesome"
z= x+y
print(z)
output: HelloWorld

String Replication
The * operator is used for string multiplication. But when the * operator is used on one string
value and one integer value, it becomes the string replication operator.
Example
st='Alice'
print(st*3)
output: AliceAliceAlice

Q5. Explain different data types used in python. (3 marks)


The most common data types in Python are listed in Table
Data type Examples
1 Integers -2, -1, 0, 1, 2, 3, 4, 5
2 Floating-point -1.25, -1.0, --0.5, 0.0, 0.5, 1.0, 1.25
numbers
3 Strings 'a', 'aa', 'aaa', 'Hello!', '11 cats'

Q6. Explain variable names, keywords and expressions with examples (6marks)
An expression is a combination of operators and operands that is interpreted to produce some
other value. In any programming language, an expression is evaluated as per the precedence
of its operators.
Examples:
# Constant Expressions
x = 15 + 1.3

# Arithmetic Expression
x = 40
y = 12
A=x + y

# Logical Expressions
P = (10 == 9)
Q = (7 > 5)
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)

Output
False
True
True
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 10

Q7. Explain Modulus Operator with example (2 Marks)


Basically, Python modulo operation is used to get the remainder of a division. The modulo
operator (%) is considered an arithmetic operation, along with +, –, /, *, **, //.
#program to print quotient and remainder
quotient = 7 // 3
print(quotient)
2
remainder = -7 % 3
=3*3-7
=2
print(remainder)
2
remainder = -11 % 9
=2*9-7
=11
print(remainder)
11
----------------------------------------------------------------------------------------------------------------
Q8. Explain comparison operators in python. (6 marks)
Comparison operators are used to compare two values:
Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Q9. Explain Boolean expressions in python. (4 marks)


A boolean expression is an expression that is either True or False. The following examples
use the operator ==, which compares two operands and produces True if they are equal and
False otherwise:
>>> 5 = = 5
True
>>> 5 = = 6
False
The and Operator’s Truth Table
Expression Evaluates to
True and True True
True and False False
False and True False
False and False False
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 11

The or Operator’s Truth Table


Expression Evaluates to
True and True True
True and False True
False and True True
False and False False

The not Operator’s Truth Table


Expression Evaluates to
False True
True False

Q10. Explain logical operators used in python. (4 marks)


Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is true not (x < 5 and x < 10)
----------------------------------------------------------------------------------------------------------------
Q11. Explain input output operators used in python. (4 marks)
----------------------------------------------------------------------------------------------------------------
1. print() Function
The print() function displays the string value inside the parentheses on the screen.
Example:
print('Hello world!')
print('What is your name?') # ask for their name
output: Hello world!
What is your name?

2. input() Function
The input() function waits for the user to type some text on the keyboard
and press enter.
Example:
myName = input('enter your name')
output: 'enter your name' Alice
----------------------------------------------------------------------------------------------------------------
Q12. Explain the concept of type conversion functions and math functions in python with
examples. (5 marks).
Type conversion functions
1. int (a, base): This function converts any data type to integer. ‘Base’ specifies the base
in which string is if the data type is a string.
2. float (): This function is used to convert any data type to a floating-point number.
3. str () : Used to convert integer into a string.
>>> int ('32')
32
>>> int ('Hello')
Value Error: invalid literal for int () with base 10: 'Hello'

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 12

int can convert floating-point values to integers, but it doesn’t round off


off the fraction part:

>>> int (3.99999)


3
>>> int (-2.3)
-2

float converts integers and strings to floating-point numbers:

>>> float (32)


32.0
>>> float ('3.14159')
3.14159

Finally, str converts its argument to a string:

>>> str (32)


'32'
>>> str (3.14159)
'3.14159'
Python has a set of built-in math functions, including an extensive math module, that allows to
perform mathematical tasks on numbers.
Q13. List and explain the syntax all Flow control statements with examples. (8marks)
or
List and give syntax all python supported conditional statements along with its usage with
an example program to check whether the given number is positive or negative or zero.
or
Explain the concept of conditional execution alternate execution and conditional
execution with examples.
Explain the nested conditional statement with example
i) if statement (conditional execution)

if x > 0 :
print('x is positive')
ii) if-else statement (alternative execution)

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 13

if x%2 = = 0 :
print('x is even')
else :
print('x is odd')
iii) if-elif-else ladder(chained conditionals)

if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
iv) Nested if else (nested Conditional statement)

if x = = y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 14

Q12. What is exception handling? How Exceptions are handled in Python? Write a
python program with exception handling code to solve divide-by-zero situation (6 marks).
Or
How Python handles Exceptions. Explain with programming Example.
Error in Python can be of two types i.e., Syntax errors and Exceptions. Syntax Errors are the
problems in a program due to which the program will stop the execution
Exceptions: Exceptions are raised when the program is syntactically correct, but the code
results in an error. This error does not stop the execution of the program; however, it changes
the normal flow of the program.
Common Python Exceptions
1) Type Error: occurs when the data type of objects in an operation is inappropriate.
Example:
X=” apple”
Y=10
Z=X+Y

2) Value Error: Python Value Error is raised when a function receives an argument of the
correct type but an inappropriate value.
Example:
>>import math
X=math.sqrt(-11)

3) AttributeError: occurs when an invalid attribute reference is made. This can happen if an
attribute or function not associated with a data type is referenced on it.
Example:
# Python program to demonstrate
# AttributeError
X = 10
# Raises an AttributeError
X.append(6)
# Python code to illustrate
# working of try and Exception
x=int (input (“enter the value of dividend”))
y=int (input (“enter the value of divisor”))
try:
# Floor Division : Gives only Fractional Part as Answer
result = x // y
print ("the quotient is :", result)
except:
print ("Sorry ! You are dividing by zero ")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

Q13. Explain the concept of short circuit evaluation of logical expression in python.
When Python is processing a logical expression such as x >= 2 and (x/y) > 2, it evaluates the
expression from left to right.

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 15

Because of the definition of and, if x is less than 2, the expression x >= 2 is False and so the
whole expression is False regardless of whether (x/y) > 2 evaluates to True or False.
When Python detects that there is nothing to be gained by evaluating the rest of a logical
expression, it stops its evaluation and does not do the computations in the rest of the logical
expression. When the evaluation of a logical expression stops because the overall value is
already known, it is called short-circuiting the evaluation.
>>> x = 6
>>> y = 2
>>> x >= 2 and (x/y) > 2
True
>>> x = 1
>>> y = 0
>>> x >= 2 and (x/y) > 2
False
>>> x = 6
>>> y = 0
>>> x >= 2 and (x/y) > 2
Iteration
>>> x = 0
>>> x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called
a decrement.
----------------------------------------------------------------------------------------------------------------
Q14: Explain while loop and for loop with example. (4marks)
The while statement
With the while loop we can execute a set of statements as long as a condition is true.
n=5
while n > 0:
print(n)
n=n-1
print('Blastoff!')
The flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at
the next statement.
3. If the condition is true, execute the body and then go back to step 1.

Q15. With syntax and example code, explain the working of definite loop in python. (5
marks)

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 16

for loop statement


A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
Example1:
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends:
print('Happy New Year:', friend)
print('Done!')
output:
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
Example 2:Loop through the letters in the word "banana":
for x in "banana":
print(x)

Output:

apple
cherry

Example 3: Using the range () function:

for x in range (6):


print(x)
output:
0
1
2
3
4
5

Example: Using the range:

for x in range(2, 6):


print(x)

output:
2
3
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 17

4
5
for x in range(2, 30, 5):
print(x)
output:
2
7
12
17
22
27 2------------

22
Q16: With syntax, explain the finite and infinite looping constructs in python. (4marks)

Finite loop Infinite loop


It iterates for a finite number of It continues iterating indefinitely.
iterations.
Example: Example:
n=0 while True:
while n<10: print('Infinite loop')
n = n +1
print('Finite loop')
There is an iteration variable(n), the There is no iteration variable, the
loop will repeat for finite number of loop will repeat forever,
iterations. resulting in an infinite loop.

Q3: Explain Break and Continue statement with an example in Python. (4 marks)
Mention the advantages of continue statement. Write a program to compute only even
number sum within the given natural number using continue statement. (8marks)

Break statement
• The break statement is used to terminate the loop or statement in which it is present.
• After that, the control will pass to the statements that are present after the break statement, if
available.
• If the break statement is present in the nested loop, then it terminates only those loops which
contains break statement.
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done! out of while loop’ )
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 18

output
> hello there
hello there
> finished
finished
> done
Done! out of while loop
The loop condition is True, which is always true, so the loop runs repeatedly until
it hits the break statement.
Continue statement
• Continue is also a loop control statement just like the break statement.
• continue statement is opposite to that of break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop.
• As the name suggests the continue statement forces the loop to continue or execute the next
iteration.
• When the continue statement is executed in the loop, the code inside the loop following the
continue statement will be skipped and the next iteration of the loop will begin.
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done! Out of while loop')
output
> hello there
hello there
> # don't print this
> print this!
print this!
> done
Done! Out of while loop

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 19

All the lines are printed except the one that starts with the hash(#) sign because when the
continue is executed, it ends the current iteration and jumps back to the while statement
to start the next iteration, thus skipping the print statement.

Basis for comparison Break Continue


It is used for the termination of
It is used for the termination of the
Use all the remaining iterations of
only current iteration of the loop.
the loop.
Control after using The line which is just after the The control will pass to the next
break/continue loop will gain control of the iteration of that current loop by
statement program. skipping the current iteration.
It performs the termination of It performs early execution of the next
Causes
the loop. loop by skipping the current one.
It stops the continuation of the It stops the execution of the current
Continuation
loop. iteration.
It can be used with labels and It can't be used with labels and
Other
switches. switches.

# Python Program to Calculate Sum of Even Numbers from 1 to N


N= int(input(" Please Enter the Value : "))
total = 0
for number in range (1, N+1):
if number % 2 == 0:
total = total + number
print(number)
print (‘The Sum of Even Numbers from 1 to N’, total))
output:
Please Enter the Value: 15
2
4
6
8
10
12
14
The Sum of Even Numbers from 1 to N = 56

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 20

Q17. Write a python program to read the numbers repeatedly until the user enters ‘done’.
Once ‘done is entered print out total, count and average of numbers (6 marks)

count = 0
tot = 0.0
while True:
number = input("Enter a number")
if number == 'done':
break
num1 = float(number)
count= count+1
tot = tot + num1
Avg=tot/count
print (tot,num,Avg)

Write a python program to create username and password. (8 marks)

while True:
print('Who are you?')
name = input()
if name != 'Joe':
continue
print('Hello, Joe. What is the password? (It is a fish.)')
password = input()
if password == 'swordfish':
break
print('Access granted.')
output: Who are you?
Joe
Hello, Joe. What is the password? (It is a fish.)
swordfish
Access granted.

importing modules

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 21

Python comes with a set of modules called the standard library. Each module is a Python
program that contains a related group of functions that can be embedded in your programs. For
example, the math module has mathematics- related functions, the random module has random
number–related functions, and so on.
Before the use of functions in a module, you must import the module with an import statement.
In code, an import statement consists of
the following:
• The import keyword
• The name of the module
• Optionally, more module names, as long as they are separated by commas
Example 1:
for i in range (5):
print (random.randint(1, 10))
output:
4
1
8
4
1
Example 2:
#Ending a Program early with sys.exit()
import sys
while True:
print('Type exit to exit.')
response = input()
if response == 'exit':
sys.exit()
print('You typed ' + response + '.
Random numbers
• Python defines a set of functions that are used to generate or manipulate random
numbers through the random module.
• The random module provides functions that generate pseudorandom numbers
• The function random returns a random float between 0.0 and 1.0 (including 0.0
but not 1.0). Each time you call random, you get the next number in a long series.
Method Description

randrange() Returns a random number between the given range

randint() Returns a random number between the given range (integer)

choice() Returns a random element from the given sequence

shuffle() Takes a sequence and returns the sequence in a random order

random() Returns a random float number between 0 and 1

uniform() Returns a random float number between two given parameters

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 22

import random
for i in range (10):
x = random.random()
print(x)
This program produces the following list of 10 random numbers between 0.0 and
up to but not including 1.0.
0.11132867921152356
0.5950949227890241
0.04820265884996877
0.841003109276478
0.997914947094958
0.04842330803368111
0.7416295948208405
0.510535245390327
0.27447040171978143
0.028511805472785867

he function randint takes the parameters between low and high (including both)
>>> random.randint (5, 10)
output
5
>>> random.randint (5, 10)
output
9
To choose an element from a sequence at random, you can use choice:
>>> t = [1, 2, 3]
>>> random.choice (t)
output
2
>>> random.choice(t)
output
3
>>mylist = ["apple", "banana", "cherry"]
>>random.shuffle(mylist)
>>print(mylist)
>>['apple', 'cherry', 'banana']
>> print (random.uniform(20, 60))
>>23.680525894591096
#To list all the functions listed under math module
import math
print(dir(math))
Method Description
math. sin() Returns the sine of a number
math. cos() Returns the cosine of a number
math.tan() Returns the tangent of a number
math.log() Returns the natural logarithm of a number, or the logarithm of number to base
math.log10() Returns the base-10 logarithm of x

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 23

math.ceil() Rounds a number up to the nearest integer


math.pi Returns 3.141592653589793

Example:
>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)

>>> radians = 0.7


>>> height = math.sin(radians)
>>> degrees = 45
>>> radians = degrees / 360.0 * 2 * math.pi
>>> math.sin(radians)
0.7071067811865476
>>> math.sqrt(2) / 2.0
0.7071067811865476

Functions________________________________________________________________
Q18. What is a function? How to define a function in python? Define with suitable
example. (6 marks).
_____________________________________________________________
A function is a reusable block of programming statements designed to perform a certain task.
To define a function, Python provides the def keyword. The following is the syntax of
defining a function.
def mult_Num(num1):
return num1 * 8

result = mult_Num(8)
print(result)
# Output:
----------------------------------------------------------------------------------------------------------------
Q19. Differentiate between argument and parameter. Illustrate the flow of execution of
a Python function with an example program to convert given Celsius to Fahrenheit
temperature. (8 marks)
Argument Parameter

Arguments are also known as Actual Parameters are also called Formal
Parameters. Parameters

When the function is called,


Each argument is always assigned to
parameters are local variables that
the parameter in the function
are assigned the values of the
definition during the call.
arguments.

When a function is invoked, the The values defined at the time of


values passed during the call are the function prototype or definition
referred to as arguments. are referred to as parameters.

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 24

In a function call statement, these These are used in the called


are used to send data from the function's function header to
calling function to the receiving receive the value from the
function. arguments.

# Python program to convert Celsius to Fahrenheit using function


def convertTemp(c): #user-defined function
# find temperature in Fahrenheit
f = (c * 1.8) + 32
return f
# take inputs
cel = float (input ('Enter temperature in Celsius: '))
# calling function and display result
fahr = convertTemp(cel)
print (“The temp in Fahrenheit”, fahr)

output: 'Enter temperature in Celsius: 30


The temp in Fahrenheit 86.0
----------------------------------------------------------------------------------------------------------------
Q20: Explain with an example what are fruitful and void functions. (4 marks)
Fruitful functions
1. The functions that return a value after their completion are called Fruitful functions.
2. A fruitful function must always return a value to where it is called from.
3. A fruitful function can return any type of value may it be string, integer, Boolean, etc.
4. It is not necessary for a fruitful function to return the value of one variable, the value
to be returned can be an array or a vector.
5. A fruitful function can also return multiple values.

# Creation of Function
def add_no (a, b):
c=a+b
# Returning the value
return c;
# Function call
d = add_no (3, 4);
print(d)

Void Functions

1. Void functions are those that do not return any value after their calculation is
complete.
2. These types of functions are used when the calculations of the functions are not
needed in the actual program.
3. These types of functions perform tasks that are crucial to successfully run the program
but do not give a specific value to be used in the program.

# Creation of Function

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 25

def add_no (a, b):


c = a + b;
print(c);
# Function Call
add_no (3, 4)
----------------------------------------------------------------------------------------------------------------
Q21. Explain Local and Global scope of variables in Python with example. (8 marks)
----------------------------------------------------------------------------------------------------------------
Python Local Variables
• Local variables in Python are those which are initialized inside a function and belong
only to that particular function.
• It cannot be accessed anywhere outside the function.

Python Global Variables


• These are those which are defined outside any function and which are accessible
throughout the program, i.e., inside and outside of every function. Let’s see how to
create a Python global variable.

Q22.How can you force a variable in a function to refer to the global variable?
To create a global variable inside a function, you can use the global keyword.
Example:
def spam():
global eggs
eggs = 'spam'
spam()
print(eggs)
output: spam

Programs:
Exercise 1: Write a program that uses input to prompt a user for their name and
then welcomes them.
name = input ("Enter your name")
print ('Hello!’, name)
output: Enter your name Marry
'Hello! Marry
Exercise 2: Write a program to prompt the user for hours and rate per hour to
compute gross pay.
#Compute gross pay bye hours and rate per hour
hours=input ("Enter Hour:")
rate=input ("Enter Rate per Hour:")
pay=float(hours)*float(rate)
print ("Pay is:", pay)
output: Enter Hour 20
Enter Rate per Hour: 2
Pay is 40.0
Exercise 3: Assume that we execute the following assignment statements:

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 26

width = 17
height = 12.0
Calculate
1. width//2
>>8
2. width/2.0
>>8.5
3. height/3
>>4.0
4. 1 + 2 \* 5
>>SyntaxError: unexpected character after line continuation character
Exercise 4: Write a program which prompts the user for a Celsius temperature, convert
the temperature to Fahrenheit, and print out the converted temperature.

F = (°C × 9 /5 ) + 32.
°C = [(°F-32) ×5]/9
Celsius =float (input (“enter temperature in Celsius”))
Fahrenheit = (Celsius * 1.8) + 32
print (“the given temperature in degree Fahrenheit is ", Fahrenheit)
output:
enter temperature in Celsius 40
the given temperature in degree Fahrenheit is 104.0
----------------------------------------------------------------------------------------------------------------
Exercise 5: Write a python program to calculate area of circle, rectangle and triangle.
print the results.

#Area of circle
R=int (input ("Enter the radius of the circle"))
Cir_area=float ((3.14) *R*R)
# Area of rectangle
Rw=int (input ("Enter the width of the rectangle"))
Rh=int (input("Enter the height of the rectangle"))
Rect_area=float (Rw*Rh)
#Area of triangle
Th=int (input ("Enter the height of the triangle"))
Tb=int (input ("Enter the breadth of the triangle"))
T_area=float ((0.5) *(Tb)*(Th))
#print results

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 27

print(" AREA OF CIRCLE")


print ("The area of circle is”, Cir_area)
print (" AREA OF RECTANGLE")
print ("The area of rectangle is”, Rect_area)
print (" AREA OF TRIANGLE")
print ("The area of Triangle is”, T_area)
output: Enter the breadth of the triangle 2
AREA OF CIRCLE
The area of circle is 12.56
AREA OF RECTANGLE
The area of rectangle is 200.0
AREA OF TRIANGLE
The area of Triangle is 4.0

Exercise 6: Rewrite your pay computation to give the employee 1.5 times the hourly rate
for hours worked above 40 hours.

hours =float (input ("Enter Hours:"))


rate =float (input ("Enter the Rate:"))
if hours<40:
pay=hours*rate
else:
pay=40*rate+(hours-40) *rate*1.5
print (‘the pay is’, pay)
output: Enter Hours:47
Enter the Rate:2
the pay is 101.0
Enter Hours:30
Enter the Rate:2
the pay is 60.0

Exercise 7: Rewrite your pay program using try and except so that your pro-gram handles
non-numeric input gracefully by printing a message and exiting the program. The
following shows two executions of the program:

hours=input ("Enter Hours:")

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 28

rate=input ("Enter Rate:")


try:
pay = int(hours) * int(rate)
print ("calculated Pay is:")
print(pay)
except:
print ("Error, please enter a number")
output: Enter Hours:47

Enter Rate: abc


Error, please enter a number
Enter Hours:56
Enter Rate:3
calculated Pay is:
168.0

Exercise 8: Write a program to prompt for a score between 0.0 and 1.0. If the
score is out of range, print an error message. If the score is between 0.0 and 1.0,
print a grade using the following table:
Score Grade
>=0.9 A
>=0.8 B
>=0.7 C
>=0.6 D
<0.6 F
Use Try and Except so that your program handles non-numeric input gracefully by
printing a message and exit the program.

score=input (‘enter the score value between 0.0 1nd 1.0->”)


Try:
score=float(score)
if (score>=0.9)
print (“the grade is A”)
if (score>=0.8)
print (“the grade is B”)
if (score>=0.7)

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 29

print (“the grade is C”)


if (score>=0.6)
print (“the grade is D”)
if(score<0.6)
print (“the grade is F”)
except:
print (“BAD SCORE”)
output: enter the score value 0.0 and 1.0->0.4
the grade is F

Exercise 9: Write a python program to calculate student score based on 2 exams, 1 sport
event and 3 activities conducted in a college with weightage of the activity =30% and
sports=20% for 50 marks.

a=float(input("Enter the mark of first subject(out of 100):"))


b=float(input("Enter the mark of second subject(out of 100):"))
c=float(input("Enter the performance mark of sport event(out of 50):"))
d=float(input("Enter the performance mark of first activity(out of 20):"))
e=float(input("Enter the performance mark of second activity(out of 20):"))
f=float(input("Enter the performance mark of third activity(out of 20):"))
exam=(a+b)*(50/200)
sport=c*(20/50)
activity=(d+e+f)*(30/60)
result=exam+sport+activity
#print results
print("Your result:",result)
output: Enter the mark of first subject(out of 100):90
Enter the mark of second subject(out of 100):60
Enter the performance mark of sport event(out of 50):40
Enter the performance mark of first activity(out of 20):15
Enter the performance mark of second activity(out of 20):10
Enter the performance mark of third activity(out of 20):10
Your result: 71.0

Exercise 10: Write a python program to calculate largest of three numbers.

Sapthagiri College of Engineering S.Shobha Dept. ECE


Page 30

a = int (input ('Enter first number: '))


b = int (input ('Enter second number: '))
c = int (input ('Enter third number: '))
if a > b and a > c :
largest = a
elif b > c :
largest = b
else :
largest = c
print (largest, "is the largest of three numbers.")
output: Enter first number: 20
Enter second number: 70
Enter third number: 30
70 is the largest of three numbers.

Exercise 11: write a python program to find best of two average marks out of three
test's marks accepted from user.

m1=float(input('enter the marks obtained'))


m2=float(input('enter the marks obtained'))
m3=float(input('enter the marks obtained'))
if (m1 > m2):
if (m2 > m3):
total =( m1 + m2)/2
else:
total = (m1 + m3)/2
else:
if (m1 > m3):
total = (m1 + m2)/2
else:
total = (m2 + m3)/2
print('the average of best of two marks is:',total)
output: enter the marks obtained 20
enter the marks obtained 50
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 31

enter the marks obtained 10

the average of best of two marks is: 35.0

Exercise 12: Rewrite your pay computation with time-and-a-half for overtime and create
a function called computepay which takes two parameters (hours and rate)

def computepay(hr,rt):
if hr<=40:
gross_pay=hr*rt
elif hr>40:
gross_pay=(hr-40)*rt*1.5+40*rt

return gross_pay

h=float(input("input the number of hours: "))


r=float(input("input the rate of pay:"))
pay=computepay(h,r)
print("the gross pay is=",pay)
output: input the number of hours: 30
input the rate of pay: 2
the gross pay is=60.0

Exercise 13: Rewrite your pay computation with time-and-a-half for overtime and
create a function called computepay which takes two parameters (hours and rate).

def comutegrade(score):
try:
sc=float(sc)
if sc>0.9:
grade='A'
elif sc>0.8:
grade='B'
elif sc>0.7:
grade='C'
elif sc>0.6:
grade='D'
Sapthagiri College of Engineering S.Shobha Dept. ECE
Page 32

elif sc<=0.6:
grade='Fail'
return print("grade is ",grade)
except:
print('bad score')
sc=input("enter the grade between 0.0 and 1.0\n")
comutegrade(sc)

Sapthagiri College of Engineering S.Shobha Dept. ECE

You might also like