(PYTHON) In completing this task, you will need to use the following constructs:
ID: 3672104 • Letter: #
Question
(PYTHON)
In completing this task, you will need to use the following constructs:
1. IF / ELSE statements
2. Compound logic (i.e. "and" / "or")
3. WHILE loops
4. File processing
In this task, you will use WHILE loops print N names from the supplied file "first_names.txt". Here is the basic algorithm:
1. Open first_names.txt for reading (file reading template that we use in class)
2. While the user has not entered a number that is between 0 and 50 (the number of names in the file): a. Prompt the user for a number b. Let N = this number
3. Use a WHILE loop and compound logic to output the first N names in the file.
Here's my program's output:
Enter a value between 0 and 50: -100
Enter a value between 0 and 50: -1
Enter a value between 0 and 50: 100
Enter a value between 0 and 50: 51
Enter a value between 0 and 50: 5
Name at 0 : James
Name at 1 : John
Name at 2 : Robert
Name at 3 : Michael
Name at 4 : William
Explanation / Answer
def readFile():
inp = open ("first_names.txt","r")
n = 51
while n < 0 or n > 50 :
print "Enter a value between 0 and 50:"
n = input()
#read line into array
count = 0
for line in inp.readlines():
if count == n :
break
print "Name at",count," : ", line
count += 1
readFile()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.