Monday, June 27, 2016

Hi,
In this post i attached my lecture 5 which describes chapter 8,9. Here i am going to post practice questions for chapter 9 and tutorials for chapter 8 and 9.

here, you can find the lecture slides,


Programming exercises
you can find these exercise questions at the end of the chapter 9 in this book.

1. InitialsWrite a program that gets a string containing a person’s first, middle, and last names, and then display their first, middle, and last initials. For example, if the user enters John William Smith the program should display J. W. S.

answer :- 


firstName = input("Enter the first name : ")

middleName = input("Enter the middle name :")
lastName = input("Enter the last name : ")

print("disply the first , middle and last initials...")
print(firstName[0],".",middleName[0],".",lastName[0],sep="")


2. Sum of Digits in a String
Write a program that asks the user to enter a series of single-digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the string. For example, if the user enters 2514, the method should return 12, which is the sum of  2, 5, 1, and 4. 

answer :- 


numbers = input("Enter the series single-digit numbers : ")


total = 0
for i in numbers:
    convertNumber = int(i)
    total += convertNumber
print("total :",total)


3. Date Printer
Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the form March 12, 2012.

answer :- 


def main():

    monthList = ["January" , "february" , "March" , "April" , "May" ,\
             "June" , "July" ,"August" , "September" , \
             "October" , "November" , "December" ]
    print("assign months into the list...")
    print(monthList)
    print("get the date from the user in the form (mm/dd/yyyy)")
    date = input("Enter the date(mm/dd/yyyy) : ")
    
    monthNumber , dateNumber , year, yearLength = date_split(date)
    
    while monthNumber >= 13 or dateNumber>= 32 or \
      monthNumber <= 0 or dateNumber<= 0 or yearLength != 4:
        warning()
        date = input("Enter the date(mm/dd/yyyy) : ")
        monthNumber , dateNumber , year, yearLength = date_split(date)
        
    print("print the date in the form: ",end="")
    month = monthList[monthNumber - 1]
    print(month,",",dateNumber,",",year,sep="")
    
def date_split(date):
    dateSplit = date.split("/")
    print("dateSplit = ",end="")
    print(dateSplit)
    monthNumber = int(dateSplit[0])
    dateNumber = int(dateSplit[1])
    year = int(dateSplit[2])
    yearLength = len(dateSplit[2])
    return monthNumber , dateNumber ,year,yearLength

def warning():
    print("you gave the wrong inputs.....")
    print("give the month number between 1 -12")
    print("give the day number between 1 -31")
    print("year must be 4 digits")
    
main()



4. Morse Code Converter
Morse code is a code where each letter of the English alphabet, each digit, and various punctuation characters are represented by a series of dots and dashes. Table 9-5 shows part of the code.
Write a program that asks the user to enter a string, and then converts that string to Morse code.

Table 9-5 Morse code
Character                  Code                  Character               Code      
space                            space                 6                                 – . . . .
comma                        – – . . – –          7                                  – – . . .  .
period                         . – . – . –             8                                 – – – . .
question mark       . . – – . .              9                                 – – – – .
0                                     – – – – –           A                                 . –
1                                      . – – – –             B                                 – . . .
....................................................

answer :- 


def main():

    file_variable = open("morsecode.txt" , "r")
    listOFlist = []
    for line in file_variable:
        line = line.rstrip('\n')
        mylist = line.split()
        listOFlist.append(mylist)
    character = input("Enter the character : ")
    morseCode = findOfCode(character,listOFlist)
    if morseCode == "":
        print(" chracter not found  ")
    else:
        print("Morse Code for the character:"+"("+character+")","is",morseCode)
        
def findOfCode(character,listOFlist):
    for i in range(len(listOFlist)):
        for j in range(len(listOFlist[i])):
            if(listOFlist[i][j] == character):
                return listOFlist[i][j+1]
    return ""
main()


5. Alphabetic Telephone Number Translator
Many companies use telephone numbers like 555-GET-FOOD so the number is easier for their customers to remember. On a standard telephone, the alphabetic letters are mapped to numbers in the following fashion:
A, B, and C =  2
D, E, and F 3
G, H, and I 4
J, K, and L 5
M, N, and O =   6
P, Q, R, and S =  7
T, U, and V 8
W, X, Y, and Z  = 9
Write a program that asks the user to enter a 10-character telephone number in the format XXX-XXX-XXXX. The application should display the telephone number with any alphabetic characters that appeared in the original translated to their numeric equivalent. For example, if the user enters 555-GET-FOOD the application should display 555-438-3663.

answer :- 


def main():

    alphaList = [["A","B","C"],\
                    ["D","E","F"],\
                    ["G","H","I"],\
                    ["J","K","L"],\
                    ["M","N","O"],\
                    ["P","Q","R","S"],\
                    ["T","U","V"],\
                    ["W","X","Y","Z"]]
    numList = ["2","3","4","5","6","7","8","9","1"]
    print("get the 10 character tp number",\
          "from the user in the form (XXX-XXXX-XXXX)")
    tpNumber = input("Enter the 10-character tp number(XXX-XXXX-XXXX) : ")
    tpSplit = tpNumber.split("-")
    listLength1,listLength2,listLength3 = tpList(tpSplit)
    while listLength1 != 3 or listLength2 != 3 or \
          listLength3 != 4 :
        print("you gave the wrong format of telephone number...")
        print("format should be XXX-XXX-XXXX")
        tpNumber = input("Enter the 10-character tp number(XXX-XXXX-XXXX) : ")
        tpSplit = tpNumber.split("-")
        listLength1,listLength2,listLength3 = tpList(tpSplit)
    print("user entered format : ",end="")
    print(tpSplit[0].upper(),"-",tpSplit[1].upper(),\
          "-",tpSplit[2].upper(),sep="")
    print("numeric format : ",end="")
    for element in tpSplit[0]:
        elementUpper = element.upper()
        result = convert_tp(elementUpper,numList,alphaList)
        print(result,end="")
    print("-",end="")
    for element in tpSplit[1]:
        elementUpper = element.upper()
        result = convert_tp(elementUpper,numList,alphaList)
        print(result,end="")
    print("-",end="")
    for element in tpSplit[2]:
        elementUpper = element.upper()
        result = convert_tp(elementUpper,numList,alphaList)
        print(result,end="")
    
    
def tpList(anyList):
    anyList1 = len(anyList[0])
    anyList2 = len(anyList[1])
    anyList3 = len(anyList[2])
    return anyList1,anyList2,anyList3

def convert_tp(element,numList,alphaList):
    if element in numList:
        return element
    else:
        for row in range(len(alphaList)):
            for coloumn in range(len(alphaList[row])):
                if element == alphaList[row][coloumn]:
                    return numList[row]


main()


6. Average Number of Words
If you have downloaded the source code from this book’s companion Web site, you will find a file named text.txt in the Chapter 09 folder. The text that is in the file is stored as one sentence per line. Write a program that reads the file’s contents and calculates the average number of words per sentence.

answer :- 


def main():

    file_variable = open("text.txt" , "r")
    textList = []
    for line in file_variable:
        line = line.strip().rstrip("/n")
        mylist = line.split()
        textList.append(mylist)
    print("finding number of lines in text.txt file")
    totalLine = findLine(textList)
    print("number of line : ",totalLine)
    print("finding number of words in text.txt file")
    totalWords = findWords(textList)
    
    print("number of words : ",totalWords)
    print("finding average words per line in text.txt file")
    wordsPerLine = averageWords(totalWords , totalLine)
    print("average words per line : ",wordsPerLine)
    
def findLine(anyList):
    count = 0
    for rachRow in anyList:
        count+= 1
    return count

def findWords(anyList):
    total = 0
    for row in range(len(anyList)):
        count = 0
        for coloumn in range(len(anyList[row])):
            count += 1
        total += count
    return total

def averageWords(words , lines):
    wordsPerLine = round(words /lines)
    return wordsPerLine

main()


7. Character AnalysisIf you have downloaded the source code from this book’s companion Web site, you will find a file named text.txt in the Chapter 09 folder. Write a program that reads the file’s contents and determines the following:
• The number of uppercase letters in the file
• The number of lowercase letters in the file
• The number of digits in the file
• The number of whitespace characters in the file

answer :- 


def main():

    file_variable = open("text.txt" , "r")
    textList = []
    for line in file_variable:
        line = line.rstrip("/n")
        mylist = line
        textList.append(mylist)

    
    print("finding number of uppercase Letters in text.txt file")
    totalUpCaLetters = countUpperCase(textList)
    print("number of uppercase Letters : ",totalUpCaLetters)
    print()
    print("finding number of lowercase letters in text.txt file")
    totalLoCaLetters = countLowerCase(textList)
    print("number of Lower case Letters : ",totalLoCaLetters)
    print()
    print("finding number of digits in text.txt file")
    totalDigits = countDigits(textList)
    print("number of digits : ",totalDigits)
    print()
    print("finding number of whitespaces in text.txt file")
    totalWhiteSpaces = countWhiteSpace(textList)
    print("number of whitespaces : ",totalWhiteSpaces)
        
def countUpperCase(anyList):
    count = 0
    for row in range(len(anyList)):
        for i in range(len(anyList[row])):
            if anyList[row][i].isupper():
                count+= 1
    return count

def countLowerCase(anyList):
    count = 0
    for row in range(len(anyList)):
        for i in range(len(anyList[row])):
            if anyList[row][i].islower():
                count+= 1
    return count

def countDigits(anyList):
    count = 0
    for row in range(len(anyList)):
        for i in range(len(anyList[row])):
            if anyList[row][i].isdigit():
                count+= 1
    return count

def countWhiteSpace(anyList):
    count = 0
    for row in range(len(anyList)):
        for i in range(len(anyList[row])):
            if anyList[row][i].isspace():
                count+= 1
    return count

main()



8. Sentence Capitalizer
Write a program with a function that accepts a string as an argument and returns a copy of the string with the first character of each sentence capitalized. For instance, if the argument is “hello. my name is Joe. what is your name?” the function should return the string “Hello. My name is Joe. What is your name?” The program should let the user enter a
string and then pass it to the function. The modified string should be displayed.

answer :- 


getSentence = input("Enter the sentence : ")

i = 0
while i < len(getSentence):
    if i == 0:
        print(getSentence[i].upper(),end="")
    elif getSentence[i] == '.':
        print(". ",end="")
        print(getSentence[i + 2].upper(),end="")
        i += 2
    else:
        print(getSentence[i],end="")
    i += 1


9. Vowels and ConsonantsWrite a program with a function that accepts a string as an argument and returns the number of vowels that the string contains. The application should have another function that accepts a string as an argument and returns the number of consonants that the string contains. The application should let the user enter a string and should display the number of vowels and the number of consonants it contains.

answer :- 


def main():

    getString = input("Enter the string : ")
    print("counting number of vowel letters in given string....")
    totalVowels = vowelCount(getString)
    print("number if vowel letters :",totalVowels)
    print()
    print("counting number of consonants letters in given string....")
    totalconsonants = consoCount(getString)
    print("number if vowel letters :",totalconsonants)

def vowelCount(string):
    count = 0
    string1 = string.upper()
    for ch in string1:
        if ch == "A" or ch == "E" or ch == "I" or \
           ch == "O" or ch == "U":
            count += 1
    return count

def consoCount(string):
    count = 0
    for ch in string:
        if ch.isalpha():
            count += 1
    totalConsonants = count - vowelCount(string)
    return totalConsonants
main()


10. Most Frequent Character
Write a program that lets the user enter a string and displays the character that appears most frequently in the string.

answer :- 
(Not a good solution. good one will be updated)

def main():

    string = input("Enter the string : ")
    charList = []
    occurList = []
    for ch in string:
        count = 0
        for i in range(len(string)):
            if ch == string[i]:
                count += 1
        if ch in charList:
            charList
            occurList
        else:
            charList.append(ch)
            occurList.append(count)
    print("character list : ",charList)
    print("corresponding occurance list :",occurList)
    print()
    mostfreChar = maxOccur(occurList,charList)
    if mostfreChar == " ":
        print(" most frequent character : space ")
    else:
        print(" most frequent character :", mostfreChar)
        


def maxOccur(list1,list2):
    largest = 0
    for i in range(len(list1)):
        find_lar = int(list1[i])
        if(largest <= find_lar):
            largest = find_lar
     
    for i in range(len(list1)):
        find_position = int(list1[i])
        if(find_position == largest):
            return list2[i]
        
main()



11. Word Separator
Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string “StopAndSmellTheRoses.” would be converted to “Stop and smell the  roses.”

answer :- 


getSentence = input("Enter the sentence without space : ")

uppLists = []
stringList = []
print("sentence before separate: ",getSentence)
for i in range(len(getSentence)):
    if getSentence[i].isupper():
        uppLists.append(i)
uppLists.append(len(getSentence))

i = 0
while i <  len(uppLists) - 1:
    startLimit = int(uppLists[i])
    endLimit = int(uppLists[i + 1])
    stringList.append(getSentence[startLimit : endLimit])
    i += 1
print("sentence after separated: ",end = "")
for i in range(len(stringList)):
    if i == 0:
        print(stringList[i]+' ',end="")
    else:
        print(stringList[i].lower() + " ",end="")



12. Pig Latin
Write a program that accepts a sentence as input and converts each word to “Pig Latin.” In one version, to convert a word to Pig Latin you remove the first letter and place that letter at the end of the word. Then you append the string “ay” to the word. Here is an example:
English: I SLEPT MOST OF THE NIGHT
Pig Latin: IAY LEPTSAY OSTMAY FOAY HETAY IGHTNAY

answer :- 


getSentence = input("Enter the string : ")


lists = getSentence.split()

print("English :",getSentence)

print("Pig Latin : ",end="")
for i in lists:
    newString = i[1:len(i)] +\
                i[0]+"AY"
    print(newString.upper(),end=" ")





From the tutorials,
Task 1 
Create a single text file in IDLE named serverConnections.txt. This file stores a list of host names and the number of connections for each server for a particular month of the year, one line per server. For example, the serverConnections.txt might look like the following (you may extend this file or create a completely new one consisting at least of 10 lines of data). According to this file www.melbourne.edu.au had 1245 while www.athens.org.gr had 6754 connections for a particular month that the file refers to.

 www.melbourne.edu.au                 1245
 www.famagusta.com                      457
 www.athens.org.gr                         6754
 www.istanbul.com.tr                      2980
 ….

Task 2 
Write a menu driven Python program with the following functionality:
 • When run, the program first opens the serverConnections.txt file for reading, reads the contents line by line and creates a list of lists (say serverConnectionsList), each small list in the big one being a list of two elements, corresponding to a server name and the number of connections for that server (for more information on how to do this, Page 2 of 2 refer to the hint given at the end of this document). It then repeatedly displays a menu with 5 options:
         1. Get server connections
         2. Find busiest server
         3. Add new server
         4. Backup files
         5. Quit program 

When option 1 is selected, program asks the user to enter the server name, searches for the server name and if it finds it, it returns the number of connections for that particular server. If it doesn’t find it, it returns a message stating that the server doesn’t exist in the file (or some message like “unknown server”).

 • When option 2 is selected, program finds the largest connections value and then it returns the corresponding server.

 • When option 3 is selected, program prompts the user for a new server name and the corresponding number of connections and then adds the server name and the corresponding number of connections at the end of serverConnections.txt file and also updates the list of lists created initially when the program was first executed (serverConnectionsList).

 • When option 4 is selected, program opens a text file named serversConnectionsBKUP.txt for writing and then copies the contents of serverConnections.txt to it.

 • When option 5 is selected, the program terminates.

[Hint: when the file is being read line by line in order to create the list of lists, you should remove the newline character from each line before splitting it using the split() function. This can be done by either using the stringVariableName.rstrip(“\n”) or stringVariableName[:-1]. Remember that these methods do not (in fact cannot) modify the original line string. They just produce a new one without the newline character which can then be used with the split() function to produce a list to be added to the list of lists]

answer:-


def main():

    file_variable = open("servers.txt" , "r")
    listOFlist = []
    for line in file_variable:
        line = line.rstrip('\n')
        mylist = line.split()
        listOFlist.append(mylist)
    choice = menu()
    while choice != '5':
        if choice == '1':
            serverName = input("Enter the server name : ")
            connections = findOfServer(serverName,listOFlist)
            if connections == " ":
                print(" server not found ")
            else:
                print("NUmber of Connection for server",serverName,"is",connections)
        elif choice == '2':
            busyServer = busiestServer(listOFlist)
            print("busiest server is",busyServer)
        elif choice == '3':
            serverName = input("Enter new server you want to add : ")
            connections = int(input("Enter the number of connection: "))
            addServer(serverName , connections , listOFlist )
            print("server added to the files")
        elif choice == '4':
            backupFile()
            print("Backing Files up...")
            print("Backed up")
        else :
            print("Invalid input")
            print("Enter number between 1 and 5")
        choice = menu()
    if(choice == '5'):
       print("program terminated") 
        

def findOfServer(serverName,listOFlist):
    for i in range(len(listOFlist)):
        for j in range(len(listOFlist[i])):
            if(listOFlist[i][j] == serverName):
                return listOFlist[i][j+1]
    return " "
        
        
    

def addServer(serverName , connections , listOFlist):
    file_variable = open("servers.txt","a")
    file_variable.write( serverName + '\t' + str(connections) + "\n")
    file_variable.close()
    #to add those records in list as well
    appendList = [serverName , connections]
    listOFlist.append(appendList)
    
def busiestServer(listOFlist):
    largest = 0
    for i in range(len(listOFlist)):
        find_lar = int(listOFlist[i][1])
        if(largest <= find_lar):
            largest = find_lar
    for i in range(len(listOFlist)):
        find_server = int(listOFlist[i][1])
        if(find_server == largest):
            return listOFlist[i][0]
                
    
    

def backupFile():
    file_variable = open("servers.txt","r")
    file_backupServer = open("serversBACKUP.txt" , 'w')
    for line in file_variable:
        line = line.rstrip('\n')
        file_backupServer.write(line + '\n')
    file_backupServer.close()
    file_variable.close()
def menu():
    print("The main menu")
    print("----------------")
    print("1.Find server Conncetions")
    print("2.Find busiest server ")
    print("3.Add new server")
    print("4.Backup files")
    print("5.Quiet program")
    print("----------------------------")
    option = input("Enter your selection (1 - 5 ) : ")
    return option
main()


 From the exam,

Write a program which has two functions, main() and maximum(), with the following specifications:

 • In the main() function, opens a text file named visitors.txt, which contains data relating to number of visitors of several websites (structure and content of the file is given below)

 • Reads the contents of the file, line by line and builds a list of lists, each small list containing one line of data as two strings split from one line of data from the file (call this list visitorsList)

 • Invokes the maximum() function from main(), passing the list visitorsList as the only argument

 • The maximum()function uses the visitorsList to find the website with the maximum number of visitors and returns this value to the main()

 • The main()gets the maximum number of visitors returned from the maximum()function and displays it on the screen
 The structure and content of visitors.txt file:
      www.melbourne.com.au    5463
      www.roma.org.it                   7777
      www.famagusta.edu.cy      234
      www.athena.com.gr            8953
      www.newyork.com              3333
      www.swinburne.edu.au    17990
      www.istanbul.tr                    3786
      www.paris.com.fr                555
      www.larnaca.cy                    2534
      www.london.org.en            965

[Hint: For a complete solution, this program should use exception handling to detect and respond to invalid data from the file as well as possible errors occurring when attempting to open the file.]

answer:-

def main():
 try:
     visitors = open("visitors.txt", "r")
     visitorsList = []
     for line in visitors:
         lineList = (line.rstrip()).split()
         visitorsList.append(lineList)
     max = maximum(visitorsList)
     print("The maximum number of visitors is", max)
 except ValueError:
     print ("Error: Invalid input data!")
 except IOError:
     print ("Error: unable to open file!")
 except:
     print ("An error occurred!")

def maximum(visitorsList):
    largest = 0
    for i in range(len(visitorsList)):
        find_lar = int(visitorsList[i][1])
        if(largest <= find_lar):
            largest = find_lar
    return largest
    
main()    

  i will post  chapter 11(Classes and Object-Oriented Programming) very soon
    
    

Introduction To Network Programming - Data Structures: Strings and Lists


Hi,
In this post i attached my lecture 5 which describes chapter 8,9. Here i am going to post practice questions for chapter 8.

here, you can find the lecture slides,


Programming exercises
you can find these exercise questions at the end of the chapter 8 in this book.



1. Total Sales
Design a program that asks the user to enter a store’s sales for each day of the week. The amounts should be stored in a list. Use a loop to calculate  the  total  sales  for  the  week and 

display the result.

answer :-

saleList = []
print("store's sales for each day of the week ")

for i in range(7):
    print("store sale of the day",(i + 1),": $",sep="",end="")
    storeSale = float(input(""))
    saleList.append(storeSale)
    
print("saleList : ",end="")
print(saleList)

print("calculating the total sales for the week....")
total = 0

for element in saleList:
    total += element
    
print("total sales for the week : $",format(total,',.2f'),sep="")

2. Lottery Number Generator
Design a program that generates a seven-digit lottery number. The program should generate seven random numbers, each in the range of 0 through 9, and assign each number to a list element. Then write another loop that displays the contents of the list.

answer :-

import random
lotteryList = []

print("assigning the lottery numbers to the list.....")
for i in range(7):
    lotteryNumber = random.randint(0,9)
    lotteryList.append(lotteryNumber)

print("lottery numbers are assigned to the list.....")
print("represting the lottery number....")
print("contents of the list : ",end="")
print("[ ",end="")
for element in lotteryList:
    print(element ,end="")
print(" ]")

3. Rainfall Statistics
Design a program that lets the user enter the total rainfall for each of 12 months into a list. The program should calculate and display the total rainfall for the year, the average monthly rainfall, and the months with the highest and lowest amounts.

answer :-

rainfallList = []
print("store the rainfall for each month of the year ")
for i in range(12):
    print("rainfall of the month ",(i + 1),": ",sep="",end="")
    storeRainfall = float(input(""))
    rainfallList.append(storeRainfall)
print("saleList : ",end="")
print(rainfallList)

print("calculating the total and average rainfall for the year....")
total = 0
for element in rainfallList:
    total += element
averageRainfall = total / 12
print("total rainfall for the year : ",format(total,',.2f'),sep="")
print("average rainfall for the year : ",format(averageRainfall,',.2f'),sep="")
print("highest railfall of the year : ",max(rainfallList))
print("lowest railfall of the year : ",min(rainfallList))

4. Number Analysis Program
Design a program that asks the user to enter a series of 20 numbers. The program shouldstore the numbers in a list and then display the following data:

• The lowest number in the list
• The highest number in the list
• The total of the numbers in the list
• The average of the numbers in the list

answer :-

numberslList = []
print("store the 20 numbers in a list ")
for i in range(20):
    print("Enter the number ",(i + 1),": ",sep="",end="")
    numbers = float(input(""))
    numberslList.append(numbers)
print("numberslList : ",end="")
print(numberslList)

print("finding the lowest,highest,total and average of the list....")
total = 0
for element in numberslList:
    total += element
averageNumbers = total / 20
print("The lowest number in the list :",min(numberslList))
print("The highest number in the list :",max(numberslList))
print("The total of the numbers in the list : ",format(total,',.2f'),sep="")
print("The average of the numbers in the list : ",format(averageNumbers,',.2f'),sep="")

5. Charge Account ValidationIf you have downloaded the source code from this book’s companion Web site, you will find a file named charge_accounts.txt in the Chapter 08 folder. This file has a list of a company’s valid charge account numbers. Each account number is a seven-digit number, such as 5658845.

Write a program that reads the contents of the file into a list. The program should then ask the user to enter a charge account number. The program should determine whether the number is valid by searching for it in the list. If the number is in the list, the program should display a message indicating the number is valid. If the number is not in the list, the program should display a message indicating the number is invalid.

answer :-

accountList = []
file_vari = open("charge_accounts.txt","r")
for i in file_vari:
    j = i.rstrip("\n")
    accountList.append(j)

file_vari.close()
print("accountList = ",end="")
print(accountList)
accountCheck = input("Enter the charge account number : ")
if accountCheck in accountList:
    print("account number that you entered is valid")
else:
    print("account number that you entered isnot valid")

6. Driver’s License Exam
The local driver’s license office has asked you to create an application that grades the written portion of the driver’s license exam. The exam has 20 multiple-choice questions. Here are the correct answers:

1. B      6. A       11. B       16. C
2. D      7. B       12. C       17. C
3. A      8. A       13. D      18. B
4. A      9. C       14. A      19. D
5. C      10. D     15. D      20. A

Your program should store these correct answers in a list. The program should read the student’s answers for each of the 20 questions from a text file and store the answers in another list. (Create your own text file to test the application.) After the student’s answers have been read from the file, the program should display a message indicating whether the student passed or failed the exam. (A student must correctly answer 15 of the 20 questions to pass the exam.) It should then display the total number of correctly answered questions, the total number of incorrectly answered questions, and a list showing the question numbers of the incorrectly answered questions.

answer :-

canswer = []
sanswer = []
file_vari = open("canswer.txt","r")
for i in file_vari:
    j = i.rstrip("\n")
    canswer.append(j)

file_vari.close()

file_vari1 = open("sanswer.txt","r")
for i in file_vari1:
    j = i.rstrip("\n")
    sanswer.append(j)

file_vari1.close()
print(canswer)
print(sanswer)


print("student result is : ")
i = 0
j = 0
for k in range(len(canswer)):
    if (canswer[k] == sanswer[k]):
        i += 1
    else:
        j += 1
print("correct answer is ",i,"out of",len(canswer))

print("incorrect answer is ",j,"out of",len(canswer))

7. Name Search
If you have downloaded the source code from this book’s companion Web site, you will find the following files in the Chapter 08 folder:


• GirlNames.txt—This file contains a list of the 200 most popular names given to girls
born in the United States from the year 2000 through 2009.
• BoyNames.txt—This file contains a list of the 200 most popular names given to boys
born in the United States from the year 2000 through 2009.


Write a program that reads the contents of the two files into two separate lists. The user should be able to enter a boy’s name, a girl’s name, or both, and the application will display messages indicating whether the names were among the 
most popular.

answer :-

girlList = []
boyList = []
file_vari = open("GirlNames.txt","r")
for i in file_vari:
    j = i.rstrip("\n")
    girlList.append(j)

file_vari.close()

file_vari1 = open("BoyNames.txt","r")
for i in file_vari1:
    j = i.rstrip("\n")
    boyList.append(j)

file_vari1.close()
print("Girl List = ",end ="")

print(girlList)
print()
print()
print("Boy List = ",end ="")
print(boyList)

girlName = input("Enter the girl name : ")
boyName = input("Enter the boy name : ")

if girlName != "":
    if girlName in girlList:
        print("the girl that you entered is valid in the list")
    else:
        print("the girl that you entered isnot valid in the list")
else:
    print("you didnot enter the girl name")

if boyName != "":
    if boyName in boyList:
        print("the boy that you entered is valid in the list")
    else:
        print("the boy that you entered isnot valid in the list")
else:

    print("you didnot enter the boy name")


8. Population Data
If you have downloaded the source code from this book’s companion Web site, you will find a file named USPopulation.txt in the Chapter 08 folder. The file contains the midyear population of the United States, in thousands, during the years 1950 through 1990. The first line in the file contains the population for 1950, the second line contains the population for 1951, and so forth. Write a program that reads the file’s contents into a list. The program should display the following data:

• The average annual change in population during the time period
• The year with the greatest increase in population during the time period
• The year with the smallest increase in population during the time period

answer :-


populaionList = []

file_vari = open("USPopulation.txt","r")
for i in file_vari:
    j = i.rstrip("\n")
    populaionList.append(j)

file_vari.close()
print("pupulation List(1950 - 1990) = ",end="")
print(populaionList)

total = 0
for element in populaionList:
    convertElement = int(element)
    total += convertElement
averagePopulation = total / len(populaionList)
print("average annual change in population(1950 -1990) : ",format(averagePopulation,',.2f'))
print("year with greatest increase in population(1950 -1990) : ",max(populaionList))
print("year with smallest increase in population(1950 -1990) : ",min(populaionList))


9. World Series Champions
If you have downloaded the source code from this book’s companion Web site, you will find a file named WorldSeriesWinners.txt in the Chapter 08 folder. This file contains a chronological list of the World Series winning teams from 1903 through 2009. (The first line in the file is the name of the team that won in 1903, and the last line is the name of the team that won in 2009. Note that the World Series was not played in 1904 or 1994.) Write a program that lets the user enter the name of a team and then displays the number of times that team has won the World Series in the time period from 1903 through 2009.

answer :-


winnersList = []
file_vari = open("WorldSeriesWinners.txt","r")
for i in file_vari:
    j = i.rstrip("\n")
    winnersList.append(j)

file_vari.close()
print("Winners List(1903 - 1994) = ",end="")
print(winnersList)

print("finding how many time a team won during 1903 - 1994")
teamName = input("Enter the team name : ")
count = 0
for i in winnersList:
    if teamName == i:
        count += 1
print("team name :",teamName)

print("Nuber of time they won during 1903 - 2009 :",count)


i will post chapter 9 very soon..