I'm trying to do a simple declaration of an inputted variable to an integer, but am receiving an error:
Bargle. We hit an error creating a run python. :-( Error:
Your code had an error! Traceback (most recent call last): File "/tmp/tmpXq4aAP/usercode.py", line 7, in the_function num = int(input['managers']) KeyError: 'num'
The following is the code i'm using:
num = int(input['num'])
if num >= 100 :
big_num = true
else:
big_num = false
return {'big_num': big_num}
Your error is right here:
num = int(input['num'])
Change those square brackets for round brackets:
num = int(input('num'))
If you are on Python 2 you should use raw_input
num = int(raw_input('num'))
In Zapier, the code:
input['varname']
refers to the variable that is passed in the "Code by Zapier" Action.
The error you are getting sounds to me like you have not defined the num variable prior to your code.
Also, True and False need to be capitalized.
Otherwise, see below, this setup works...
num = int(input['num'])
if num >= 100 :
big_num = True
else:
big_num = False
return {'big_num': big_num}
Many of these answers reference the input() built in - we override that in Code by Zapier (since it literally makes zero sense to have user input on an automated script). In it's place is a dictionary defined by some fields above.
Definitely confusing for folks unfamiliar with the context of Zapier - we'll look into renaming it and just nulling the input build.
Input is a kernel method and it can't be subscriptable , there is an syntax error change the code to like this.
num = int(input('num'))
Within Zapier, the proper way to convert Input Data (every input into a Code Step is a String) to Integers is as follows:
num = int(input.get('num'))
or
num = int(input['num'])
If the number comes attached with a decimal, strip the unwanted characters from the String before converting to an Integer. For a number like 80.0 this would look like:
num = int(input['num'][:-2])
Related
Rudimentary Python/ArcPy skills at work here, not sure where I'm going wrong.
Trying to do a simple random selection of 10 features from a layer to be indicated by the placement of a "1" in another attribute set aside for this purpose. Basic concept is is to use random.sample() to generate a random list of 10 FID's, and then check to see if each FID is in the list. NewID is an attribute containing FID's values. This is what I have in the code block:
import random
def randSelTen():
featurecount = arcpy.GetCount_management("layer_name")
linecount = int(str(featurecount))
lst_oids = range(0, linecount)
rand_lines = random.sample(lst_oids, 10)
if !NewID! in rand_lines:
return 1
else:
return 0
I keep getting a syntax error on the conditional containing !NewID!, and no matter what I do I can't fix it. If I replace !NewID! with an integer, the script runs, but of course the output is bad. Any help is appreciated... thanks!
If you are putting this code in the "Codeblock" of the field calculator then the reason you are getting a syntax error is because you can not access fields like that from the codeblock. You must pass in the field as an argument to the function. So you would have to do this:
# -----Codeblock---------
import random
def randSelTen(NewID):
featurecount = arcpy.GetCount_management("layer_name")
linecount = int(str(featurecount))
lst_oids = range(0, linecount)
rand_lines = random.sample(lst_oids, 10)
if NewID in rand_lines:
return 1
else:
return 0
# ----- Expression (goes in bottom text box of the field calculator if using GUI) -----
randSelTen(!NewID!)
I hoping someone can help with this.
I have created a class with a function in it that counts the total cars in 4 lists of cars.
On another script I am creating the interface and want to say if the answer to 'totalCars' is bigger than zero then proceed to offer a type of car.
However when I do this I get this error: TypeError: '>' not supported between instances of 'method' and 'int'. Here is the code:
def totalCars(self):
p = len(self.getPetrolCars())
e = len(self.getElectricCars())
d = len(self.getDieselCars())
h = len(self.getHybridCars())
totalCars = int(p) + int(e) + int(d) + int(h)
return totalCars
And on the interface script have:
while self.totalCars > 0:
To get around this I tried to use a boolean, like this:
def totalCars(self):
p = len(self.getPetrolCars())
e = len(self.getElectricCars())
d = len(self.getDieselCars())
h = len(self.getHybridCars())
totalCars = int(p) + int(e) + int(d) + int(h)
if totalCars > 0:
return True
And on the app script I have:
while self.totalCars is True
But this totally crashed the program and won't run at all.
Any guidance welcome here.
Many thanks.
That's because self.totalCars is a method and you need to call it to get it's return value by adding a couple parenthesis at the end, like so:
while self.totalCars() > 0:
#Insert the rest here
Otherwise, like the message says, you're comparing a method with a number, and that's not gonna work.
No need to add a boolean, but if you insisted on using one, you could do something like:
while self.totalCars(): #Will run if self.totalCars() RETURNS True
Again, this didn't really work in your original code because you forgot the parenthesis.
Hope this helps.
For your last question, you just need this:
while self.totalCars():
Call the method, but don't check against Trueif it returns a Boolean.
Also
def totalCars(self):
should end with:
return False
You should also point the exact location of the error next time.
Without calling method, no data is return so it can't be compared to a number.
you just add "()"
while self.totalCars > 0:
=> while self.totalCars() > 0:
Same when you are using count,
I had this issue when I were using count
Model1.objects.filter(user=self.user).count > 1
Adding parentheses after count will make it work 👇
Model1.objects.filter(user=self.user).count() > 1
I am trying to write a program asking users to input a positive integer and calculate factorial.
This is what I did
def main():
getN()
fact()
print (n,"! is ",num)
def fact():
num=1
while n>=1:
num=num*n
n=n-1
return num
def getN():
n=input("Enter a positive integer: ")
if not n%1==0:
print("Enter a positive integer: ")
return n
main()
But when I run this code, I got the error saying type error: not all arguments converted during string formatting.
I have to get a postivie integer and want to use getN function to guarantee that it is a positive.
Please help me.
Thank you in advance.
When you get an error message, it's always a good idea to post the whole error message including the stack trace. Your question should be self explaining without code if possible. So provide the error message but also analyze the error message yourself.
Traceback (most recent call last):
File "/home/labbi/git/sandkasten/sandkasten.py", line 21, in <module>
main()
File "/home/labbi/git/sandkasten/sandkasten.py", line 2, in main
n1 = getN()
File "/home/labbi/git/sandkasten/sandkasten.py", line 17, in getN
if not n%1==0:
TypeError: not all arguments converted during string formatting
The error message says the TypeError occurred on line 17 which is the operation in your if statement. The only string can be contained in the variable n.
Your problem is that input() on line 16 returns a string so you can't use it for numeric operations. You can convert strings with int() as bellow.
When you have fixed it you will also notice a few mistakes in your main function. You're calling fact() and getN(). Both return values but you don't store them even though you're trying to use the returned values.
def main():
n_result = getN()
num_result = fact(n_result)
print (n_result,"! is ",num_result)
def fact(n):
num=1
while n>=1:
num=num*n
n=n-1
return num
def getN():
n = int(input("Enter a positive integer: "))
if not n%1==0:
print("Enter a positive integer: ")
return n
main()
Furthermore for readability reasons I would also like to point you to the python style guide, especially to the chapter about whitespace.
Bit of a tricky error message, but if not n%1 == 0: is an attempt to perform mod division, however n is still a string. You need to cast the input to int with
n=int(input("Enter a positive integer: "))
Your code still won't work however, because you are referencing variables everywhere before their assignment, and in functions for which they are not defined. I would consider re-arranging the order of your functions, and ensuring that all relevant parameters necessary for each function are passed - currently you don't use function parameters at all.
As an aside, you got that error message because % is also used in string formatting operations to mark the start of a conversion specifier. See the docs.
Use this code
def factorial():
i = int(input())
mul = list(range(1, int(i)))
for eve in mul:
i = i * eve
return i
print(factorial())
I made a program in python that is supposed to accept a name as user input. It will then check if the name given is contained inside a string that is already given and if it is then the program will print out the telephone next to that name. My code is as follows:
tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217"
check=str(input("Give a name: "))
for check in tilefwnikos_katalogos:
if check=="Christoforos":
arxi=check.find("Christoforos")
elif check=="Eirini":
arxi=check.find("Eirini")
elif check=="Costas":
arxi=check.find("Costas")
elif check=="George":
arxi=check.find("George")
elif check=="Panayiotis":
arxi=check.find("Panayiotis")
elif check=="Katerina":
arxi=check.find("Katerina")
s=check.find(" ",arxi)
arxi=s
y=check.find(":",arxi)
telos=y
apotelesma=tilefwnikos_katalogos[arxi+1:telos]
print(apotelesma)
But when I try to run it, I input the name and then the following message pops up:
Traceback (most recent call last):
File "C:\Users\Sotiris\Desktop\test.py", line 16, in <module> s=check.find(" ",arxi)
NameError: name 'arxi' is not defined
What am I doing wrong?
You're getting your error because arxi isn't getting defined in the first place when then name the user gave is not present on your list.You can fix that by simply adding an unconditional else case to your if/else if bundle as pointed in the comments. But the very way you tackled this problem is faulty, storing data like this in a string is a bad idea, you want to use a dictionary:
phone_catalog = {'Christoforos': 99111111, 'Eirini': 99556677, 'Costas': 99222222, 'George':99333333, 'Panayiotis':99444444, 'Katerina': 96543217}
Also check isn't a very clear variable name, maybe you should try using something better like:
user_name = str(input("Give a name: "))
And now you can do your if/elif condition but replacing it for using dictionary logic and making sure you have a final else, like such:
if user_name in phone_catalog:
print(phone_catalog[user_name])
else:
print("Unknown user")
See how the dictionary made your life much easier and your code cleaner here? Read more on Python Data Structures.
so there are a few things you have overlooked / not going as expected, the first of which is how iterating over strings in python works:
tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217"
for check in tilefwnikos_katalogos:
print(check)
#print(repr(check)) #this shows it as you would write it in code ('HI' instead of just HI)
so check can never be equal to any of the things you are checking it against, and without an else statement the variable arxi is never defined. I'm assuming you meant to use the check from the user input instead of the one in the loop but I'm not sure you need the loop at all:
tilefwnikos_katalogos = "Christoforos 99111111: Eirini 99556677: Costas 99222222: George 99333333: Panayiotis 99444444: Katerina 96543217"
check=str(input("Give a name: ")) #the str() isn't really necessary, it is already a str.
if check=="Christoforos":
arxi=check.find("Christoforos")
elif check=="Eirini":
arxi=check.find("Eirini")
elif check=="Costas":
arxi=check.find("Costas")
elif check=="George":
arxi=check.find("George")
elif check=="Panayiotis":
arxi=check.find("Panayiotis")
elif check=="Katerina":
arxi=check.find("Katerina")
else: raise NotImplementedError("need a case where input is invalid")
s=check.find(" ",arxi)
arxi=s
y=check.find(":",arxi)
telos=y
apotelesma=tilefwnikos_katalogos[arxi+1:telos]
print(apotelesma)
but you could also just see if check is a substring of tilefwnikos_katalogos and deal with other conditions:
if check.isalpha() and check in tilefwnikos_katalogos:
# ^ ^ see if check is within the string
# ^ make sure the input is all letters, don't want to accept number as input
arxi=check.find(check)
else:
raise NotImplementedError("need a case where input is invalid")
although this would make an input of C and t give Cristoforos' number since it retrieves the first occurrence of the letter. An alternative approach which includes the loop (but not calling the variable check!) would be to split up the string into a list:
tilefwnikos_katalogos = "..."
check = input(...)
for entry in tilefwnikos_katalogos.split(":"):
name, number = entry.strip().split(" ")
if check == name:
apotelesma=number
break
else:
raise NotImplementedError("need a case where input is invalid")
although if you are going to parse the string anyway and you may use the data more then once it would be even better to pack the data into a dict like #BernardMeurer suggested:
data = {}
for entry in tilefwnikos_katalogos.split(":"):
name, number = entry.strip().split(" ")
data[name] = number #maybe use int(number)?
if check in data:
apotelesma = data[check]
else:
raise NotImplementedError("need a case where input is invalid")
I want to print the result of the equation in my if statement if the input is a digit and print "any thing" if it is a letter.
I tried this code, but it's not working well. What is wrong here?
while 1:
print '\tConvert ciliuse to fehrenhit\n'
temp = input('\nEnter the temp in C \n\t')
f = ((9/5)*temp +32)
if temp.isdigit():
print f
elif temp == "quit" or temp == "q" :
break
elif temp.isalpha() :
print ' hhhhhhh '
You need to go through your code line by line and think about what type you expect each value to be. Python does not automatically convert between, for example, strings and integers, like some languages do, so it's important to keep types in mind.
Let's start with this line:
temp = input('\nEnter the temp in C \n\t')
If you look at the documentation for input(), input() actually calls eval() on what you type in in Python 2.x (which it looks like you're using). That means that it treats what you type in there as code to be evaluated, just the same as if you were typing it in the shell. So if you type 123, it will return an int; if you type 'abc', it will return a str; and if you type abc (and you haven't defined a variable abc), it will give you an error.
If you want to get what the user types in as a string, you should use raw_input() instead.
In the next line:
f = ((9/5)*temp +32)
it looks like you're expecting temp to be a number. But this doesn't make sense. This line gets executed no matter what temp is, and you're expecting both strings containing digits and strings containing letters as input. This line shouldn't go here.
Continuing on:
if temp.isdigit():
isdigit() is a string method, so here you're expecting temp to be a string. This is actually what it should be.
This branch of the if statement is where your equation should go, but for it to work, you will first have to convert temp to an integer, like this:
c = int(temp)
Also, to get your calculation to work out right, you should make the fraction you're multiplying by a floating-point number:
f = ((9/5.0)*c +32)
The rest of your code should be okay if you make the changes above.
A couple of things first - always use raw_input for user input instead of input. input will evaluate code, which is potentially dangerous.
while 1:
print "\tConvert ciliuse to fehrenhit\n"
temp = raw_input("\nEnter the temp in C \n\t")
if temp in ("quit", "q"):
break
try:
f = ((9.0 / 5.0) * float(temp) + 32)
except ValueError:
print "anything"
Instead of using isalpha to check if input is invalid, use a catch clause for ValueError, which is thrown when a non-numerical value is used.
Why isn't it working? Are you getting an error of any kind?
Straight away I can see one problem though. You are doing the calculation before you verify it as a number. Move the calculation to inside the if temp.isdigit().
Take a look at this for some examples:
http://wiki.python.org/moin/Powerful%20Python%20One-Liners
OK, this works. Only problem is when you quit, you get dumped out of the interpreter.
while 1: import sys; temp=raw_input('\nEnter the temp in C \n\t'); temp.isdigit() and sys.stdout.write('%lf' %((9./5)*float(temp)+32)) or temp=='q' and sys.exit(0) or sys.stdout.write(temp)