Hi I'm VERY new to programming, and I am working on my first program. I've been following along in a book and I decided to stop and test a function. The function is in a file called myPythonFunctions.py. I then created a new file called untitled.py and put it in the same folder as myPythonFunctions.py.
In untitled.py I have the following code:
import myPythonFunctions as m
m.generateQuestion()
Very simple, but when I try to run it I get Import Error: no module named myPythonFunctions.
I don't understand, there is clearly a file named myPythonFunctions in the folder. What's going on?
In case you need it, here is the code for m.generateQuestion()
def generateQuestion():
operandList = [0,0,0,0,0,]
operatorList = ['', '', '', '', '']
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
for index in range(0,5):
operandList[index] = randint(1,9)
for index in range(0,4):
if index > 0 and operatorList[index-1] !='**':
operator = operatorDict[randint(1,4)]
else:
operator = operatorDict[randint(1,3)]
operatorList[index] = operator
questionString = str(operandList[0])
for index in range(1,5):
questionString = questionString + OperatorList[index-1] + str[operandList[index]
result = eval(questionString)
questionString.replace("**","^")
print('\n' + questionString)
userAnswer=input('Answer: ')
while true:
try:
if int(userAnswer) == result:
print('Correct!')
return 1
else:
print('Sorry, the correct answer is', result)
return 0
except Exception as e:
print("That wasn't a number")
userAnswer = input('Answer: ')
Edit: I'm now getting this error
Traceback (most recent call last):
File "/Users/Brad/Desktop/Python/Untitled.py", line 1, in <module>
import myPythonFunctions as m
File "/Users/Brad/Desktop/Python/myPythonFunctions.py", line 33
operatorDict = [1:'+', 2:'-', 3:'*', 4:'**']
^
SyntaxError: invalid syntax
The syntaxis error you are getting, is because you are trying to define a dictionary as a list, so the interpreter is raising the error because it does not know what to do with that.
To define a dictionary you need to use { } instead of [ ]
--- EDIT 2
Your dictionary implementation is wrong, do you really copied this code from somewhere?
The
operatorDict = {1:'+', 2:'-', 3:'*', 4:'**'}
Your code was mispelled
---- EDIT
Your code on myPythonFunctions is really bad.
Python needs correct identation to works, please double check this step
I suggest you to do a check in your structure:
I did this right now
/somefolder
--this.py
--functions.py
/
The contents
--this.py
import functions as f
print f.hello()
--functions.py
def hello():
return 'It worked'
Try this structure in your environment :D
And then run:
python this.py
Related
I am trying to make a python program, that will help me read notifications log easily.
Here's the code:-
location=open("/home/pika/.cache/xfce4/notifyd/log","rt")
data=location.read()
l_data=list(data) #Contents of log file is in string now, in data variable
x=data.count('app_name')
def rm(start,stop,p_name):
for x in range(start,stop+1):
print(x)
n=p_name(x)
m=l_data.remove(n)
print(m)
data=''
data=data.join(l_data)
for i in range(0,x):
#Time of notification
t_start=data.index('[')
t_end=data.index(']')
t=data[t_start:t_end+1]
print(t)
print('\n')
rm(t_start,t_end,t)
#Name of the application
name_start=data.index('app_name')
name_end=data.index('summary')
name=data[name_start:name_end-1]
print(name)
print('\n')
rm(name_start,name_end,name)
#Heading of notification
head_start=data.index('body')
head_end=data.index('app_icon')
head=data[head_start:head_end-1]
print(head)
print('\n')
rm(head_start,head_end,head)
print('-----------------------------------------------------------')
But, it is giving me the following error:-
[2020-07-23T16:24:43]
0
Traceback (most recent call last):
File "New File.py", line 20, in <module>
rm(t_start,t_end,t)
File "New File.py", line 8, in rm
n=p_name(x)
TypeError: 'str' object is not callable
Any idea what's the issue?
(p.s. i am new to programming, sorry for messy code)
p_name is a list. So you need to use square brackets:
n=p_name[x]
You called the function rm() with last parameter p_name as a string.
t=data[t_start:t_end+1] # this is a string
rm(t_start,t_end, t) # t is a string
Inside the function you assign n = p_name(x) which causes the error.
Did you mean n = p_name[x]?
I am. Pickle loading two files one by one and I am getting an unbound local error while closing them.
I used exception handling while opening the file and in the except block it shows unbound local error while closing the files.
though i used filenotfound In the exception block as it is a necessary exception to handle.no indentation errors are there i just am not able to handle the error stating.
"Traceback (most recent call last):
File "d:\Python\t.py", line 648, in dispdeisel
fdl=open("D:/Python/deisel/"+str(z1)+".txt","rb+")
FileNotFoundError: [Errno 2] No such file or directory: 'D:/Python/deisel/Wed Apr 29 2020.txt'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "d:\Python\t.py", line 820, in <module>
b.dispdeisel()
File "d:\Python\t.py", line 664, in dispdeisel
fdl.close()
UnboundLocalError: local variable 'fdl' referenced before assignment"
k1=[]
try:
tdc=open("D:/Python/deisel/collection.txt","rb+")
fdl=open("D:/Python/deisel/"+str(z1)+".txt","rb+")
while True:
self.f1=pickle.load(tdc)
self.fd=pickle.load(fdl)
k1.append(self.f1)
kd.append(self.fd)
except EOFError and FileNotFoundError:
qa=0
for i in kd:
if "L"in i:
qa1=i[:-1]
qa=qa+int(qa)
else:
qa=qa+int(i[0])
print (" Total Collection for Deisel on date ",z1,"is",qa)
tdc.close()
fdl.close()
In your example code, when this line is reached (and causes an error):
tdc=open("D:/Python/deisel/collection.txt","rb+")
.. then the next line will never be executed and fdl won't have a value.
After the error, execution continues after except EOFError and FileNotFoundError: and this line is reached:
fdl.close()
Since fdl was never defined (as that line was skipped), it has no value and that's the cause of your error.
One way of fixing it would be to deal with the exceptions more cleanly:
class SomeClass:
def some_method(self, z1):
# initialisation
qa = 0
kd = []
k1 = []
try:
tdc = open("D:/Python/deisel/collection.txt","rb+")
try:
fdl = open("D:/Python/deisel/"+str(z1)+".txt","rb+")
try:
try:
while True:
self.f1 = pickle.load(tdc)
self.fd = pickle.load(fdl)
k1.append(self.f1)
kd.append(self.fd)
except EOFError:
pass # no message needed, but not the nicest way to use the exception
for i in kd:
if "L" in i:
# this bit makes no sense to me, but it's not relevant
qa1 = i[:-1]
qa = qa + int(qa)
else:
qa = qa + int(i[0])
print(" Total Collection for Deisel on date ", z1, "is", qa)
finally:
tdc.close()
fdl.close()
except FileNotFoundError:
tdc.close() # this is open, closing it
pass # some error message perhaps?
except FileNotFoundError:
pass # some error message perhaps?
This is better, but not very Pythonic and only illustrates how you could solve your problem - it's not at all how I recommend you write this.
Closer to what you probably need:
import pickle
class SomeClass:
def some_method(self, z1):
# initialisation
qa = 0
kd = []
k1 = []
try:
with open("D:/Python/deisel/collection.txt","rb+") as tdc:
try:
with open("D:/Python/deisel/"+str(z1)+".txt","rb+") as fdl:
try:
while True:
self.f1 = pickle.load(tdc)
self.fd = pickle.load(fdl)
k1.append(self.f1)
kd.append(self.fd)
except EOFError:
pass # no message needed, but not the nicest way to use the exception
for i in kd:
if "L" in i:
# this bit makes no sense to me, but it's not relevant
qa1 = i[:-1]
qa = qa + int(qa)
else:
qa = qa + int(i[0])
print(" Total Collection for Deisel on date ", z1, "is", qa)
except FileNotFoundError:
pass # some error message perhaps?
except FileNotFoundError:
pass # some error message perhaps?
with does exactly what you're trying to do and cleans up the file handle, guaranteed.
And this still has the issue of getting multiple pickles from files, with no guarantee the number of pickles will be the same for both - if you write these pickles yourself, why not pickle a list of objects and avoid that mess?
In general, don't use exceptions if you expect them to occur, instead code directly what you expect - it's easier to read and maintain and it generally performs better:
import pickle
from pathlib import Path
class SomeClass:
def some_method(self, z1):
# initialisation
qa = 0
kd = []
k1 = []
fn1 = "D:/Python/deisel/collection.txt"
fn2 = "D:/Python/deisel/"+str(z1)+".txt"
if not Path(fn1).is_file() or not Path(fn2).is_file():
return # some error message perhaps?
with open(fn1, "rb+") as tdc:
with open(fn2, "rb+") as fdl:
try:
while True:
# not using self.f1 and .fd, since it seems they are just local
# also: why are you loading k1 anyway, you're not using it?
k1.append(pickle.load(tdc))
kd.append(pickle.load(fdl))
except EOFError:
pass # no message needed, but not the nicest way to use the exception
for i in kd:
if "L" in i:
qa1 = i[:-1]
qa = qa + int(qa)
else:
qa = qa + int(i[0])
print(" Total Collection for Deisel on date ", z1, "is", qa)
I don't know about the rest of your code, but you could probably get rid of the EOF exception as well, if you pickle in a predictable way and it seems the load of f1 into k1 only serves the purpose of being a possible limit to how many elements are loaded from kd, which is wasteful.
Note how, with every example, the code gets more readable and shorter. Shorter by itself is not a good thing, but if your code becomes more easy to read and understand, performs better and is shorter on top, you know you're on the right track.
This code is appearing to give me an error to my arguments i don't know what i have done wrong in this code. When attempting to run a binary search inside tkinter using python 2.7 The programs works fine if i don't use the gui just line code. This is the code I have based my program on
http://www.pythonschool.net/data-structures-algorithms/binary-search/
The error is: Exception in Tkinter callback Traceback (most recent call last): File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in call return self.func(*args) TypeError: binarySearch() takes exactly 2 arguments (0 given)
from Tkinter import *
import csv
with open('scoresRecord.csv', 'rb') as f:
reader = csv.reader(f)
your_list = list(reader)
root = Tk()
root.resizable(0,0)
root.title("Score Board")
def binarySearch(myitem,myList):
found = False
bottom = 0
top = len(myList)-1
while bottom<=top and not found:
middle = (bottom+top)//2
if myList[middle]== myitem:
found = True
elif myList[middle] < myitem:
bottom = middle + 1
else:
top = middle-1
return found
if __name__=="__main__":
Scorelist = [row[0] for row in your_list]
Dismissallist =[row[1] for row in your_list] # create a list of only the dismissal
Venuelist =[row[2] for row in your_list] # create a list of only the venue
item = int(input(entScore.get()))
Scorelist = map(int, Scorelist)
rowPos = Scorelist.index(item)
isitFound = binarySearch(item,Scorelist)
if isitFound:
Score= Scorelist[rowPos]
Dismissal= Dismissallist[rowPos]
Venue= Venuelist[rowPos]
else:
Score= ("Not Found")
Dismissal= ("Not Found")
Venue= ("Not Found")
numScoreLbl.configure(text=Score)
numDismissal.configure(text=Dismissal)
outVenue.configure(text=Venue)
#==========GUI Section==================#
First of all, make sure your list is ordered, otherwise the results may be wrong.
Second, do this
Scorelist = list(map(int, Scorelist))#convert to list
isitFound = binarySearch(item,Scorelist)
Although, if you are using .index method, then you can do something like this for better performance:
try:
index = Scorelist.index(item)
isitFound = True
except ValueError:
isitFound = False
It takes out the binary search part, but you were using .index anyways. So this is better. Hope it helps :)
I have the following code that uses 3 strings 'us dollars','euro', '02-11-2014',
and a number to calculate the exchange rate for that given date. I modified the
code to pass those arguments but I get an error when I try to call it with
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
Traceback (most recent call last):
File "currencyManager.py", line 37. in <module>
currencyManager(currTo,currFrom,currAmount,currDate)
NameError: name 'currTo' is not defined
I'm fairly new to Python so my knowledge is limited. Any help would be greatly appreciated. Thanks.
Also the version of Python I'm using is 3.4.2.
import urllib.request
import re
def currencyManager(currTo,currFrom,currAmount,currDate):
try:
currency_to = currTo #'us dollars'
currency_from = currFrom #'euro'
currency_from_amount = currAmount
on_date = currDate # Day-Month-Year
currency_from = currency_from.replace(' ', '+')
currency_to = currency_to.replace(' ', '+')
url = 'http://www.wolframalpha.com/input/?i=' + str(currency_from_amount) + '+' + str(currency_from) + '+to+' + str(currency_to) + '+on+' + str(on_date)
req = urllib.request.Request(url)
output = ''
urllib.request.urlopen(req)
page_fetch = urllib.request.urlopen(req)
output = page_fetch.read().decode('utf-8')
search = '<area shape="rect.*href="\/input\/\?i=(.*?)\+.*?&lk=1'
result = re.findall(r'' + search, output, re.S)
if len(result) > 0:
amount = float(result[0])
print(str(amount))
else:
print('No match found')
except URLError as e:
print(e)
currencyManager(currTo,currFrom,currAmount,currDate)
The command line
python currencyManager.py "us dollars" "euro" 100 "02-11-2014"
does not automatically assign "us dollars" "euro" 100 "02-11-2014" to currTo,currFrom,currAmount,currDate.
Instead the command line arguments are stored in a list, sys.argv.
You need to parse sys.argv and/or pass its values on to the call to currencyManager:
For example, change
currencyManager(currTo,currFrom,currAmount,currDate)
to
import sys
currencyManager(*sys.argv[1:5])
The first element in sys.argv is the script name. Thus sys.argv[1:5] consists of the next 4 arguments after the script name (assuming 4 arguments were entered on the command line.) You may want to check that the right number of arguments are passed on the command line and that they are of the right type. The argparse module can help you here.
The * in *sys.argv[1:5] unpacks the list sys.argv[1:5] and passes the items in the list as arguments to the function currencyManager.
I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").