Python Note script with dictionary throwing error [duplicate] - python

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 5 years ago.
python 2.7.9 so i wanted to make a script to run constantly where i can take notes on names and characteristics but i don't know why its throwing this error. eventually i would like it to be exported to a file so it can save the inputted information.
Traceback (most recent call last):
File "C:\Users\Admin\Desktop\PythonFiles\Dictionary.py", line 18, in
key = input("Enter a player name: ")
File "", line 1, in
Name Error: name 'bob' is not defined
basket = {}
print("""
Note Program:
___________
1: Add Item
2: Remove Item
3: View
0: Exit Program
""")
option = int(input("Enter an Option: "))
while option != 0:
if option == 1:
key = input("Enter a player name: ")
if key in basket:
print("Name Found!...")
value = input("adding notes: ")
basket[key] += value
else:
value = input("Notes: ")
basket[key] = value
elif option == 2:
key = input("Enter a player name: ")
del(basket[key])
elif option == 3:
for key in basket:
print(key,":",basket[key])
elif option !=0:
print("please enter a valid option")
option = str(input("\n\nEnter an option: "))
else:
print("Note Program Closed.")

You should use raw_input() instead of input(), as input is trying to eval() which is causing the exception.
raw_input() takes the input and passes it back as a string.
input() will actually run as eval(raw_input()).

Related

I keep getting an error on the line with the #. I've tried putting "" around each symbol, all the symbols together, and put the symbols in () [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 months ago.
I keep getting an error on the line with the #. I've tried putting "" around each symbol, all the symbols together, and put the symbols in ().
def main():
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
#if symbol not >,<,=:
print("please use >,<,=")
return
if rating not -5,-3,0,1,3:
print("please use -5,-3,0,1,3")
return
if name = []:
print('no books found')
return
You can use the not in construct to check if an item is not in a list/tuple/other container. Thus, you can do this:
item = "foo"
print(item not in ["foo", "bar", "baz"]) # False
print(item not in ["ham", "egg", "pan"]) # True
This works for numbers too. However, using sets (with curly braces) is more efficient if all you're doing is testing if an item is in the container. Also, I see your code has
if name = []:
When testing for equality in an if statment, use the equals operator ==. Thus your code will be:
name = input("Enter a reader's name: ")
symbol = input("Enter a symbol: ")
rating = input("Enter a rating: ")
if name not in 'ratings.txt':
print("No such reader " + name)
print("bye!")
return
if symbol not in {">", "<", "="}:
print("please use >,<,=")
return
if rating not in {-5, -3, 0, 1, 3}:
print("please use -5,-3,0,1,3")
return
if name == []:
print('no books found')
return
Finally, the line
if name not in "ratings.txt":
does not check if name is in the contents of the file ratings.txt, but rather if it is a substring of that filename. For checking the file contents, you can try this question.

Instantiating classes with user input

I have just started learning about classes. In the examples that I'm learning I notice how everything that gets instantiated is hardcoded into the examples. I wanted to try and figure out if I could instantiate without having to do this, by means of user input.
In line 74/75 my expectation is that print(RecordID_map_PilotID[valUE].flownhours) prints me the number of hours I have chosen to log for a specific instance. Instead I'm confronted with the following pesky error:
Traceback (most recent call last):
File "oop_test.py", line 74, in <module>
RecordID_map_PilotID[valUE].recordflytime(loghours)
AttributeError: 'str' object has no attribute 'recordflytime'
Can anyone please help me understand why what I intend Python to do doesn't actually work?
Thank you!
PilotID_ClassValCalls = {}
RecordID_map_PilotID = {}
class PilotRecord:
department = "Aviation"
asset = "Employee"
assetcategory = "FTE"
flownhours = 0
def __init__(self, pilotid, name, age, licensestatus, licenseexpiration, shiptype, callsign, flownhours):
self.pilotid = pilotid
self.name = name
self.age = age
self.licensestatus = licensestatus
self.licenseexpiration = licenseexpiration
self.shiptype = shiptype
self.callsign = callsign
self.flownhours = flownhours
def __str__(self):
return f"{self.pilotid} has an {self.licensestatus} license with an expiration date of {self.licenseexpiration} with the following callsigns:\n {self.callsign} ."
def recordflytime(self, hours):
self.flownhours = self.flownhours + hours
def Adding_Pilot_Records(): #This definitions created new pilot records and instantiates a new object for each pilot rcord that is created. In addition memory values are stored in Dict
add_records_number = int(input("How many pilot records would you like to add? "))
for eachrecord in range(add_records_number):
record_store = [input("Please provide pilot ID: "), input("Please provide pilot Name: "), int(input("Please provide pilot Age: ")),
input("Please provide pilot licensestatus: "), input("Please provide pilot licenseexpiration: "), input("Please provide pilot shiptype: "), input("Please provide pilot callsign: "), 0]
PilotID_ClassValCalls.update({eachrecord + 1 : record_store[0]})
RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})
PilotID_ClassValCalls[eachrecord+1] = PilotRecord(record_store[0], record_store[1], record_store[2], record_store[3], record_store[4], record_store[5], record_store[6], record_store[7])
while True == True:
print("Hello, Welcome to the PILOT RECORD DATABASE\n",
"What would you like to do with the Records?:\n\n",
" \t1 - \"Add\"\n",
" \t2 - \"Log\"\n",
" \t3 - \"Delete\"\n",
" \t4 - \"Quit\"\n")
userchoice = str(input().lower().strip())
try:
if userchoice == "1" or userchoice == "add":
Adding_Pilot_Records()
continue
elif userchoice == "2" or userchoice == "log":
while userchoice == "2" or userchoice == "log":
pickarecord = str(input("Which Record ID would you like to create a log for? ")).split()
pickarecord_yesno = input(f"Selected Record >>> {RecordID_map_PilotID[pickarecord[0]]}, Is this the correct record? [Y] [N] [Quit]").upper().split()
userchoice = ""
if pickarecord_yesno[0] == "Q" or pickarecord_yesno[0] == "QUIT":
break
elif pickarecord_yesno[0] == "Y" or pickarecord_yesno[0] == "YES":
userchoice = ""
loghours = int(input(f"How many hours would you like to log?"))
pickarecord = str(pickarecord[0])
for record, valUE in RecordID_map_PilotID.items():
if pickarecord in valUE:
RecordID_map_PilotID[valUE].recordflytime(loghours)
print(RecordID_map_PilotID[valUE].flownhours)
elif pickarecord_yesno[0] == "N" or pickarecord_yesno == "NO":
userchoice = "2"
continue
elif userchoice == "3" or userchoice == "delete":
continue
elif userchoice == "4" or userchoice == "quit":
break
except ValueError:
print("Sorry an Error has occurred")
This is the line causing the error:
RecordID_map_PilotID[valUE].recordflytime(loghours)
You're trying to call .recordflytime() on RecordID_map_PilotID[valUE]. But RecordID_map_PilotID is a dictionary of type str -> str, so RecordID_map_PilotID[valUE] references a string and strings don't have .recordflytime() methods.
I can tell it's a string, because this line is the only line modifying it:
RecordID_map_PilotID.update({PilotID_ClassValCalls[eachrecord+1]: record_store[0]})
So, you're updating one dict with another, with a single key/value pair, the key being PilotID_ClassValCalls[eachrecord+1] and the value record_store[0]. PilotID_ClassValCalls is filled similarly, and its value also typically is record_store[0]. And you fill record store with the result of a call to input(), which is a string.
I would suggest you read some examples on object-oriented programming in Python - I think you're trying to do 'by hand' what is better done with the specific data structures and methods that exist for it in Python.
More generally, it's a good idea to separate the structures that hold and operate on data from the code that gets an processes input. After all, you want to manipulate these objects with direct user input now, but what if you save stuff out to a file and read it back later? Or perhaps call your code from a web page? You'd want to use the same classes, but without the direct calls to input() resulting in your code expecting input on the console.

Having an issue coding a list based palindrome checker [duplicate]

This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 3 years ago.
My base text is asking to be defined but I can't work out why.
I've tried changing it from list to string.
My code is:
text_str = input("What is your text: ")
text_list = list(text)
text_list_reversed = text_list.reverse()
text_str_reversed = str(text_list_reversed)
if text_str_reversed == text_str:
print("Your word is a palindrome")
else:
print("Your original was",text_str)
print("Your word reversed is",text_str_reversed)
Error code:
What is your text: owo
Traceback (most recent call last):
File "C:/Users/sambi.LAPTOP-UU5B18TJ/OneDrive/Documents/Python/My Code/School Stuff/Palindrome checker.py", line 1, in <module>
text_str = input("What is your text: ")
File "<string>", line 1, in <module>
NameError: name 'owo' is not defined
My excepted result would be for it to tell me it's a palindrome but instead it's spitting out a message saying that "owo" needs to be defined.
Lot going wrong in the original code. Try:
def pal_check():
text_str = input("What is your text: ")
text_str_rev = text_str[::-1]
if text_str_rev == text_str:
print("Your word is a palindrome")
else:
print(f"Your original was: {text_str}")
print(f"Your word reversed is: {text_str_rev}")
In your original code, text_list_reversed = text_list.reverse() fails because reverse() reverses in place, and returns None. Also, text is an uninitialized variable, which indicates you probably didn't copy-paste the code, but rather retyped it, if you weren't getting an error for that.

Splitting a Python Filename [duplicate]

This question already has answers here:
Extract file name from path, no matter what the os/path format
(22 answers)
Closed 4 years ago.
I am trying to create an anagram program quiz. One of the things I have done is having one central method of reading from a specified file dependant on which option the user has chosen rather than having to repeat the code. However, when trying to save the info to file, the variable saved has the pathfile saved inside it. How can I split it so that it will only save the name of the file (i.e, name of the quiz) that has been opened?
def main():
name = input("Please Enter your name to begin")
print("Hi",name,"Welcome to the Computer Science Quiz")
user_choice = menu()
option = choice(user_choice)
option, counter = questions(option)
update_file(name, option, counter)
def menu():
print("Select from the following categories:")
print("1 for System's Architecture, 2 for Memory, 3 for Storage or 4 for Network Topologies")
choice = int(input("choose option"))
if choice >0 and choice<=4: ## range check
print("you have chosen",choice,)
else:
print("This is an invalid number")
menu()
return choice
def choice(user_choice):
if user_choice == 1:
systems = open('systems.csv','r')
return systems
elif user_choice ==2:
memory = open('memory.csv','r')
return memory
else:
storage = open('storage.csv','r')
return storage
def questions(option):
counter = 0
for line in option:
anagrams = (line.rstrip("\n").split(","))
question = anagrams[0]
answer = anagrams[1]
print (question)
print (answer)
guess = input("Enter your guess")
if guess == answer:
print("Well Done")
counter = counter + 1
else:
print("oops")
print("You have scored",counter,"correctly")
return option,counter
def update_file(name, option, counter):
string_counter = (str(counter))
string_option = (str(option))
results = [name,",",string_counter,",",string_option,"\n"]
file = open('results.csv','a')
file.writelines(results)
file.close()
This is what it shows when the file is saved for the option variable:
<_io.TextIOWrapper name='storage.csv' mode='r' encoding='cp1252'>
You can remove the path from filename with this function:
import os
print(os.path.basename(file_name_with_path))

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

Categories

Resources