Having a very simple to fix (I guess at least) issue with calling functions from within another function.
Here's the code:
class File_Modification:
def Start_Up():
x = 0
if x == 0:
print('Options: \n 1. Create New File \n 2. Open Existing File \n 3. Modify Existing File \n 4. Verify File')
Op_Ans = input()
if Op_Ans == '1':
Create_File()
x = 1
elif Op_Ans == '2':
Open_File()
x = 1
elif Op_Ans == '3':
print('Option Three')
x = 1
elif Op_Ans == '4':
print('Option Four')
x = 1
Start_Up()
def Create_File():
print('Create File Menu')
def Open_File():
print('Open File Menu')
def Modify_File():
print('Modify File Menu')
def Verify_File():
print('Verify File Menu')
The code is meant to open a menu, ask the user to input an option and then go to a setting to modify or create information. From the start up function (called once it has been written) the next function i.e. Create_File() gives an error that the function is not recognised.
Any one got any solutions to this error? Haven't been able to find any solutions to this yet.
This is the error I am getting:
Traceback (most recent call last):
File "C:\Users\explo\Downloads\Modify Bulk Files.py", line 1, in
class File_Modification:
File "C:\Users\explo\Downloads\Modify Bulk Files.py", line 26, in File_Modification
Start_Up()
File "C:\Users\explo\Downloads\Modify Bulk Files.py", line 12, in Start_Up
Create_File()
NameError: name 'Create_File' is not defined
Thanks everyone!
EDIT:
I've made the program work by taking out the class and only using functions. Naming all functions before the StartUp() call. This means it's all created prior.
Thanks everyone for your time. If there's any way of fixing this please note it for future reference. other wise there's my fix.
EDIT 2: Added the error that comes with it and corrected the indentations on the code.
They're in a class, so just call them as self.FunctionName()
Related
i'm trying to edit only a specific set of columns of a row in a csv file for a school project but not having much luck, and am now running into the error when trying to see if using dictwriter will work as I need the last two columns im not wanting to be edited to still exist:
Traceback (most recent call last):
File "C:\Users\nikit\PycharmProjects\C0027838_csc1034_project2_2021\main.py", line 104, in <module>
writer.writerow = csv.DictWriter(file, fieldnames=["first_name","last_name","title","pronouns","dob","occupation"], extrasaction="ignore")
AttributeError: 'builtin_function_or_method' object has no attribute 'writerow
Here's the section of code i'm trying to get working:
if choice == "4":
with open("mock_data.csv", newline='') as file:
reader = csv.DictReader(file)
client = list(reader)
editClient = int(input("Please enter the index number of the client you wish to edit: "))
print("Please enter the details for each of the following: ")
for i in range(len(existing_clients[0])):
newDetails = input("Enter new data for " + str(existing_clients[0][i]) + ": ")
existing_clients[editClient][i] = newDetails
changes = input("Are you sure you'd like to make these changes? Enter Yes or No")
if changes == ("Yes"):
# Newline fixed the spacing issue I was having
with open("mock_data.csv", "w+", newline="") as file:
writer.writerow = csv.DictWriter(file, fieldnames=["first_name","last_name","title","pronouns","dob","occupation"], extrasaction="ignore")
writer.writeheader()
for line in client:
writer.writerow(line)
And an example of my csv file:
first_name,last_name,title,pronouns,dob,occupation,account_balance,overdraft_limit
Garner,Coupman,Ms,Male,14/04/2022,General Manager,2200.76,2.28
Jens,Eldrid,Honorable,Male,13/11/2021,Research Associate,967.64,79.15
Enrichetta,Pinkerton,Honorable,Female,29/11/2021,Software Engineer I,1182.94,6.10
Merwyn,Abraham,Mrs,Male,23/05/2022,Associate Professor,1071.10,93.88
Cheers!
I've tried slicing but obviously that gets rid of the last two columns which i need for later in the program so if you can help me fix this or point me toward another method that would be great :)
cheers!
In the following code snippet, I am trying to understand the simpy tutorial. I am unable to explain the output. I expect all the "\o/" to be printed in one go before other statements are printed. Also, there is a problem with the callback.
import simpy
class School:
def __init__(self, env):
self.env = env
self.class_ends = env.event()
self.pupil_procs = [env.process(self.pupil()) for i in range(3)]
for x in self.pupil_procs:
x.callbacks.append(self.my_callback(x))
#print(x.callbacks)
self.bell_proc = env.process(self.bell())
def bell(self):
for i in range(2):
value=yield self.env.timeout(45,value="bell_rang!at"+str(env.now))
self.class_ends.succeed(value='class_ends!')
print("in bell proc")
self.class_ends = self.env.event()
print(value)
def pupil(self):
for i in range(2):
print(' \o/',i, end=' ')
classends=yield self.class_ends
print('done!')
print(classends)
def my_callback(self,event):
print('Called back from',event)
env = simpy.Environment()
school = School(env)
env.run()
The output is as follows:
Called back from <Process(pupil) object at 0x7fd7ddce97b8>
Called back from <Process(pupil) object at 0x7fd7ddce9be0>
Called back from <Process(pupil) object at 0x7fd7ddcad5f8>
\o/ 0 \o/ 0 \o/ 0 in bell proc
bell_rang!at0
done!
class_ends!
\o/ 1 done!
class_ends!
\o/ 1 done!
class_ends!
\o/ 1 in bell proc
bell_rang!at45
done!
class_ends!
done!
class_ends!
done!
class_ends!
Traceback (most recent call last):
File "/home/deeplearning/PycharmProjects/python-scheduling/learnSimPy/learnmore.py", line 35, in <module>
env.run()
File "/usr/local/lib/python3.5/dist-packages/simpy/core.py", line 137, in run
self.step()
File "/usr/local/lib/python3.5/dist-packages/simpy/core.py", line 221, in step
callback(event)
TypeError: 'NoneType' object is not callable
Process finished with exit code 1
You add the result of self.my_callback(x) (which is None) to the list of callbacks.
Instead, you should append functools.partial(self.my_callback, x).
I also recommend that you rather use yield from process instead of append functions to process's callbacks.
I am new to this python coding.So,please can someone find what is the problem with this code.
def factorial(n):
sum=1
for i in range(1..n+1):
sum=sum*i
print(sum)
return sum
v=int(input("enter the number:"))
factorial(v)
the error i get:
enter the number:4
Traceback (most recent call last):
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py",line 9, in <module>
factorial(v)
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py", line 3, in factorial
for i in range(1..n+1):
AttributeError: 'float' object has no attribute 'n'
There are two ways you can write your program. To reformat your code so that it is in good form, you might organize your program like so:
def main():
variable = int(input('Enter the number: '))
print(factorial(variable))
def factorial(number):
total = 1
for integer in range(1, number + 1):
total *= integer
return total
if __name__ == '__main__':
main()
If instead you are trying to accomplish the same thing using the least amount of code, the following two lines will do the exact same thing for you:
import math
print(math.factorial(int(input('Enter the number: '))))
I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()
Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')
the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error
for _ in range(10):
try:
next_results = search_results['search_metadata']['next_results']
except KeyError or e:
break
kwargs = dict([ kv.split('=')
for kv in next_results[1:].split("&") ])
search_results = twitter_api.search.tweets(**kwargs)
statuses += search_results['statuses']
if len(statuses) > max_results:
break
q = "CrossFit"
results = twitter_search(twitter_api, q, max_results=10)
print (json.dumps(statuses[0], indent=1))
The code posted is not what you ran, as search_results is not defined and execution would stop there. My guess, based on what you posted, is that max_results is not defined when len(statuses) > max_results is executed. In your original code, the loop must be within a function definition. The error message can only occur when a name within a function, defined to be local because it is an assignment target, is used before any assignment. For instance:
>>> def f():
if True: return y
else: y = 1
>>> f()
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
f()
File "<pyshell#10>", line 2, in f
if True: return y
UnboundLocalError: local variable 'y' referenced before assignment
Please read and act on this SO mcve help page. What you posted is both incomplete and over-complete (everything after the if statement is superfluous).