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.
Related
This question already has answers here:
Cannot change global variables in a function through an exec() statement?
(3 answers)
Closed 2 years ago.
I'm learning python and trying to use a function to choose and change a global variable.
I want to use the console to choose which variable to change and then choose the new value.
I'm using global inside the function to access the variables and I'm using exec() to proceed with the desired modification captured through input(). But something is not working.
Can someone please figure out what is wrong here?
name = "John"
age = 45
gender = "male"
def identify_yourself():
print("My name is " + name + ".")
print("I'm " + str(age) + " years old.")
print("I'm " + gender + ".")
def change_something():
global name, age, gender
something = input("Which variable do you want to change?\n> ")
# I then input "name"
new_value = input("Change to what?\n> ")
# I Then input "Paul"
exec(something + " = '" + new_value + "'")
identify_yourself()
identify_yourself()
# This first prints...
#
# My name is John.
# I'm 45 years old.
# I'm male.
change_something()
# On the second time this SHOULD print...
#
# My name is Paul.
# I'm 45 years old.
# I'm male.
#
# ... but it's not working.
# It keeps printing "My name is John" even after I run the change_something() function
The exec() uses globals() and locals() as defaults for their global and local variables. It defaults to changes in the locals(), not the globals. You therefore have to explicitly tell it to overwrite globals. You can do this the following way:
exec(something + " = '" + new_value + "'", globals())
I am trying to access a variable within a function in a class and print it. Whenever I try I keep getting the error: AttributeError: 'NoneType' object has no attribute 'job_ID'.
def driver():
q = my_queue.Queue_()
for line in df:
if 'received' in line:
q.enqueue(line)
print("Adding job " + q.new_item.job_ID + " to the queue with the timestamp: " + q.new_item.time_stamp + ".")
print("The prority of the job is: " + q.new_item.job_priority)
print("The job type is: " + q.new_item.job_type)
if 'respond' in line:
q.dequeue()
print("Completed job " + q.current.job_ID + " in " + str(int(q.time_elapsed)) + " seconds.")
if 'active' in line:
q.active_jobs()
print("Total number of jobs: " + str(len(q.temp)))
print("Average priority: " + str(q.average))
if 'modify' in line:
q.modify(line)
print("Modified job " + q.current.job_ID)
The error is coming from the last print statement in this code.
This is the function within the class that is being used here:
def modify(self, x): # need to fix printing bug
self.current = self.head
while self.current != None:
if x[1] in self.current.get_data():
self.current.data[2] = x[2]
self.current.data[3] = x[3]
break
# print("Modified job " + current.job_ID)
else:
# print('The job details cannot be modified.')
pass
self.current = self.current.get_next()
The exit condition for the loop in the modify function that you have provided is self.current == None.
When you call modify() in this last conditional statement:
if 'modify' in line:
q.modify(line) // here
print("Modified job " + q.current.job_ID)
You are making q.current evaluate to None. Therefore, the reason why you are getting an AttributeError is because q.current is None, which has no such attribute called job_ID.
To fix your problem, you must ensure that q.current is not None before printing q.current.job_ID. I can't give you any help beyond this, since I don't know what the purpose of your program is.
This question already has answers here:
Making a string out of a string and an integer in Python [duplicate]
(5 answers)
Closed 8 years ago.
Here is a simplified snapshot of my code:
def getExamPoints(examPoints):
totalexamPoints = 0
return totalexamPoints
def getHomeworkPoints(hwPoints):
totalhwPoints = 0
return totalhwPoints
def getProjectPoints(projectPoints):
totalprojectPoints = 0
return avgtotalprojectPoints
def computeGrade(computeGrade):
computeGrade = 1
return computeGrade
def main ( ):
gradeReport = "\n\nStudent\t Score\tGrade\n=====================\n"
studentName = input ("Enter the next student's name, or 'quit' when done: ")
while studentName != "quit":
examPoints = getExamPoints(studentName)
hwPoints = getHomeworkPoints(studentName)
projectPoints = getProjectPoints(studentName)
studentScore = examPoints + hwPoints + projectPoints
studentGrade = computeGrade (studentScore)
gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore + "\t" + studentGrade**
main ( ) # Start program
Getting an error on gradeReport assignment on last line which says "can't convert int object to str implicitly". Why is it so?
This is the line in question:
gradeReport = gradeReport + "\n" + studentName + "\t%6.1f"%studentScore+"\t"+studentGrad
You should use string formatting instead of simply adding strings and ints together (which is an error). One way would be:
gradeReport = '%s\n%s\t%6.1f\t%s' % (gradeReport, studentName, studentScore, studentGrade
There are other ways, but since you were already using % formatting, I've continued that here
In Python, "5" + 5 is an error, because it's ambiguous. Should it return "55"? 10? Rather than make assumptions and be wrong half the time, Python requires you to be explicit about it.
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.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
TypeError: ‘module’ object is not callable
This is my very first Python attempt, just trying to regain basic programming knowledge after a 10 year silence in a, for me, new language, Python. The basic idea is a tiny battly engine which decides the better hit. The bugging code is next.
self.__power = self.__att*random(2,4)/dier.__defn
As my python knowledge is extremely basic, I'm rather scared of saying the right things so Im gonna put my code down below (47 lines), you..ll notice it is really transparant so I dont suspect this will give any problem. The errorline is 16. I tried renaming the att variable to atta as well as some repositionings though new bugs come, I solve them and in the end its always the same error on the same line.
class Character:
def __init__(self,name="", att=0,defn=0,lvl=0,leven=0,exp=0, power=0):
self.__att = att
self.__defn = defn
self.__lvl = lvl
self.__leven = leven
self.__name = name
self.__xp = exp
self.__power = power
def batl(self):
import random
while self.__lvl <= 3:
dier = Character("Anaconda",1,1,50,1,0,0)
print "You encountered an " + dier.__name + " and fight it."
**self.__power = self.__att*random(2,4)/dier.__defn**
dier.__power = (dier.__att*random(1,4))/self.__defn
if self.power > dier.power:
growth = dier.__lvl*dier.__atta
groei()
else:
dmg = dier.lvl*dier.att
leven = leven-dmg
if leven < 0:
print "Alas, you're done for."
exit()
else:
print "You took " + dmg + "damage and have " + leven + "life left."
def groei(self):
if (growth+exp) > 100:
lvl += 1
exp = growth-100
print "You won and gained " + str(growth) + " and grew from level " + str(lvl-1) + " to level " + str(lvl) + "."
else:
exp = growth + exp
print "You won and gained " + str(growth) + "."
def main():
hero = Character("Nevery",2,1,2,100,0,0)
hero.batl()
if name == 'main':
main()
As you can see ive got my character class, in which i have defined the battle() method and the groei() method, very basic. Can anyone point me what I'm missing out on, been looking at it for hours. Thanks in Advance
random is the module, not the function. You need to call random.random. You could also from random import random, but I'd go with the first option in this case.
Use random.random() instead of random?