Using python, write code for problem. The text file USPres.txt is used and i hav
ID: 3845753 • Letter: U
Question
Using python, write code for problem. The text file USPres.txt is used and i have put screenshot of contents of the file. Please also put screenshot of your code.
45. U.S. Presidents The file USPres.txt contains the names of the first 44 U.S. presi dents in the order they served. Write a program (without using a list) that requests a range of numbers and displays all presidents whose number is in that range. Figure 5.11 shows one possible outcome. Oohn Tyler was the tenth president, James Polk was the eleventh president, and so on.)Explanation / Answer
As you provided the Queston, I'm providing the following answer. From the question I'm not getting , from which pyhton version solution required. I verified this on Python 2.7
For this question we can solve in multiple ways, here I'm using Doctionary, because its internally uses hashing techiniques , so based on range it is simple for acces values random way.
1) I handled error handling for file oiperation
2) Handled the range mismatching
The code is as follows :
d = {}
try:
with open("USPres.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
except IOError:
print "Error: can't find file or read data"
lowRange = int(raw_input("Please enter the lower number for the range:"))
highRange = int(raw_input("Please enter the higher number for the range:"))
for key in xrange(lowRange,highRange):
print key, d[int(key)]
As a result , Output as you expected
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.