Monday, June 20, 2016

Introduction to Network Programming - Decision and Repetition Structures (2)



Hi,
In this post i attached my lecture notes - 2 again which contains chapter  5, in this post i am going to post practice questions and tutorials  for chapter 5

here is the lecture notes



In this chapter you will learn,

  • while loop
  • for loop


programming exercises

You can find these exercise questions at the end of the chapter 5 in the book that i attached above, here i have written answers for each questions in exercises. So, you can check with your answers


1. Bug Collector
A bug collector collects bugs every day for seven days. Write a program that keeps a running total of the number of bugs collected during the seven days. The loop should ask for he number of bugs collected for each day, and when the loop is finished, the program should display the total number of bugs collected.

answer :-
total = 0
in_a_week = 7
for bugs in range(in_a_week):
    print("day "+str(bugs + 1),end = " ")
    bugs = int(input("Enter the bugs was collected by bug collector : "))
    total += bugs
print("Total number of bugs collected by bugs collector in a week was ",total)

2. Calories Burned
Running on a particular treadmill you burn 3.9 calories per minute. Write a program that uses a loop to display the number of calories burned after 10, 15, 20, 25, and 30 minutes.
answer :-
calories_per_minute = 3.9
print("minutes\tburned_calories")
for calories in range(10 , 31 , 5):
    no_of_calories = calories * calories_per_minute
    print(str(calories)+"\t"+str(no_of_calories))

3. Budget Analysis
Write a program that asks the user to enter the amount that he or she has budgeted for a month. A loop should then prompt the user to enter each of his or her expenses for the month, and keep a running total. When the loop finishes, the program should display the amount that the user is over or under budget.

answer :-
Estimated_budget = float(input("Enter the estimated budget for this month : "))
total_expense = 0
loop = True
while loop == True:
    user_response = input("is there any expenses for this month (y/n) : ")
    if user_response == 'y' or user_response == 'Y':
        expense = float(input("Enter the expense forthis month : "))
        total_expense += expense
    else:
        loop = False
if(Estimated_budget < total_expense):
    print("over budget")
else:
    print("under budget")

4. Distance Traveled
The distance a vehicle travels can be calculated as follows:
                         distance = speed * time
For example, if a train travels 40 miles per hour for three hours, the distance traveled is 120 miles. Write a program that asks the user for the speed of a vehicle (in miles per hour) and the number of hours it has traveled. It should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Here is an example of the desired output:
What is the speed of the vehicle in mph?40 enter
How many hours has it traveled?3 enter
Hour                Distance Traveled
1                          40 
2                         80
 3                        120

answer :-
speed = float(input("enter the speed of vehicle(in miles per hour) : "))
hours = int(input("how many hours it has travelled : "))
print("hour\tDstance Traveled")
for hour in range(1,hours + 1 ):
    distance = speed * hour
    print(hour,"\t\t",distance)


5. Average Rainfall
Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. The program should first ask for the number of years. The outer loop will iterate once for each year. The inner loop will iterate twelve times, once for each month. Each iteration of the inner loop will ask the user for the inches of rainfall for that month. After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.

answer :-
no_of_years = int(input("Enter the number of years : "))

total_years = 0
for year in range(1,no_of_years + 1 ):
    in_a_year = 12
    total = 0 
    for month in range(1,in_a_year + 1):
        print("month no :",(month),": in the year of :",(year),end=" ")
        month = float(input("Enter the rainfall of this month in inches : "))
        total += month
    total_years += total
    print("year :",year,"\t","TotalRainfall : ",total)
    no_of_months = no_of_years * 12
print("number of month : ",no_of_months)
print("total inches of rainfall :",total_years)
print("average rainfall per month : ",(total_years /no_of_months))

6. Celsius to Fahrenheit Table
Write a program that displays a table of the Celsius temperatures 0 through 20 and their Fahrenheit equivalents. The formula for converting a temperature from Celsius to Fahrenheit is
                                  F = ( 9 / 5 ) * c + 32
where F is the Fahrenheit temperature and C is the Celsius temperature. Your program must use a loop to display the table.

answer :-
print("Celsious\tFehrenheit")
for C in range(0,21 ):
    F = (9/5)*C + 32
    print(C,"\t\t",format(F , '.1f'))

7. Pennies for Pay
Write a program that calculates the amount of money a person would earn over a period of time if his or her salary is one penny the first day, two pennies the second day, and continues to double each day. The program should ask the user for the number of days. Display a table showing what the salary was for each day, and then show the total pay at the end of the period. The output should be displayed in a dollar amount, not the number of pennies.

answer :-
noOfDays = int(input("Enter the number of days : "))
print("Days\t\tSalary")
PENNY = 0.01
for day in range(noOfDays + 1 ):
    salary = (2 ** day ) * PENNY
    print((day + 1),"\t\t","$"+str(salary))
8. Sum of Numbers
Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum.

answer :-
total = 0
n = 1
print(n ,")",end = " ")
num = int(input("Enter the number : "))
while num >= 0:
    n += 1
    total += num
    print(n ,")",end = " ")
    num = int(input("Enter the number : "))
print( "Total :" , total)




From the tutorial,
The for loop,
(1) Write a for loop which will print numbers from 1 to 10 on the same line separated by a space. 
answer :-
for num in range(1,11):
    print(num,end = " ")
(2) Write a for loop which will print numbers from 10 to 1, one number per line
answer :-
for num in range(10,0,-1):
    print(num)
 (3) Write a small program which will prompt the user to enter a number and then use a for loop to print the numbers from 1 to the number entered.
answer :-
endMark = int(input("Enter the number : "))
for num in range(1,endMark + 1)     :
    print(num,end=" ")
 (4) Modify the program above so that it calculates the sum and product (multiplies the numbers) instead of just displaying the numbers
answer :- 
endMark = int(input("Enter the number : "))
sumt = 0
product = 1
for num in range(1,endMark + 1)     :
    sumt += num
    product *= num
print("product = ",product)
print("sum = ",sumt)
(5) Write another program similar to the one in part 4 above which will add only the even numbers up to the number entered by the user
answer :-
endMark = int(input("Enter the number : "))
sumt2 = 0
for num in range(0,endMark + 1,2)     :
    sumt2 += num
 
print("sum =",sumt2)

The while loop,
(1) Write a while loop which will print numbers from 1 to 10 on the same line separated by a space. 
answer :-
num = 1
while(num <= 10):
    print(num,end = " ")
    num += 1
(2) Write a while loop which will print numbers from 10 to 1, one number per line
answer :-
num = 10
while(num > 0):
    print(num)
    num -= 1
 (3) Write a small program which will prompt the user to enter a number and then use a while loop to print the numbers from 1 to the number entered.
answer :-
number = int(input("Enter the number you want : "))
num = 1
while(num <= number):
    print(num,end=" ")
    num +=1
 (4) Modify the program above so that it calculates the sum and product (multiplies the numbers) instead of just displaying the numbers
answer :- 
number = int(input("Enter the number : "))
num = 1
sumt = 0
product = 1
while(num <= number):
    sumt += num
    product *= num
    num +=1
print("sum = ",sumt)
print("product = ",product)
(5) Write another program similar to the one in part 4 above which will add only the even numbers up to the number entered by the user
answer :-
number = int(input("Enter the number : "))
num = 0
sumt = 0
#product = 1
while(num <= number):
    print(num,end=" ")
    sumt += num
    #product *= num
    num +=2
print("sum = ",sumt)
#print("product = ",product)


From the exam,
Write a program with the specifications described below.
• Display a welcoming message such as “Welcome to server classification program!”
• Prompt the user for a whole number, indicating the number of connections to a particular server, and store this value in a variable named hits
• If the input is a non-negative integer value: 
                ü     Determine whether the server is busy, quiet, lazy or idle based on                             the information given in the table below and return an appropriate                         string message to indicate this classification (also given in the                                     table)
                ü     Display this message to the user
                ü     Ask user to enter another value to classify another server
• If the user entered a negative integer value:
                ü     Display “Goodbye” on the screen and terminate the program
• Note that the program will continue to run and classify servers based on the number of connections until the user enters a negative number at the prompt
Table used for classifications and corresponding messages
connections hits > 2000     1000<hits<=2000     0<hits<=1000           hits=0

message             Busy                         Quiet                             Lazy                        Idle

answer :-
print("welcome to the server classification program! ")
hits = int(input("Enter the number of conncetion to a perticular server : "))
while(hits >= 0):
    if(hits > 2000):
        print("Very busy")
    elif(1000 < hits and hits <= 2000):
        print("busy")
    elif(0 < hits and hits <= 1000):
        print("Quiet")
    elif(hits == 0):
        print("Idle")
    hits = int(input("Enter the number of conncetion to a perticular server : "))
print("...........Goodbye.............")


Create Patterns in python,
Pattern -- 1


Code :- 
for row in range(10):
    for coloum in range(10):
        print("*",end="")
    print()

Pattern -- 2

Code :- 

for row in range(10):
    for coloum in range(row):
        print("*",end="")
    print()

Pattern -- 3
Code :- 
for row in range(10):
    for coloum in range(row):
        print(" ",end="")
    print("*")
Or
for row in range(10):
    for coloum in range(row+1):
        if(coloum == row):
            print("*",end="")
        else:
            print(" ",end="")
    print()

Pattern -- 4
Code :-
for row in range(10):
    for coloum in range(9-row):
        print(" ",end="")
    print("*")

Pattern -- 5
Code :-
for row in range(10):
    for coloum in range(9-row):
        print("*",end="")
    print()


Pattern -- 6












Code :-
 for row in range(10):
    for coloum in range(row+1):
        if(coloum == 0):
            print("*",end="")
        else:
            print(" ",end="")
    print("*")

Pattern -- 7












Code :-
for row in range(1,11):
    for column in range(10,0 ,-1):
        if column >= row:
            print(" ",end="")
    for k in range(1,2 * row ):
        print("*",end="")
    print("")

Pattern -- 8












Code :-
for row in range(10,0,-1):
    for column in range(10,0 ,-1):
        if column > row:
            print(" ",end = "")

    for k in range(1,2 * row ):
        print("*",end = "")
    print()

Pattern -- 9


















Code :-
for row in range(1,11):
    for column in range(row,11):
        print(" ",end = "")
    for k in range(1,2 * row ):
        print("*",end = "")
    print()
for row in range(9,0,-1):
    for column in range(11,0 ,-1):
        if column > row:
            print(" ",end = "")
    
    for k in range(1,2 * row ):
        print("*",end = "")
    print()  


i will post chapter 3,6 very soon. any correction has to be made, you can make it as comments it will be appreciated.












No comments:

Post a Comment