I'm a fairly new Python programmer (started 3 days ago). I'm working as a apprentice for a civil engineer and he asked me to do some simpler tasks for his program, as of the objective I should work with is to not allow numbers from inputs in certain glade objects.
The code I've been struggling with creating is as such:
def testOmHeltal (self, number1):
textviewResultat = self.builder.get_object("textviewResultat")
text = gtk.TextBuffer()
try:
#print number1.get_text()
#temp = number1.get_text() + number1.get_text()
temp = float(number1.get_text())
except ValueError:
text.set_text("ERROR: Endast Nummer")
self.builder.get_object("hboxWarning").show()
self.builder.get_object("image12").show()
self.builder.get_object("textviewResultat").set_buffer(text)
return 0
self.builder.get_object("hboxWarning").hide()
self.builder.get_object("image12").hide()
def quit(self, widget):
sys.exit(0)
This code is called upon at the location of the glade object with this line:
self.testOmHeltal(entryGladeObject)
Now to the problem at hand, I allways get an Float error as such:
File "bvf.py", line 393, in utfora
+float(entryTjockleksskyddslager.get_text<>>>>
ValueError: invalid literal for float<>: 0.04e
0.04e is the invalid input and line 393 is a piece of my Chiefs code, since all he uses is float all the time and I shouldn't meddle with it too much I'm kind of panicking alittle..
I understand that float can only start and end with a number to not give an error, but since my "code" bit wants an error(or rather, an exception) to start the 'hboxWarning' and 'image12' of someone using a letter instead of the supposed number, I'm at a loss at what to do ><
Instead of showing my error with hboxWarning and image12, nothing happens at all...
Any hints or advice would help alot.
I don't know if I understood correctly, but the error is not on your code, right?
All I can assume is that there's a piece of code trying to convert the value to float before your verification. If that's the case, you should verify the value before any processing is done on it, or move the try-except code around the faulty code, depending on the processing itself (for example, if the processing implies database manipulation, it would be safer to do all the verifications previously).
If the error is happening before the line where you run self.testOmHeltal(entryGladeObject), the execution of the signal/method stops right away and your code is never excecuted; that's why the warning isn't showing.
Related
an image of the error message for anyone interested
trying to make a simple version of a language translator to a language I made that is similar to one from Outer wilds. but when I try to execute one of the letters for turtle to draw it says as the image above or
arg1 must be a string, bytes or code object
As I am not an amazing coder, I have no clue what that means.
This is the code that I have written and I want to exec()
There is another image containing the code I want to exec()
if anyone can tell me how to solve this thanks! and if you are able to use more simple python and dumb the answer down an little bit so I can understand then that would also be massively helpful!
if you can't dumb it down for me, no problem!
a = T.fd(20)
b = T.fd(20); T.rt(60); T.fd(20)
Neither of those statements does what you think they do. The first statement calls the fd function immediately (presumably moving the turtle forward by 20), and returns None, so None will be stored in a.
The second line also does a forward 20 and stores that return value in b. It then does a right 60 and a forward 20, but nothing about those will be stored in b. Those are completely separate statements.
The bottom line is, if you want to store up a macro to be executed later with exec, then those lines MUST BE STRINGS. You don't have any strings. So, change your code to:
a = "T.fd(20)"
b = "T.fd(20); T.rt(60); T.fd(20)"
...etc...
Then it will do what you want. This is not the BEST way to do this, because exec is a bad habit, but it will do what you want. The better way would be to do something like:
a = "F20"
b = "F20,R60,F20"
and then write a little interpreter to convert those to turtle movements.
I am facing challenges implementing OOP in python to enable me to call the functions whenever i want , so far i have no syntax errors which makes quite challenging for me . The first part of the code runs ehich is to accept data but the function part does not run.
I have tried different ways of calling the function by creating an instance of it.
print (list)
def tempcheck(self,newList):
temp=newList[0]
if temp==27:
print ("Bedroom has ideal temperature ")
elif temp>=28 or temp<=26:
print ("Bedroom Temperature is not ideal ,either too low or too cold. ")
print ("Please to adjust the temperature to the optimum temperature which is 27 degree Celsuis")
# now to initialize args
def __init__(self,temp,puri1,bedwashroom,newList):
self.temp=temp
self.puri1=puri1
self.bedwashroom=bedwashroom
tempcheck(newList)
# now calling the functions
newvalue=tempcheck(list)
# where list contains the values from the input function.
I expected the function to to check the specific value at the location in the list provided which is called list and also for the function to return a string based on the if statements.
i got it right ,i figured out an alternative to my bug thanks for the critique however any further addition is welcome,
the main goal was to create a function that takes input and passes it to list to be used later i guess this code is less cumbersome
the link to the full code is pasted below
So, I have a function which basically does this:
import os
import json
import requests
from openpyxl import load_workbook
def function(data):
statuslist = []
for i in range(len(data[0])):
result = performOperation(data[0][i])
if result in satisfying_results:
print("its okay")
statuslist.append("Pass")
else:
print("absolutely not okay")
statuslist.append("Fail" + result)
return statuslist
Then, I invoke the function like this (I've added error handling to check what will happen after stumbling upon the reason for me asking this question), and was actually amazed by the results, as the function returns None, and then executes:
statuslist = function(data)
print(statuslist)
try:
for i in range(len(statuslist)):
anotherFunction(i)
print("Confirmation that it is working")
except TypeError:
print("This is utterly nonsense I think")
The output of the program is then as follows:
None
This is utterly nonsense I think
its okay
its okay
its okay
absolutely not okay
its okay
There is only single return statement at the end of the function, the function is not recursive, its pretty straightforward and top-down(but parses a lot of data in the meantime).
From the output log, it appears that the function first returns None, and then is properly executed. I am puzzled, and I were unable to find any similar problems over the internet (maybe I phrase the question incorrectly).
Even if there were some inconsistency in the code, I'd still expect it to return [] instead.
After changing the initial list to statuslist = ["WTF"], the return is [].
To rule out the fact that I have modified the list in some other functions performed in the function(data), I have changed the name of the initial list several times - the results are consistently beyond my comprehension
I will be very grateful on tips in debugging the issue. Why does the function return the value first, and is executed after?
While being unable to write the code which would at the same time present what happened in my code in full spectrum, be readable, and wouldn't interfere with no security policies of the company, I have re-wrote it in a simpler form (the original code has been written while I had 3 months of programming experience), and the issue does not reproduce anymore. I guess there had be some level of nesting of functions that I have misinterpreted, and this re-written code, doing pretty much the same, correctly returns me the expected list.
Thank you everyone for your time and suggestions.
So, the answer appears to be: You do not understand your own code, make it simpler.
I tried writing the code for a problem, but the module won't run. It says invalid syntax, but it's not highlighting anything.
The code: http://pastebin.com/cJVNBcYE
The problem: http://pastebin.com/p8E0E0Nj
I don't understand why it's not working.
I have numDealers set as a variable so that info can be entered in the program. The arrays are all defined. I have index=0 and x=1 to set up the loop for the numDealer arrays for sales and commission. I have another array=index section to calculate commissions. And then I have the prints set up.
Why isn't the program working? I don't understand.
Please post code in future, with a full traceback of the error. However:
else print(sales[index]) and print(comm[index])
should be:
else:
print(sales[index]) and print(comm[index])
i.e. you are missing a colon
I'm a bit puzzled by the and. It means that the second print will only be executed if the first fails (unlikely). Did you mean:
else:
print(sales[index])
print(comm[index])
?
By the way, it appears you are not using arrays but lists. The Python standard library includes a module called array https://docs.python.org/3/library/array.html which you do not appear to be using. So don't have a list called array, that collides with the standard library module name, and can cause no end of confusion.
def travel():
travel.s=0
travel.frate=[]
travel.tr=[]
def accomodation():
print"""specialises
1.place 1
a.hotel 1
b.hotel 2
Hotel1:ac/non ac rooms
Ac.for ac...
Noac.for non ac...."""
hd=[5000,6000]
hg=[4000,7000]
TAc=[1000]
Nac=[400]
ch5=input("Enter your choice")
fav=raw_input("ENter hotel choice")
mode=raw_input("Enter ac/no ac")
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
else:
frate=hd[i]+Nac
if(ch5==2):
for i in range(0,2,1):
frate=hg[i]+TAc
else:
frate=hg[i]+Nac
accomodation()
travel()
When i run the program , i get the error as List Index out of range.but in hd and hg list,there are only two elements, so index number will be from 0 right?? Is there anything i should import?? I even gave statements like this:
travel.frate=travel.hg[i]+TAc
but it still doesn't come.Thank you for your effort.
the indentation is proper now,but the output is still not coming.
The specific issue you are encountering is caused by these lines here:
if(ch5==1):
for i in hd:
frate=hd[i]+TAc
hd[i] looks at hd[5000] and hd[6000] which will throw an IndexError.
But if you fix that, you're going to run into another error, because
frate=hd[i]+TAc
tries to add a list TAc to an integer hd[i], which is an unsupported operation. You probably need frate=hd[i]+TAc[0], or even better, make TAc a number rather than a list. This issue occurs elsewhere in your code as well.
Finally, while not causing explicit issues in your code right now, there are two other problems:
ch5=input("Enter your choice") is dangerous since input tells Python to run whatever code snippet the user enters. In this case, much safer to do ch5=int(raw_input("Enter your choice"))
for i in range(0,2,1): is really for i in range(2): - only use the starting index and jump parameters if you need to change them from their default, namely 0 and 1.
There are other issues like variable scope (you're expecting travel.frate to be modified from within accommodation, but that's not happening) and defining variables in functions like travel.frate (not invalid syntax, but definitely strange) but those are probably better addressed outside of this question.