Having issue printing out data i want to show - python

i was modifying a program that i was writing to make it so that it wont continue on unless they put in a input that matches a word thats stored in a list. however after i did that, it would not let me print out the data i have, here is the code
while True:
dept = input('what department are you in right now: ')
dept = dept.upper()
if dept not in department_storage:
print("not approriate response")
continue
else:
break
if dept in department_storage:
department_url = requests.get(f"https://api.umd.io/v0/courses?dept_id={dept}")
specific_major =department_url.json()
keep_keys = ["course_id"]
courses = [{k: json_dict[k] for k in keep_keys}
for json_dict in specific_major]
#return courses,dept
print(courses)
im trying to print out the courses variable, however when i try and run the function
it doesn't show the print output, and it doesn't show any errors when i run it so im lost on what i did wrong and how to fix it . i was wondering if i could ask the kind stack overflow community for help.

You may not be getting the output for multiple reasons: -
Did you enter an input? the interpreter may be waiting for a user input which has not been entered yet.
Maybe the dept not in department_storage is breaking the loop if its true. break gets you out of the loop.
courses is a null object, probably because the result you are getting has empty objects.
You can add import pdb; pdb.set_trace(); at various points in your code and write the variable names in the debugger to see the values. That will aid you in the investigation.
As per the requirement, my suggestion is the following code: -
while True:
dept = input('what department are you in right now: (type exit to quit)')
dept = dept.upper()
if dept == 'EXIT':
break
if dept not in department_storage:
print("this department does not exist, enter correct department")
else:
try:
department_url = requests.get(f"https://api.umd.io/v0/courses?dept_id={dept}")
specific_major =department_url.json()
keep_keys = ["course_id"]
courses = [{k: json_dict[k] for k in keep_keys}
for json_dict in specific_major]
print(courses)
except Exception as e:
print(e)

The break command forces to exit the while loop and stop taking inputs.
Try:
if dept in department_storage:
...
# if dept not in department_storage
else:
...

Related

I am trying to update my program to have some return values to make it more testable. Why is the one named other not returned usable in main?

I receive a NameError: name 'other' is not defined. Could someone give me an example and reasoning to point me in the right direction to help me out (so i don't screw up when adding return values to the rest of my program). I thought i understood them that's why I know i need help to get a better understanding. I almost forgot to mention i am entering a number to trigger the else clause when i get the error message regarding main code.
def yes_no(y_n):
other = 'invalid response'
if y_n == 'n':
index_person(address_dict)
elif y_n == 'y':
add_person()
else:
return other
def main():
#other = 'Invalid response'
while True:
#Hmmm..would the user like to add a new person the the address book or index it?
#Loop the address program until break.
try:
user_answer = input('Would you like to add a new person to the address book? y/n \n - ')
yes_no(user_answer)
if user_answer not in ['y','n']:
print(other)

having trouble implementing the right word to a url link

i have a program that asks users which department they want to choose from, i made the question into a while loop that would keep asking the same question until they put a valid response in. and whenever they wanted to break the loop they would type the word "exit". once they type in a valid response it would add ask another question in another function that would ask for the class your want info on based on the department you're in, it would then lead it to a website where i can get the information i need. the issue im facing is that it doesn't take the valid response that was typed in, it would instead implement the word "exit" which was used to break out of the loop as it was the last input. i want it to take the input before that and not "EXIT"
here is the code
def get_departments():
umd_departments = requests.get("https://api.umd.io/v0/courses/departments")
umd_departments_list = umd_departments.json()
umd_departments_list2 = json.dumps(umd_departments_list, indent=1)
department_storage = [department['dept_id'] for department in umd_departments_list]#comprehensive for loop to put the department ID into a list
print(department_storage)
while True:
dept = input('what department are you in right now: ')
dept = dept.upper()
if dept == 'EXIT':
break
if dept not in department_storage:
print("not approriate response")
else:
try:
department_url = requests.get(f"https://api.umd.io/v0/courses?dept_id={dept}")
specific_major =department_url.json()
keep_keys = ["course_id"]
courses = [{k: json_dict[k] for k in keep_keys}
for json_dict in specific_major]
print(courses)
except Exception as e:
print(e)
return courses,dept
def get_classes(courses):
classes = [course['course_id'] for course in courses]
print(classes)
course_select = input('what class would you like to select').upper()
if course_select not in classes:
raise ValueError(" class does not exist")
else:
driver = webdriver.Chrome(ChromeDriverManager().install())
url = f"https://app.testudo.umd.edu/soc/202008/{dept}"
driver.get(url)
section_container = driver.find_element_by_id(f"{course_select}")
section_container.find_element_by_xpath(".//a[#class='toggle-sections-link']").click()# it would click on the show section button on the site that would reveal the sections
sleep(1)
section_info = section_container.find_element_by_xpath(".//div[#class='sections sixteen colgrid']").text
return section_info
let's say for example in the get departments function i type in INST and its considered a valid response, it would then ask for which class i want to choose from that department. it would then create a url that would get me the info i need like this:
https://app.testudo.umd.edu/soc/202008/INST
however i get this:
https://app.testudo.umd.edu/soc/202008/EXIT
the latter doesn't produce anything as it doesn't exist and it causes errors. is there a way to make it so that it doesn't make the "EXIT" input stored into a valuable and instead takes the valid response before it? greatly appreciated if anyone could help.
Looks like you just need another variable
userInput = input('what department are you in right now: ')
userInput = userInput.upper()
if userInput == 'EXIT':
break
else:
dept = userInput

Python infinite while loop issue

I am trying to make a script that asks for user input in Python, it is supposed to error with the response "Please enter first name", and then return the user back to the initial input question prompt.
This isn't working, instead after asking for both the first and last name if no name is given for both I am thrown into an infinite loop of the first error.
# User input for first name
first_name = input('Enter FIRST name here: ')
# User input for last name
last_name = input('Enter LAST name here: ')
def print_name():
# store user input in separate variable
fname = first_name
lname= last_name
while True:
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()
Please can someone help me understand whats going wrong here? It should only loop back to asking for a first name (or last name) when nothing is given, other wise it should print the users name to console. both names should be given too, if first name is not given then id expect an error in the first while loop, like wise if last name is not given.
Also is there a better way to do this? using 2 while loops seems wrong?
Don't repeat yourself. If you copy and paste a section of code, stop and think. It should either be a function, or a loop.
def wait_for_input(prompt):
data = ""
while data == "":
data = input(prompt).strip()
return data
def print_name(fname, lname):
print(f'your name is {fname} {lname}')
first_name = wait_for_input('Enter FIRST name: ')
last_name = wait_for_input('Enter LAST name: ')
print_name(first_name, last_name)
Also, don't use comments to repeat what the code says.
The issue is with your infinite loops, you can simplify your function like:
def print_name():
first_name = ""
last_name = ""
# User input for first name
while first_name == "":
first_name = input('Enter FIRST name here: ')
# User input for last name
while last_name == "":
last_name = input('Enter LAST name here: ')
print(f'your name is {first_name} {last_name}')
I have the impression you are new at this:
While-loops generally look as follows:
while <condition>
...
<check_condition>
...
This means that in most cases, at every time the loop is executed, the condition is re-calculated and checked again by the while.
In your case, this would become something like:
while (len(fname) == 0)
<show_error_message>
<get fname again>
The case you have written here (while true) also exists and is used regularly, but in very different cases, like in multi-threaded event-based programs:
while true
<get_event>
This means that a part of the program (a so-called thread) is waiting for an event (like a buttonclick) to be catched and then something happens. This, however, is mostly done in multi-threaded applications, which means that the "main" program is doing something, while a subprogram is handling the events, which are coming in.
I am not fully understanding why you need so many loops. Something like this should do:
def print_name():
fname = input('Enter FIRST name here: ')
if len(fname) == 0:
raise Exception('No FIRST name entered...')
lname= input('Enter LAST name here: ')
if len(lname) == 0:
raise Exception('No LAST name entered...')
print(f"your name is {fname} {lname}")
And if all you wanted is to repeat this loop all you need to do is nest your print_name() function in a loop.
EDIT: Now that I seen other answers, I believe #Tomalak answer is better, was not getting what you really wanted.
Try this code:
def print_name():
# store user input in separate variable
first_name = input('Enter FIRST name here: ')
fname = first_name
while True:
fname = first_name
# throw error if user enters no first name
if len(fname) == 0:
# error msg
print('No FIRST name entered...')
first_name = input('Enter FIRST name here: ')
# loop back to prompt asking for first name
continue
else:
# if first name given move on to prompting for last name
# break loop
break
# loop into prompting user for last name
while True:
last_name = input('Enter LAST name here: ')
lname= last_name
# throw error if user enters no last name
if len(lname) == 0:
print('No LAST name entered...')
# loop back to prompt asking for last name
continue
else:
# if last name given move on to running print command
# break loop
break
return fname, lname
print(f'your name is {fname} {lname}')
print_name()

List in python will only return the first line

I have two lists in separate text files, "messages" and "codes". My program will open them and read them. My program is a code redeemer that will take a code and redeem it for a message.
lstCodes = open("codes.txt").readlines()
lstMessages = open("messages.txt").readlines()
I take in a user input as the code with the following class.
class DateCheck:
def __init__(self, date1):
self.date1 = date1
if date1 == datetime.date(xxxx,x,xx):
print('Correct! \n')
checkx = input('Are you ready to type in your final secret code? YES = 1, NO = 0: \n')
dcodex = input("Enter Code: \n")
#progressB=progress(50,.04)
LoopCheck(checkx, dcodex)
else:
print('Wrong code')
Once it asks for the user to input the code it passes it to another class that will look for that code in the text file and if found return the message from messages.txt.
class LoopCheck:
def __init__(self, check, code):
self.check = check
self.code = code
if code in lstCodes:
print(lstMessages[lstCodes.index(code)])
else:
print("Wrong Code")
And heres the issue, it will only work with the first code in code.txt and the first message in message.txt. When I input the correct code2 it returns "Wrong". I've tried looking at how I'm reading the lists but I can't figure out what I'm doing wrong. I'm sure it's a small mistake but I haven't been able to figure it out.
#messages.txt
message1
message2
#codes.txt
xxxx
xxxx
Best would be to use a dictionary:
codes = {}
with open("codes.txt") as cod_fobj, open("messages.txt") as mess_fobj:
for code, mess in zip(cod_fobj, mess_fobj):
codes[code.strip()] = mess.strip()
Now:
>>>> codes['code1']
'message1'
The check could look like this:
if code in codes:
print(codes[code])
else:
print("Wrong Code")
Or:
try:
print(codes[code])
except KeyError:
print("Wrong Code")
I think I figured out what was wrong. I changed the formatting on codes.txt to:
#codes.txt
xxxx, xxxx, xxxx
I also changed lstCodes = open("codes.txt").readlines() to lstCodes = open("codes.txt").read().split(',')so now when I look for the code in code.txt it returns its index and then I look up the index number on messages.txt and return the message associated with it.

Having trouble parsing a txt file into a list full of zip codes in my zipcode lookup program

Hello everyone thanks for looking into my problem. What I am trying to do is write a "Structured" program in python that takes txt from a file and parses it into lists. Then after closing the file, I need to reference the user input (zipcode) in those lists and then print out the city and state according to the zipcode that they entered. My instructor is having us use structure by making several functions. I know there are probably lots of more efficient ways of doing this, but I must keep the structure thats in place.
EDIT
Here is my code(Current):
#-----------------------------------------------------------------------
# VARIABLE DEFINITIONS
eof = False
zipRecord = ""
zipFile = ""
zipCode = []
city = []
state = []
parsedList = []
#-----------------------------------------------------------------------
# CONSTANT DEFINITIONS
USERPROMPT = "\nEnter a zip code to find (Press Enter key alone to stop): "
#-----------------------------------------------------------------------
# FUNCTION DEFINITIONS
def startUp():
global zipFile
print "zipcode lookup program".upper()
zipFile = open("zipcodes.txt","r")
loadList()
def loadList():
while readRecord():
pass
processRecords()
def readRecord():
global eof, zipList, zipCode, city, state, parsedList
zipRecord = zipFile.readline()
if zipRecord == "":
eof = True
else:
parsedList = zipRecord.split(",")
zipCode.append(parsedList[0])
city.append(parsedList[1])
state.append(parsedList[2])
eof = False
return not eof
def processRecords():
userInput = raw_input(USERPROMPT)
if userInput:
print userInput
print zipCode
if userInput in zipCode:
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
def closeUp():
zipFile.close()
#-----------------------------------------------------------------------
# PROGRAM'S MAIN LOGIC
startUp()
closeUp()
raw_input("\nRun complete. Press the Enter key to exit.")
Here is a sample from the zipcode txt file:
00501,HOLTSVILLE,NY
I am definitely stuck at this point and would appreciate your help in this matter.
EDIT
Thanks for all the help everyone. I really do appreciate it. :)
why you fill the lists zipcode, city , state like that, i mean in each user entry we get the next line from the file
i think that you should do :
def loadList():
# Fill all the list first , make the readRecord() return eof (True or False).
while readRecord():
pass
# than process data (check for zip code) this will run it only one time
# but you can put it in a loop to repeat the action.
processRecords()
about your problem :
def processRecords():
userInput = raw_input(USERPROMPT)
# Check if a user has entered a text or not
if userInput:
# check the index from zipcode
if userInput in zipcode:
# the index of the zipcode in the zipcode list is the same
# to get related cities and states.
index_ = zipcode.index(userInput)
print "The city is %s and the state is %s " % \
(city[index_], state[index_])
else:
print "\nThe zip code does not exist."
else:
print "Please enter a data"
one of the beauties of Python is that it's interactive. if you take processRecords() out of loadList(), and then at the bottom of your program put:
if __name__ == '__main__':
processRecords()
Then, from the command prompt, type "python". You'll get the Python shell prompt, ">>>". There you type:
from zipcodes import * # this assumes your program is zipcodes.py
dir() # shows you what's defined
print zipCode # shows you what's in zipCode
that ought to help debugging.
Strings don't have an append method like lists do. What I think you're trying to do is append the strings zipCode, city, and state to parsedList. This is the code you'd use to do that:
parsedList.append(zipCode)
parsedList.append(city)
parsedList.append(state)
Or, even more compactly:
parsedList = [zipCode, city, state]
Let me know if you get another error message and I can offer more suggestions.

Categories