Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write Python code: Write a program that reads a Python source file and prints ou

ID: 3804396 • Letter: W

Question

Write Python code:

Write a program that reads a Python source file and prints out the number of function definitions
found in the source file. The task is accomplished by counting how many times you detect the
reserved word def in a given file. Assume the input file is a valid Python program and does not
include any comments. Use this starter Python code:

def count_def(source):
    print(source) ## test print;

    return 10     ## MODIFY this

while True:
    filename = input("Python Source File: ")

    if filename == "": break

    file = open(filename, "r")

    source = file.read()

    def_cnt = count_def(source)

    print(def_cnt)

Explanation / Answer

import os
import sys
import numpy as np


filename =str(raw_input("enter file name"))
fr = open(filename,"r")
lines =fr.readlines()
count=0
for line in lines:
if "def" in line:
count+=1

print count

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote