Python Job Collector Files I/O [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am trying to make a program that you can input job names, categories, and pay, and i am trying to write the inputed job names, categories, and pay to a file to store the data, but i am having problems doing so.
class Job(object):
def __init__(self, jobName = '', jobCategory = '', jobPay = ''):
self.jobName = jobName
self.jobCategory = jobCategory
self.jobPay = jobPay
def getName(self):
self.jobName = input("What is the Job Title: ")
def getCategory(self):
self.jobCategory = input("What is the Job Category: ")
def getPay(self):
self.jobPay = input("What is the Job Pay: ")
def displayJob(self):
print("Job: " + self.jobName)
print("Job Category: " + self.jobCategory)
print("Job Pay: " + self.jobPay)
print()
def Main():
global NewJob
NewJob = Job()
NewJob.getName()
NewJob.getCategory()
NewJob.getPay()
print()
NewJob.displayJob()
myFile = open('newFile.txt', 'w')
myFile.write(NewJob.displayJob())
myFile.close()
Main()

displayJob() prints to stdout, not to your file. You have to return a string:
def displayJob(self):
results = [
"Job: " + self.jobName,
"Job Category: " + self.jobCategory,
"Job Pay: " + self.jobPay
]
return "\n".join(results)
Or pass file as an argument, but that looks a little odd:
import sys
def displayJob(self, file=sys.stdout):
print("Job: " + self.jobName, file=file)
print("Job Category: " + self.jobCategory, file=file)
print("Job Pay: " + self.jobPay, file=file)
print(file=file)
...
NewJob.displayJob(myFile)

Assuming that the problem is nothing gets written to the file. Job.displayJob() does not return anything to be written into the file, it only displays it to stdout. Figure out how you want your object to serialize to the file and have a method that returns that string.

Related

Don't understand what's wrong with my code. Can anyone help me understand why it isn't working? [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 2 years ago.
Improve this question
So I'm making a program where you capture a pokemon and set their level, and when you query them it returns their level, but when I query it doesn't return the pokemon selected, just the last pokemon in the dictionary.
pk = {}
line = input('Command: ')
while line:
tempq = 2
if "Query" in line:
tempq = 1
qparts = line.split()
tempname = parts[1]
if tempname in pk:
print(tempname, "is level", pk.get(tempname),".")
elif tempname not in pk:
print("You have not captured" + tempname + "yet.")
else:
parts = line.split()
name = parts[1]
lvl = parts[tempq]
pk[name] = int(lvl)
line = input('Command: ')
print(pk)
qparts = line.split()
tempname = parts[1]
You create qparts, but then never use it. Instead, you refer to parts, which is created in your else block, and contains the information for whatever pokemon was named in the last non-Query command.
Try making tempname from qparts instead.
pk = {}
line = input('Command: ')
while line:
tempq = 2
if "Query" in line:
tempq = 1
qparts = line.split()
tempname = qparts[1]
if tempname in pk:
print(tempname, "is level", pk.get(tempname),".")
elif tempname not in pk:
print("You have not captured" + tempname + "yet.")
else:
parts = line.split()
name = parts[1]
lvl = parts[tempq]
pk[name] = int(lvl)
line = input('Command: ')
print(pk)
Result:
Command: catch pikachu 50
Command: catch bulbasaur 10
Command: Query pikachu
pikachu is level 50 .

looping through task numbers

Could someone help with my current code. I would like to add task numbers to my tasks that get saved in my output text document. I would need to loop it so each task will be assigned the next task number. If possible I would like to be able to call on these task numbers later.
My code so far is:
def add_task():
if menu == "a" or menu == "A":
with open( 'user.txt' ) as fin :
usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
task = input ("Please enter the username of the person the task is assigned to.\n")
while task not in usernames :
task = input("Username not registered. Please enter a valid username.\n")
else:
task_title = input("Please enter the title of the task.\n")
task_description = input("Please enter the task description.\n")
task_due = input("Please input the due date of the task. (yyyy-mm-dd)\n")
date = datetime.date.today()
task_completed = False
if task_completed == False:
task_completed = "No"
else:
task_completed = ("Yes")
with open('tasks.txt', 'a') as task1:
task1.write("\nUser assigned to task:\n" + task + "\nTask Title :" + "\n" + task_title + "\n" + "Task Description:\n" + task_description + "\n" + "Task Due Date:\n" + task_due + "\n" + "Date Assigned:\n" + str(date) + "\n" + "Task Completed:\n" + task_completed + "\n")
print("The new assigned task has been saved")
add_task()
Firstly, I don't really want to go into detail but the way you are storing your output is highly inefficient and difficult to access the larger your text file gets. Why not use some free DB system to store your data.
Secondly. Assuming that you want to write many tasks at a time but only "save" once so to speak, consider using a dict of dicts.
def write_task_to_txt(task):
### break down the dict to from your lines to write to your text
def add_task(task_list,task_id):
new_tasks[task_id] = {}
new_tasks[task_id]["username"] = "username"
new_tasks[task_id]["title"] = "Task 1"
### How you fill up a task
return task_list
new_tasks = {}
for i in range(10):
new_tasks = add_task(new_tasks,i+1)
write_task_to_txt(new_tasks)
With this you can always access the task using new_tasks[task_id] to pull all the data of that task. Note the for loop is using an iterator. If you want to avoid this you could use a global and a while loop instead. BUT if you want to do that, i recommend converting your application into a class and use class variables instead.
Here is a skeleton of how I would try that:
class yourclass():
def __init__(self):
self.task_num = 1 #use 1 if no values
self.tasks_towrite = {}
self.mode_select()
def mode_select(self):
self.menu = input("choose mode")
while(1):
if self.menu == "a" or self.menu == "A":
self.add_task()
if self.menu == "s".casefold() #Cool function that does the same as your menu thingy
self.write_to_text()
else:
print("exit")
self.close_program()
def close_program(self): # Exit function
print("exiting")
sys.exit(1)
def add_task(self): #Add task
with open( 'user.txt' ) as fin :
self.usernames = [i.split(',')[0] for i in fin.readlines() if len(i) > 3]
task = input ("Please enter the username of the person the task is assigned to.\n")
while task not in self.usernames :
task = input("Username not registered. Please enter a valid username.\n")
else:
new_task = {}
new_task["username"] = task
new_task["title"] = input("Please enter the title of the task.\n")
new_task["description"] = input("Please enter the task description.\n")
new_task["due"] = input("Please input the due date of the task. (yyyy-mm-dd)\n")
date = datetime.date.today()
task_completed = False
if task_completed == False:
new_task["completed"] = "No"
else:
new_task["completed"] = "Yes"
new_task["assigned"] = date
self.tasks_towrite[self.task_num] = new_task
sefl.task_num +=1 #New test number
return None #returns to mode_select
def write_to_text(self):
with open('tasks.txt', 'a') as task1:
for i in self.tasks_towrite:
task1.write(str(i) + "\n") #Writes it all at once You can reformat however you want
self.tasks_towrite = {}
print("The new assigned tasks has been saved")
return None #returns to menu or you could go to self.close_program to exit
if __name__== '__main__':
x = yourclass()

How to fix NameError: name 'author' is not defined when running python script

I am trying to open up this on the terminal on my mac, but I keep getting name 'author' not defined when it clearly is.
def bibformat_mla(author, title, city, publisher, year):
author = input("enter author: ")
title = input("enter title: ")
city = input("enter city: ")
publisher = input("enter publisher: ")
year = input("enter year: ")
answer = author + ' , ' + title + ' , ' + city + ': ' + publisher + ', ' + year
return answer
bibformat_mla(author, title, city, publisher, year)
'author, title, city: publisher, year'
bibformat_mla("Jake, Matt", "Open Data ", "Winnipeg", "AU Press", 2013)
'Morin, Pat. Open Data Structures. Winnipeg: AU Press, 2013'
When you run the following:
bibformat_mla(author,title,city,publisher,year)
You are saying to the program that you have a variable called "author" which is ready to pass into biblformat(). This causes an error because the the variable isn't defined before the function is called.
I.e You're telling the function to expect a certain variable, and it throws an error at you because the variable doesn't actually exist yet.
From what it looks like you are trying to accomplish, you can simply call the function like this:
bibformat_mla()
You will also need to change your definition to this so that your function no longer expects the parameters:
def bibformat_mla():
With functions you can pass information as Parameters, in your function definition you are indicating that when you run the function you will also pass 5 variables with it.
From the looks of it you are setting the variables by user input and thus you do not need to pass parameters, deleting them should make the code work.
This:
def bibformat_mla(author, title, city, publisher, year):
Into this:
def bibformat_mla():
You need to decide whether your function will be accepting those strings as arguments or if it will prompt the user for them? There isn't much point requiring the user provide the values as arguments, then immediately overwriting them with values they enter.
So you have a choice.
perform the inputs prior to calling the function and pass the inputted values to the function.
remove the arguments to the function and allow the user to input the strings as part of bibformat_mla.
code:
def bibformat_mla1 (author,title,city,publisher,year):
return author + ' , ' + title + ' , ' + city + ': ' + publisher + ', ' + str(year)
def bibformat_mla2 ():
author = input ("enter author: ")
title = input ("enter title: ")
city = input ("enter city: ")
publisher = input ("enter publisher: ")
year = input ("enter year: ")
return author + ' , ' + title + ' , ' + city + ': ' + publisher + ', ' + year
print(bibformat_mla1("Jake, Matt", "Open Data ", "Winnipeg", "AU Press", 2013))
print(bibformat_mla2())

Replacing string character in python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am making a program where the user inputs some text, and I wan't all the characters in that text that is not in the variable "alfabet" to be changed to "?". How can I do this? I also want a to do it in two functions, main and clean_text. My code looks like this now:
def clean_text():
for char in text:
if char in alfabeth:
continue
elif char not in alfabeth:
#don't know what to do here
#text[] = "?"
def main():
userInput = input("type in text: ")
text = list(userInput)
if__name__ == "__main__":
main()
clean_text(text)
This would be the basic code you need:
alfabeth = 'abcdefghijklmnopqrstuvwxyz'
text_in = list(input('What ever'))
for x in range(len(text_in)):
if text_in[x] in alfabeth:
continue
else:
text_in[x] = '?'
text_in = "".join(text_in)
print(text_in)
If you want you can define everything as one function or two or what ever you like.
Hope it helps
This is how it can look with functions. It worked for me.
alfabeth = 'abcdefghijklmnopqrstuvwxyz'
def clean_text(text_in, alfabeth):
for x in range(len(text_in)):
if text_in[x] in alfabeth:
continue
else:
text_in[x] = '?'
def main():
global UsrInput
UsrInput = list(input('type in text: '))
return UsrInput
if __name__ == "__main__":
main()
clean_text(UsrInput, alfabeth)
print("".join(UsrInput))
You have to return something to be able to assign that user_input to a variable to pass into clean_text(). Here is a working version of your project. This will handle multiple words separated by space as well.
def clean_text(word):
alphabeth = 'vshthstmpd'
for idx, item in enumerate(word):
if item == ' ':
pass
elif item not in alphabeth:
word[idx] = '?'
return ''.join(word)
def main():
user_input = input('Type in text: ')
text = list(user_input)
return text
if __name__ == '__main__':
text = main()
print(clean_text(text))
Type in text: vash the stampede
v?sh th? st?mp?d?

Python function name finder not working [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 6 years ago.
Improve this question
Trying to make a function to find names of python functions in a file
for a python class I have no idea why it's only returning one comma that I add in between the function names
def pythonanalysis(s):
pythonlen = str(s.count("\n"))
functionname = ''
funcdoc = s
counter = 0
while funcdoc.find("def") != -1:
function = funcdoc.find("def")
funcdoc = funcdoc[function + 4:funcdoc.find("(")]
functionname += funcdoc[:funcdoc.find("(")] + ", "
counter += 1
print(functionname)
forlen = str(s.count("for"))
iflen = str(s.count("if"))
whilelen = str(s.count("while"))
authnum = s.find('__author__ =')
author = s[authnum + 14:]
authname = author[:author.find('\'')]
return "There are " + pythonlen + " lines in this file \n\
There are "+ str(counter) + " functions in this document named: " + functionname + "\n\
There are " + forlen+" for loops and " + iflen + " if loops and " + whilelen + " while loops\n\
The author is " + authname
function = funcdoc.find("def")
funcdoc = funcdoc[function + 4:funcdoc.find("(")]
The "(" that you find could quite possibly be BEFORE the "def", which would result in an empty string here! Even if you did find the "(" that's just after the function name, you discard the entirety of the file after that point, so you could never find more than one function. Hint: the str.find() method takes an optional second parameter that specifies the starting point of the search.

Categories