Question

Add high level comments throughout the program to explain what each line of code does. Finally,...

 Add high level comments throughout the program to explain what each line of code does. Finally, use a diagramming tool (Visio, Lucidchart, MSPaint, paper & pen) to create a flowchart of the code below. 

path = "/Users/user1/data/baby_names/"
myyear = input("Please provide the year to be searched:")
babyname = input("Please provide the baby name to be searched:")
babyname = babyname.capitalize()

baby_counts = count_babies(myyear, babyname)

print("There were {0} boys and {1} girls with that name in {2}".format(
    baby_counts[0], 
    baby_counts[1], 
    myyear))

def count_babies(year, baby):

    file = "yob" + year + ".txt"
    bnames = []

    if file not in os.listdir(path):
        print("These are not the files you are looking for, move along")
        return 0
    else:
        f = open(path + file)
        f.readline()
        
        for each in f:
            fields = each.split(',')
            bnames.append(fields)
        f.close()
        print("Imported " + file)

        mcount = 0
        fcount = 0
        for fields in bnames:
            if baby in fields[0]:
                if 'M' in fields[1]:
                    mcount = int(fields[2])
                else:
                    fcount = int(fields[2])

        return [mcount, fcount]
0 0
Add a comment Improve this question Transcribed image text
Answer #1

path = "/Users/user1/data/baby_names/" #its path where all files of baby names stored
myyear = input("Please provide the year to be searched:") #take input from user of the year to be searched
babyname = input("Please provide the baby name to be searched:") # take name from the user to be search in the above path database
babyname = babyname.capitalize() #whatever name has entered by the user it will be stored in the variable babyname and that will be capitalize because all the names
# in the path files have all capital names

baby_counts = count_babies(myyear, babyname) #baby_counts is a variable and count_babies is a function with parameters of year and babyname that is taken from the user

print("There were {0} boys and {1} girls with that name in {2}".format(
baby_counts[0],
baby_counts[1],
myyear))

def count_babies(year, baby): #the user's input will bring here

file = "yob" + year + ".txt" # year of birth + year + txt file extension so eg yob2018.txt where 2018 is the entered by the user
bnames = [] #empty array of bnames

if file not in os.listdir(path): #if yob2018.txt not found on the path then it will print below message
print("These are not the files you are looking for, move along")
return 0
else:
f = open(path + file) #else open the file which is on that file will be opened with file object f
f.readline() # file object with f will read all the lines inside the file
  
for each in f: #there will be names with comma seprated values will be split and append all baby names in the bnames array which is created above
fields = each.split(',') #if , comma found execute below line
bnames.append(fields) # append will store all names without loosing any name
f.close() #at last file will be closed
print("Imported " + file) #print msg with imported and file name

mcount = 0 #variable are initialized with 0
fcount = 0
for fields in bnames: #now bnames have all the names with male female names
if baby in fields[0]:
if 'M' in fields[1]:# if names have the M fields then mcount will be incremented by 1 else fcount will be increment
mcount = int(fields[2])
else:
fcount = int(fields[2])

return [mcount, fcount] #from here it will return the number of male and female names to the baby_counts variable above

if you have any doubt then please ask me without any hesitation in the comment section below , if you like my answer then please thumbs up for the answer , before giving thumbs down please discuss the question it may possible that we may understand the question different way and we can edit and change the answers if you argue, thanks :)

Add a comment
Know the answer?
Add Answer to:
Add high level comments throughout the program to explain what each line of code does. Finally,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • python programming: Can you please add comments to describe in detail what the following code does:...

    python programming: Can you please add comments to describe in detail what the following code does: import os,sys,time sl = [] try:    f = open("shopping2.txt","r")    for line in f:        sl.append(line.strip())    f.close() except:    pass def mainScreen():    os.system('cls') # for linux 'clear'    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print(" SHOPPING LIST ")    print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")    print("\n\nYour list contains",len(sl),"items.\n")    print("Please choose from the following options:\n")    print("(a)dd to the list")    print("(d)elete from the list")    print("(v)iew the...

  • Can you add code comments where required throughout this Python Program, Guess My Number Program, and...

    Can you add code comments where required throughout this Python Program, Guess My Number Program, and describe this program as if you were presenting it to the class. What it does and everything step by step. import random def menu(): #function for getting the user input on what he wants to do print("\n\n1. You guess the number\n2. You type a number and see if the computer can guess it\n3. Exit") while True: #using try-except for the choice will handle the...

  • Provide comments for this code explaining what each line of code does import java.util.*; public class...

    Provide comments for this code explaining what each line of code does import java.util.*; public class Chpt8_Project {    public static void main(String[] args)       {        Scanner sc=new Scanner(System.in);        int [][]courses=new int [10][2];        for(int i=0;i<10;i++)        {            while(true)            {                System.out.print("Enter classes and graduation year for student "+(i+1)+":");                courses[i][0]=sc.nextInt();                courses[i][1]=sc.nextInt();                if(courses[i][0]>=1...

  • I am having trouble with my Python code in this dictionary and pickle program. Here is...

    I am having trouble with my Python code in this dictionary and pickle program. Here is my code but it is not running as i am receiving synthax error on the second line. class Student: def__init__(self,id,name,midterm,final): self.id=id self.name=name self.midterm=midterm self.final=final def calculate_grade(self): self.avg=(self.midterm+self.final)/2 if self.avg>=60 and self.avg<=80: self.g='A' elif self.avg>80 and self.avg<=100: self.g='A+' elif self.avg<60 and self.avg>=40: self.g='B' else: self.g='C' def getdata(self): return self.id,self.name.self.midterm,self.final,self.g CIT101 = {} CIT101["123"] = Student("123", "smith, john", 78, 86) CIT101["124"] = Student("124", "tom, alter", 50,...

  • I need help with this C code Can you explain line by line? Also can you...

    I need help with this C code Can you explain line by line? Also can you explain to me the flow of the code, like the flow of how the compiler reads it. I need to present this and I want to make sure I understand every single line of it. Thank you! /* * Converts measurements given in one unit to any other unit of the same * category that is listed in the database file, units.txt. * Handles...

  • #Practical Quiz 3 #Add a comment above each line of code describing what it does. #Be...

    #Practical Quiz 3 #Add a comment above each line of code describing what it does. #Be specific. Use multiple comment lines if you need to #OR write code below the comments requesting code. #Make sure your file runs and generates the correct results. def main(): #define variable str1 with string "Hello" str1 = "Hello" #print out the 2nd letter print(str1[1]) #START QUIZ HERE print(str1[-2]) print(str1[:3]) print(str1[2:len(str1)-1]) str2 = "World" print(str1+str2) #write code below to iterate over the str1 and print...

  • Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text...

    Objective: Use input/output files, strings, and command line arguments. Write a program that processes a text file by removing all blank lines (including lines that only contain white spaces), all spaces/tabs before the beginning of the line, and all spaces/tabs at the end of the line. The file must be saved under a different name with all the lines numbered and a single blank line added at the end of the file. For example, if the input file is given...

  • Throughout this script, can you provide helpful comments about how each function works in the script...

    Throughout this script, can you provide helpful comments about how each function works in the script plus it's significance to the alignment process. Also are there any errors in this script or a way to improve this script? Any help would be appreciated. Thank you. THIS IS A PYTHON CODE AND IS IN IT'S FORMAT _ ITS CLEAR! #!/usr/bin/env python # file=input("Please provide fasta file with 2 sequences:") match=float(input('What is the match score?:')) missmatch=float(input('What is the missmatch score?:')) gap=float(input('What is...

  • Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - dis...

    Explain what the code is doing line from line explanations please or summarize lines with an explanation def displayCart(): #displays the cart function """displayCart function - displays the items in the cart ---------------------------------------------------------------------""" import os os.system('clear') print("\n\nCart Contents:") print("Your selected items:", cart) def catMenu(): #function that displays the category menu """catMenu function - displays the categories user picks from ---------------------------------------------------------------------""" import os os.system('clear') print(""" 1 - Books 2 - Electronics 3 - Clothing d - display cart contents x -...

  • Edit a C program based on the surface code(which is after the question's instruction.) that will...

    Edit a C program based on the surface code(which is after the question's instruction.) that will implement a customer waiting list that might be used by a restaurant. Use the base code to finish the project. When people want to be seated in the restaurant, they give their name and group size to the host/hostess and then wait until those in front of them have been seated. The program must use a linked list to implement the queue-like data structure....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT