Hi,
In this post i attached my lecture 3 which has chapter 6, here i going to post practice questions and tutorial for chapter 6
here, you can find lecture slides,
Programming Exercises
you canfind these exercise questions at the end of the chapter 6 in this book.
1. Feet to Inches
One foot equals 12 inches. Write a function named feet_to_inches that accepts a number of feet as an argument, and returns the number of inches in that many feet. Use the function in a program that prompts the user to enter a number of feet and then displays the
number of inches in that many feet.
answer :-
def main():
noOfFeet = int(input("Enter the number of feet : "))
noOfInches = feet_to(noOfFeet)
print("number of inches in that feet :",noOfInches)
def feet_to(f):
inches = f * 12
return inches
main()
2. Math Quiz
Write a program that gives simple math quizzes. The program should display two random
numbers that are to be added, such as:
247
+ 129
The program should allow the student to enter the answer. If the answer is correct, a message of congratulations should be displayed. If the answer is incorrect, a message showing
the correct answer should be displayed.
answer :-
import random
def main():
number1 = random.randint(1,1000)
number2 = random.randint(1,1000)
print(number1 , "+",number2," = " )
answer = int(input("Enter the answer : "))
calculateAnswer = findAnswer(number1 , number2)
if answer == calculateAnswer:
print("Congratulations!!!!")
else:
print("Sorry!! , correct answer is",calculateAnswer)
def findAnswer(a , b):
total = a + b
return total
main()
3. Maximum of Two Values
Write a function named maximum that accepts two integer values as arguments and returns
the value that is the greater of the two. For example, if 7 and 12 are passed as arguments
to the function, the function should return 12. Use the function in a program that prompts
the user to enter two integer values. The program should display the value that is the
greater of the two.
answer :-
def main():
number1 = int(input("Enter the number 1 : "))
number2 = int(input("Enter the number 2 : "))
findMaximum = maximum(number1 , number2)
print("maximum number is :",findMaximum)
def maximum(a , b):
if a >= b:
return a
else:
return b
main()
4. Falling Distance
The following formula can be used to determine the distance an object falls due to gravity
in a specific time period, starting from rest:
d = 1⁄2 x g x (t xx 2)
The variables in the formula are as follows:
d is the distance in meters,
g is 9.8,
t is the
amount of time in seconds, that the object has been falling.
Write a function named falling_distance that accepts an object’s falling time in seconds
as an argument. The function should return the distance in meters that the object has fallen
during that time interval. Write a program that calls the function in a loop that passes the
values 1 through 10 as arguments and displays the return value.
answer :-
def main():
print("Time(s)\tDistsnce()")
for timeSec in range(1,11):
distance = falling_distance(timeSec)
print(timeSec,"\t\t",format(distance, '.2f'))
def falling_distance(t):
d = (1/2) * 9.8 * (t ** 2)
return d
main()
5. Kinetic Energy
In physics, an object that is in motion is said to have kinetic energy (KE). The following formula can be used to determine a moving object’s kinetic energy:
KE = 1⁄2 x m x (v xx 2)
The variables in the formula are as follows:
KE is the kinetic energy in joules,
m is the
object’s mass in kilograms,
v is the object’s velocity in meters per second.
Write a function named kinetic_energy that accepts an object’s mass in kilograms and
velocity in meters per second as arguments. The function should return the amount of
kinetic energy that the object has. Write a program that asks the user to enter values for
mass and velocity, and then calls the kinetic_energy function to get the object’s kinetic
energy.
answer :-
def main():
objectMass = float(input("Enter the object's mass (Kg) : "))
objectVelocity = float(input("Enter the object's velocity (m/s) : "))
kEnergy = kinetic_energy(objectMass , objectVelocity)
print("Kinetic Energy of the Object (joules) : ",format(kEnergy, '.2f'))
def kinetic_energy(m , v):
KE = (1/2) * m * (v ** 2)
return KE
main()
6. Test Average and Grade
Write a program that asks the user to enter five test scores. The program should display a letter
grade for each score and the average test score. Write the following functions in the program:
• calc_average—This function should accept five test scores as arguments and return
the average of the scores.
• determine_grade—This function should accept a test score as an argument and
return a letter grade for the score, based on the following grading scale:
Score Letter Grade
90–100 A
80–89 B
70–79 C
60–69 D
Below 60 F
answer :-
def main():
testScore1 = float(input("Enter the test score 1 : "))
testScore2 = float(input("Enter the test score 2 : "))
testScore3 = float(input("Enter the test score 3 : "))
testScore4 = float(input("Enter the test score 4 : "))
testScore5 = float(input("Enter the test score 5 : "))
averageScore = calc_average(testScore1,testScore2,testScore3,testScore4,testScore5)
grade = determine_grade(averageScore)
print("your grade is : ",grade)
def calc_average(s1,s2,s3,s4,s5):
aveScore = (s1 + s2 + s3 + s4 + s5) / 5
return aveScore
def determine_grade(s):
if 90 <= s <= 100:
return "A"
elif 80 <= s <= 89:
return "B"
elif 79 <= s <= 79:
return "C"
elif 60 <= s <= 69:
return "D"
elif 0 <= s <= 59:
return "f"
main()
7. Odd/Even Counter
In this chapter you saw an example of how to write an algorithm that determines whether
a number is even or odd. Write a program that generates 100 random numbers, and keeps
a count of how many of those random numbers are even and how many are odd.
answer :-
import random
def main():
count = 0
for number in range(100):
number = random.randint(1,100)
print(number , end=",")
evenOrOdd = isEven(number)
if evenOrOdd == "is Even":
count += 1
print()
print(" number of even numbers from the above list :",count)
print(" number of odd numbers from the above list :",(100 - count))
def isEven(n):
if ( n % 2 == 0):
return "is Even"
else:
return "is Odd"
main()
Or
import random
def main():
countEven = 0
countOdd = 0
for number in range(100):
number = random.randint(1,1000)
print(number , end=",")
evenOrOdd = isEven(number)
if evenOrOdd == "is Even":
countEven += 1
else:
countOdd += 1
print()
print(" number of even numbers from the above list :",countEven)
print(" number of odd numbers from the above list :",countOdd)
def isEven(n):
if ( n % 2 == 0):
return "is Even"
else:
return "is Odd"
main()
8. Prime Numbers
A prime number is a number that is only evenly divisible by itself and 1. For example, the
number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, however, is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a Boolean function named is_prime which takes an integer as an argument and
returns True if the argument is a prime number, or False otherwise. Use the function in a
program that prompts the user to enter a number and then displays a message indicating
whether the number is prime.
answer :-
def main():
continueCheck = "y"
while continueCheck == "y":
is_prime = False
number = int(input("Enter the number : "))
primeOrNot = isPrime(number , is_prime)
if primeOrNot:
print("number that you are entered is PRIME")
else:
print("number that you are entered ISN'T PRIME")
continueCheck = input("do you want to continue with another number (y/n) : ")
def isPrime(n , isPrime):
for num in range(2,(n//2) + 1):
if n % num != 0 :
isPrime = True
else:
isPrime = False
return isPrime
return isPrime
main()
9. Prime Number List
This exercise assumes you have already written the is_prime function in Programming
Exercise 8. Write another program that displays all of the prime numbers from 1 through 100.
The program should have a loop that calls the is_prime function.
answer :-
def main():
count = 0
is_prime = False
print("Prime List (1 - 100) : ",end ="")
for number in range(100):
primeOrNot = isPrime(number , is_prime)
if primeOrNot:
print(number, end=",")
count += 1
print()
print("Number of Prime Numbers (1 - 100) :",count)
def isPrime(n , isPrime):
for num in range(2,(n//2) + 1):
if n % num != 0 :
isPrime = True
else:
isPrime = False
return isPrime
return isPrime
main()
10. Future Value
Suppose you have a certain amount of money in a savings account that earns compound
monthly interest and you want to calculate the amount that you will have after a specific
number of months. The formula is
F = P x (1 + i) ** t
The terms in the formula are as follows:
• F is the future value of the account after the specified time period.
• P is the present value of the account.
• i is the monthly interest rate.
• t is the number of months.
Write a program that prompts the user to enter the account’s present value, monthly interest
rate, and number of months that the money will be left in the account. The program should
pass these values to a function that returns the future value of the account after the specified
number of months. The program should display the account’s future value.
answer :-
def main():
loop = "y"
while loop == 'y':
presentValue = float(input("Enter the account's present value : "))
monthlyInterest = float(input("Enter the monthly interest rate : "))
noOfMonth = float(input("Enter the number of months money will be left : "))
futureValue = calcFutureVal(presentValue , monthlyInterest , noOfMonth )
print("Account's Future Value : $"+str(format(futureValue, '.2f')))
loop = input("do you want to continue with another/same account(y/n): ")
def calcFutureVal(P , i , t):
F = P * ((1 + i )** t)
return F
main()
11. Random Number Guessing Game
Write a program that generates a random number in the range of 1 through 100 and asks the
user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” If the user guesses the number, the application should congratulate the user and then generate a new random number so the game can
start over.
Optional Enhancement: Enhance the game so it keeps count of the number of guesses that the
user makes. When the user correctly guesses the random number, the program should display
the number of guesses.
answer :-
import random
def main():
count = 0
gCount = 0
loop = 'y'
while loop == "y":
count+=1
number1 = random.randint(1,100)
number = int(input("guess the number from 1 - 100 : "))
if number == number1:
gCount += 1
print("Congratulation!!!")
print("random number is :",number1)
elif number > number1:
print("Too high, try again")
print("random number is :",number1)
elif number < number1:
print("Too low, try again")
print("random number is :",number1)
loop =input("do you want to continue (y/n): ")
print("number of attempts : ",count)
print("number of right guesses : ",gCount)
main()
12. Rock, Paper, Scissors Game
Write a program that lets the user play the game of Rock, Paper, Scissors against the computer. The program should work as follows.
1. When the program begins, a random number in the range of 1 through 3 is generated.
If the number is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper. If the number is 3, then the computer has chosen scissors.
(Don’t display the computer’s choice yet.)
2. The user enters his or her choice of “rock”, “paper”, or “scissors” at the keyboard.
3. The computer’s choice is displayed.
4. A winner is selected according to the following rules:
• If one player chooses rock and the other player chooses scissors, then rock wins.
(The rock smashes the scissors.)
• If one player chooses scissors and the other player chooses paper, then scissors wins.
(Scissors cuts paper.)
• If one player chooses paper and the other player chooses rock, then paper wins.
(Paper wraps rock.)
• If both players make the same choice, the game must be played again to determine
the winner.
answer :-
import random
def main():
loop = 'y'
while loop == "y":
winner = programMethod()
print(winner)
while winner == "same choice":
print("both players choose same choice", \
"the game must be played aagain....")
winner = programMethod()
print(winner)
loop =input("do you want to play again (y/n): ")
def programMethod():
number1 = random.randint(1,3)
computerChoice = compChoice(number1)
userChoice = input("Enter your choice (Rock / Paper / Scissors ) : ")
winnerChoice = winChoice(computerChoice , userChoice)
print("Computer Choice :",computerChoice)
print("User Choice :",userChoice)
return winnerChoice
def compChoice(n):
if str(n) == '1':
comChoice = "Rock"
elif str(n) == '2':
comChoice = "Paper"
elif str(n) == '3':
comChoice = "Scissors"
return comChoice
def winChoice(cs , us):
if cs == "Rock" and us == "Scissors":
result = "Winner is Computer "
elif cs == "Scissors" and us == "Rock":
result = "Winner is User "
elif cs == "Scissors" and us == "Paper":
result = "Winner is Computer "
elif cs == "Paper" and us == "Scissors":
result = "Winner is User "
elif cs == "Paper" and us == "Rock":
result = "Winner is Computer "
elif cs == "Rock" and us == "Paper":
result = "Winner is User "
else :
result = "same choice"
return result
main()
i will post chapter 7(files and exceptions) very soon......
No comments:
Post a Comment