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
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.