Application Development using Python (18CS55) VTU Questions and Solutions - 1

 

1. Demonstrate the operator precedence & associative rule with respect to arithmetic operations with examples. 

5 M

Operator

Operation

Example

Evaluates to

Associative rule

**

Exponent

2 ** 3

8

right-to-left

%

Modulus/remainder

22 % 8

6

Left to right

//

Integer division/floored quotient

22 // 8

2

Left to right

/

Division

22 / 8

2.75

Left to right

*

Multiplication

3 * 5

15

Left to right

-

Subtraction

5 - 2

3

Left to right

+

Addition

2 + 2

4

Left to right















2. Implement a Number Guessing Game by ensuring the following criteria   

• The guess number is generated by the program randomly.  However, you have the option of setting the range. If the guessed number and the given number is same the user wins. The program displays “You’ve WON the game…”

 • If the number given by the user is greater or lesser appropriate message is displayed. Like “Number is too big…”     or “Number is too low…”

 • A maximum of FIVE chances are given. Even after FIVE chances the number is not guessed rightly the following message is displayed “You’ve have LOST the game…”

Note: import all modules required for successful compilation of the program

import random

def guessnumber(num):

    chance=6

    print('Guess the number I am thinking')

    print('you have '+str(chance)+' chance')

    for i in range(chance):

        guess=int(input())

        if guess==num:

            break

        elif guess<num:

            print('value is low')

            chance=chance-1

            print('you have '+str(chance)+' chance left')

        else:

            print('value is High')

            chance=chance-1

            print('you have '+str(chance)+' chance left')     

    if guess==num:

        print('Greetings!!!! you have won')

    else:

        print('Nope. Number was '+str(num))

guessnumber(random.randint(0,50))

3.  Write the syntax of all python supported conditional statements. Using Conditional statement write a python program to prompt for a score between 0.0 and 1.0. if the score is out of range print error message. if the score is between 0.0 and 1.0, print a grade using following data. Score(S)>=0.9 is A grade, similarly S>=0.8 B grade, S>=0.7 C grade, S>=0.6 D grade and S<0.6 F grade.

if condition :

    if_block

if condition :

    if_block

else:

    else_block

 if condition :

    if_block

elif condition:

    elif_block

 -

 -

else:

    else_block

 score=float(input('Enter a score between 0.0 and 1.0'))

if (score<0.0)or(score>1.0):

    print('Invalid score')

    print('Enter a score between 0.0 and 1.0  ')

else:

    if score >= 0.9 :

        print('Grade is A grade')

    elif score>=0.8 and score<0.9:

        print('B grade')

    elif score>=0.7 and score<0.8:

        print('C grade')

    elif score>=0.6 and score <0.7:

        print('D grade ')

    else:

        print('F grade')

4. Write the syntax of for loop and while loop in python. Using the for loop write a Python program to construct the following pattern:


Note: Python’s print() function comes with a parameter called ‘end’. By default, the value of this parameter is ‘\n’. You can end a print statement with any character/string using this parameter.

print('hello',end='*')

print('world')

hello*world

for i in range():

    for_block

while condition:

    while_block

 # Initialize the first five rows

n = 5

# Start the loop to print the first five rows

for i in range(5):

    for j in range(i):

        print('* ', end="")

    print('')

# Start the loop to print the remaining rows in decreasing order of stars

for i in range(n,0,-1):

    for j in range(i):

        print('* ', end="")

    print('')
5. Demonstrate the use of break statement with a program to calculate the sum of numbers (10 inputs max). For each iteration, ask user to enter number and if the user enters a negative number, the loop terminates and prints sum.

Explain break statement

sum = 0

for i in range(10):

    print('Enter a number')

    num=int(input())

    #if the user enters a negative number, break the loop

    if(num < 0):

         break;

    sum += num

print('Sum is ',sum)

6. Demonstrate the use of continue statement with a program to calculate the sum of numbers (10 inputs max). For each iteration, ask user to enter number and if the user enters a negative number, it's not added to the result.

Explain continue statement

sum = 0

for i in range(10):

    print('Enter a number')

    num=int(input())

    #if the user enters a negative number, break the loop

    if(num < 0):

         continue;

    sum += num

print('Sum is ',sum)

7. Discuss the advantages of functions in python programming. Using function write a python program that takes decimal number as input and convert that to binary equivalent and return the same.

Functions allow the same piece of code to run multiple times

Functions break long programs up into smaller components

Functions can be shared and used by other programmers

def binary(n):

   if n > 1:

       binary(n//2)

   print(n % 2,end = '')

dec = int(input("Enter an integer: "))

binary(dec)

8. Discuss any three types of errors that occur while working with the functions. Using function write a python program that takes integer number n as input and calculates value based on the formula 22n+1 and returns the same

ValueError: except integer but passed other type

NameError: function name

TypeError: parameters

 

def twonplusone(n):

   value=2**(2*n)+1

   return value

# Take input number from user

value = int(input("Enter an integer: "))

print('twonplusone is ',twonplusone(value))

9. Differentiate between List and Tuple. Write a python program for searching an element in a list using recursive binary search. The program should display index of the element if present otherwise Element not present.

Lists are mutable

Defined using []

 

Tuples are immutable

()

 

global org

def bs(ele,low,high,item):

    mid=int((low+high)/2)

    if low>high:

        print('Element is not there in list')

    elif item<ele[mid]:

        bs(ele,low,mid-1,item)

    elif item>ele[mid]:

        bs(ele,mid+1,high,item)

    else:

        print('item is present at the index ',org.index(ele[mid])) 

print('enter the elements of list (empty to stop)')

ele=[]

while True:

    i=input()

    if i==''":

        break

    ele.append(int(i))

high=len(ele)-1

org=ele.copy()

ele.sort()

item=int(input('enter the element to search in the list'))

bs(ele,0,high,item)

10. Differentiate between List and dictionary in python. Write a Python program that takes USN and marks of 10 students from the user. Create a dictionary with key as USN and value as marks. Sort the dictionary values based on marks and display the email id of the topper by adding @bmsit.in to USN.

List are ordered

List is created by placing elements in [ ] separated by commas “, “

              

Dictionary is a hashed structure of key and value pairs

Dictionary is created by placing elements in { } as “key”:”value”, each key value pair is separated by commas “,

 

print('enter USN and marks for 10 students')

d={}

for i in range(10):

    print('student ',(i+1))

    print('USN ')

    usn=input()

    print('marks ')

    marks=int(input())

    d[usn]=marks

k=list(d.keys())

t=list(d.values())

for i in range(len(t)):

    for j in range(len(t)-1):

        if t[i] > t[j]:

            t1=t[i]

            k1=k[i]

            t[i]=t[j]

            k[i]=k[j]

            t[j]=t1

            k[j]=k1

tc=t.count(t[0])

if tc>1:

    print('Email id of the toppers are ')

    for i in range(tc):

        print(k[i]+'@bmsit.in')

else:

    print('Email id of the topper is ')

    print(k[0]+'@bmsit.in')

11. Write a python program to remove numbers greater than 50 from a list while iterating but without creating a different copy of a list.

Input: number_list = [100, 120, 80, 40, 50, 60, 30, 15, 90, 10]

Expected output  

[10,15, 20, 30, 40, 50]

number_list = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

i = 0

# get list's size

n = len(number_list)

# iterate list till i is smaller than n

while i < n:

    # check if number is greater than 50

    if number_list[i] > 50:

        # delete current index from list

        del number_list[i]

        # reduce the list size

        n = n - 1

    else:

        # move to next item

        i = i + 1

print(number_list)

Comments

Popular posts from this blog

MICROCONTROLLER AND EMBEDDED SYSTEMS LABORATORY Part A

DBMS Lab 15-16: Design and implementation of COMPANY database. Design and implementation of MOVIE DATABASE.

Microcontroller and Embedded systems Questions and Scheme of Evaluation