Instantiating classes with user input - python

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.

Related

how to check if objedc has attribute false o true

I'm trying to check if any of the students are on probation and if they are, display which student please assist with the error code, the code is meant to check if anyone has violated probation, it also displays an error code, the except is normally key error, but when I was trying to figure out the problem i changed it to keyboard interrupt
if students[Student].is_on_probation:
KeyError: 0
students = {}
try:
while True:
from Student import Student
students['1'] = Student("Jim", "Business", 3.1, False)
viewing = False
viewingchange = input("Would you like to view something: ").lower()
if viewingchange == "y":
viewing = True
elif viewingchange == "yes":
viewing = True
else:
viewing = False
add = input("Would you like to add someone: ")
if add.lower() == "yes" or "y":
adder = str(input("Who would you like to add: "))
major = str(input("What is their major: "))
gpa = float(input("GPA: "))
is_on_probation = bool(input("is on probation: "))
students[str(len(students)+1)] = Student(adder, major, gpa, is_on_probation)
def checking():
if viewing:
checker = input("Would you like to view all students or student a/s: ")
if checker.lower() == "a":
print(students)
checkfor = input("Check for: ")
if checkfor.lower() == "probation":
for Student in range(len(students)):
print("works")
if students[Student].is_on_probation:
print("yeppp")
else:
pass
checkerdouble = False
elif checker.lower() == "s":
searchquery2 = input("And which attribute would you like to search: ")
test = input("Student ID: ")
dude = students[test]
if searchquery2.lower() == "Name".lower():
print(dude.name)
elif searchquery2.lower() == "Major".lower():
print(dude.major)
elif searchquery2.lower() == "GPA".lower():
print(dude.gpa)
elif searchquery2.lower() == "is on probation" or "iop" or "probation".lower():
print(dude.is_on_probation)
checkerdouble = True
checking()
except KeyboardInterrupt:
print("Error code: " + "45345593M3940249525")
Your students dictionary uses string representations of numbers that start at str(1). So the loop should do the same. I think it would be better to just use int keys.
for student_id in map(str, range(1, len(students)):
if students[student_id].is_on_probation:
print(student_id)
This would work but it relies on the dictionary keys being dense. I would prefer to do:
for student_id in sorted(students, key=int):
if students[student_id].is_on_probation:
print(student_id)
Some might object to the indexing, as one can do:
for student_id, student in sorted(students.items(), key=lambda v: int(v[0])):
if student.is_on_probation:
print(student_id)

I keep getting traceback and str callback errors after so much troubleshooting and I can't seem to fix it. Python contacts book

i have saved the dictionary in a separeate document with all the correct syntax called directory.txt. The code is for a contacts book/directory using dictionaries. I'm not sure wheter im supposed to define functions before or after calling them but i've tried both and it still doesnt seem to work.
file = open("directory.txt","r+")
contacts = file.read()
def new():
print("Please enter the name of the new contact.")
name = input()
print("Please enter the number of the new contact.")
num = input()
contacts.update({name:num})
print("Contact has successfully been added.")
def view():
for keys, values in contacts():
print("\n*************************************************")
print("Name:",keys)
print("Number:",values)
print("*************************************************\n")
def edit():
for keys, values in contacts():
print("\n*************************************************")
print("Name:",keys)
print("Number:",values)
print("*************************************************\n")
print("Type the name of the contact you would like to edit.")
global name_two
name_two = input()
print("If you would like to edit the number, type 'number'.\nIf you would like to edit the name, type 'name'.\nIf you would like to delete this contact, type 'delete'.")
edit = input().lower()
if edit == "number":
num_edit()
elif edit == "name":
name_edit()
elif edit == "delete":
delete()
def num_edit():
print("What would you like to change the number to?")
num_two = input()
contacts[name_two] = num_two
print("Contact successfully changed.")
def name_edit():
num_save = contacts[name_two]
del contacts[name_two]
print("Enter the new name for the contact.")
name_new = input()
contacts.update({name_new:num_save})
print("Contact successfully changed.")
def delete():
del contacts[name_two]
print("Contact successfully deleted.")
print("Welcome to the Contacts Book.")
print("*****************************\n")
print("If you would like to make a new contact, type 'new'.\nIf you would like to view your contacts, type 'view'.\n If you would like to edit your contacts, type 'edit'.\nIf you would like to exit, type 'exit'")
mode = input().lower()
if mode == "new":
new()
elif mode == "view":
view()
elif mode == "edit":
edit()
else:
print("Goodbye.")
Here is the error message when i type 'view' as the first input:
File "c:\Users\brain\Downloads\contacts.py", line 56, in <module>
view()
File "c:\Users\brain\Downloads\contacts.py", line 11, in view
for keys, values in contacts():
TypeError: 'str' object is not callable
I think you have some variable named str in your code and that caused this problem. This is called shadowing the built in functions, you can try to find that variable with a search in your project file and change it to some other name and should solve it.
I believe you just have an unnecessary set of parenthesis after contacts (it's a var not a function as far as I can see), so just remove those and you should be good. EDIT: gimix reply is far more accurate than what I wrote here

Python not importing data structure [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to create a text-based game. I've made a basic/generic intro and now it's getting long so I want to create a new file so that I can add things like armor and weapons. When I went to try to import 'my_character' it gave me an error so I went to research this problem and I found this, so I tried it. I just got an error message saying it wasn't define (similar to the error below). This is the intro part named intro:
# Date started: 3/13/2018
# Description: text based adventure game
import time
def display_intro():
print('It is the end of a 100 year war between good and evil that had\n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n'
+ 'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n'
+ 'wed and had you. \n')
time.sleep(3)
def main():
display_intro()
main()
gen = input('\nYour mother had a [Boy or Girl]: ')
name = input("\nAnd they named you: ")
print("You are a {} named {}".format(gen, name))
chara_class = None
# Assigning points Main
my_character = {
'name': name,
'gender': gen,
'class': chara_class,
'strength': 0,
'health': 0,
'wisdom': 0,
'dexterity': 0,
'points': 20
}
# This is a sequence establishes base stats.
def start_stat():
print("\nThis is the most important part of the intro")
time.sleep(3)
print("\nThis decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category: Strength, Health, Wisdom, or Dexterity.\n"
)
def add_character_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much? "))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character['points'] -= amount
else:
print("That attribute doesn't exist! \nYou might have to type it in all lowercase letters!!!")
def remove_character_points():
attribute = input("\nWhich of the catagories do you want to remove from? ")
if attribute in my_character.keys():
amount = int(input("How many points do you want to remove? "))
if amount > my_character[attribute]:
print("\nYou are taking away too many points!")
else:
my_character[attribute] -= amount
my_character['points'] += amount
else:
print(
"That attribute doesn't exist! \nYou might have to type it in all lowercase letters!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_character_points()
elif Continue == "n" or "No" or "no":
main()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_character_points()
elif choice == "2":
remove_character_points()
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
def story_str():
print(
"\nYou were always a strong child who easily do physical labor and gain lots of muscle."
)
time.sleep(3)
print("\nYou regularly trained with your dad who was also a skilled swordsman.")
time.sleep(3)
print("\nAs you grew into an adult, you're swordsmanship improved drastically.")
time.sleep(3)
print("\nOnce old enough, you joined the local guild as a warrior.")
time.sleep(3)
def story_dex():
print("\nYou were a sly child. You would always be stealing from other people and with"
+ "\nconstant practice you became proficient at thieving.")
time.sleep(3)
print("\nCombined with the skill of knives and short-blades, you became an extremely deadly assassin."
)
time.sleep(3)
print("\nOnce old enough, you joined the local guild as an assassin.")
time.sleep(3)
def story_wis():
print("\nYou grew up as a very intellegent child. You read books everyday and realized that magic"
+ "is the best offensively and defensively.")
print("\nYou grew up and attended the best magic school avalible and graduated."
)
print("\nYou soon went to the local guild and joined as a wizard.")
run_story = False
while run_story:
if my_character['strength'] >= 13:
story_str()
chara_class = 'Warrior'
run_story = True
else:
continue
if my_character['dexterity'] >= 13:
story_dex()
chara_class = 'Assassin'
run_story = True
else:
continue
if my_character["wisdom"] >= 13:
story_wis()
chara_class = 'Mage'
run_story = True
else:
continue
The command I have typed on part1 is to try to import my_character is:
from intro import my_character
print(my_character)
I have been trying to import my_character but it comes up as:
Traceback (most recent call last):
File "C:/Users/user/Desktop/part1.py", line 5, in <module>
my_character
NameError: name 'my_character' is not defined
The original file was named "intro" and the new one is named "part1". Do I need to do the 'if name == "__main"' thing? If so, what does that do?
Check for:
1) is the file name my_character.py
2) you have imported it as my_character
3) my_character is in the main python directory (if you are importing in interpreter)

Python pickles not storing data

I am trying to create a registrar system through Python with pickles. I have gotten the system to record user input, but it does not save it for future implementations of the program.
Here is the code that will start the program:
import datetime
import pandas as pd
import pickle as pck
import pathlib
from pathlib import *
from registrar import *
prompt = "Please select an option: \n 1 Create a new course \n 2 Schedule a new course offering \n 3 List this school's course catalogue \n 4 List this school's course schedule \n 5 Hire an instructor \n 6 Assign an instructor to a course \n 7 Enroll a student \n 8 Register a student for a course \n 9 List this school's enrolled students \n 10 List the students that are registered for a course \n 11 Submit a student's grade \n 12 Get student records \n 13 Exit"
farewell = "Thank you for using the Universal University Registrar System. Goodbye!"
print ("Welcome to the Universal University Registration System.")
print ("\n")
try: #As long as CTRL-C has not been pressed, or 13 not been input by user.
input_invalid = True
while input_invalid:
inst = input("Please enter the name of your institution. ").strip()
domain = input("Please enter the domain. ").strip().lower()
if inst == "" or domain == "":
print("Your entry is invalid. Try again.")
else:
input_invalid = False
schoolie = Institution(inst, domain)
if Path(inst + '.pkl').exists() == False:
with open(inst + '.pkl', 'r+b') as iptschool:
schoolie = pck.load(iptschool)
while True:
print (prompt)
user_input = input("Please enter your choice: ")
try:
user_input = int(user_input)
if user_input < 1 or user_input > 14: #UserInput 14: on prompt.
raise ValueError("Please enter a number between 1 and 13, as indicated in the menu.")
except ValueError:
print("Not a valid number. Please try again.")
if user_input == 1: #Create a new course
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_name = input("Please enter a course name: ").strip()
input_department = input("Please enter the course's department: ").strip()
input_number = input("Please enter the course's number (just the number, not the departmental prefix): ").strip()
try:
input_number = int(input_number)
except ValueError:
print ("Please print an integer. Try again.")
input_credits = input("Please enter the number of credits awarded for passing this course. Please use an integer: ").strip()
try:
input_credits = int(input_credits)
except ValueError:
print ("Please print an integer. Try again.")
if input_name != "" and input_department != "" and input_number and input_credits:
input_invalid2 = False #Valid input
else:
print("One or more of your entries is invalid. Try again.")
added_course = Course(input_name, input_department, input_number, input_credits)
for course in schoolie.course_catalog:
if course.department == input_department and course.number == input_number and course.name == input_name:
print("That course is already in the system. Try again.")
input_invalid2 == True
if input_invalid2 == False:
schoolie.add_course(added_course)
print ("You have added course %s %s: %s, worth %d credits."%(input_department,input_number,input_name, input_credits))
And here is the second option, which SHOULD reveal that it is stored, but it does not.
elif user_input == 2: #Schedule a course offering
input_invalid2 = True #Ensure that the user actually provides the input.
while input_invalid2:
input_department = input("Please input the course's department: ").strip()
input_number = input("Please input the course's number: ").strip()
course = None
courseFound = False
for c in schoolie.course_catalog:
if c.department == input_department and c.number == input_number: #Course found in records
courseFound = True
course = c
input_section_number = input("Please enter a section number for this course offering: ").strip()
input_instructor = input("If you would like, please enter an instructor for this course offering: ").strip()
input_year = input("Please enter a year for this course offering: ").strip()
input_quarter = input("Please enter the quarter in which this course offering will be held - either SPRING, SUMMER, FALL, or WINTER: ").strip().upper()
if input_course != "" and input_course in schoolie.course_catalog and input_section_number.isdigit() and input_year.isdigit() and input_quarter in ['SPRING', 'SUMMER', 'FALL', 'WINTER'] and input_credits.isdigit():
if input_instructor != "": #Instructor to be added later, if user chooses option 6.
added_course_offering = CourseOffering(c, input_section_number, None, input_year, input_quarter)
else:
added_course_offering = CourseOffering(c, input_section_number, input_instructor, input_year, input_quarter)
schoolie.add_course_offering(added_course_offering)
input_invalid2 = False #Valid input
print ("You have added course %s, Section %d: %s, worth %d credits."%(input_course,input_section_number,input_name, input_credits))
else:
print("One or more of your entries is invalid. Try again.")
if courseFound == False: #If course has not been found at the end of the loop:
print("The course is not in our system. Please create it before you add an offering.")
break
By the way, I think I have the system closing properly. Correct me if I'm wrong:
elif user_input == 13: #Exit
with open(inst + '.pkl', 'wb') as output:
pck.dump(schoolie, output, pck.HIGHEST_PROTOCOL)
del schoolie
print (farewell)
sys.exit()
except KeyboardInterrupt: #user pushes Ctrl-C to end the program
print(farewell)
I believe that there is something wrong with the way that I am setting up the pickles files. I'm creating them, but I seem not to be putting data into them.
I apologize for the long-winded nature of this question, but I hope that the details will help you understand the problems that I've been having. Thanks in advance for the help!
it seems you may have dump and load reversed: (from the docs)
Signature: pck.load(file, *, fix_imports=True, encoding='ASCII', errors='strict')
Docstring:
Read and return an object from the pickle data stored in a file.
Signature: pck.dump(obj, file, protocol=None, *, fix_imports=True)
Docstring:
Write a pickled representation of obj to the open file object file.
With all those lines of code, it does get a little confusing, but I don't see any code that is pickling and writing the objects to a file.
Before anything else, you should assign the file to a variable so you can reference it. To do this, you'll have code similar to this:MyFile = open("FileName.extension","wb"). MyFile can be any name you want, it will be what you use later to reference the file. FileName is the name of the file itself. This is the name it will have in File Explorer. .extension is the file's extension, specifying the type of file. You should use .dat for this. wb is the file access mode. "w" means write, and "b" means binary. (Pickled objects can only be stored in a binary file.)
To write the pickled objects, you'll need this code:pck.dump(object,MyFile). (Usually, you would use pickle.dump(object,MyFile), but you imported pickle as pck.)
After writing the data to the file, you'll want to retrieve it. To do this, the "wb" instance of MyFile needs to be closed like this:MyFile.close(). Then you'll need to re-open the file in read mode using the following code:MyFile = open("FileName.extension","rb") Then you would use this:object = pickle.load(MyFile) to read the data. In the preceding example, (the load function), your object must have the same name as when you pickled it using the dump function. (pck.dump(object,MyFile))
In the end, you'll end up with something similar to this:
if writing conditions are true:
MyFile = open("FileName.dat","wb")
pickle.dump(object,MyFile) # This will be repeated for each object.
MyFile.close()
if reading conditions are true:
MyFile = open("FileName.dat","rb")
object = pickle.load(MyFile) # This will be repeated for each object.
MyFile.close()
I'm sorry if this wasn't the answer you wanted. Because of all those lines of code, it is somewhat hard to understand. I need clarification to give a better answer.

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