I have the following code:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
else:
pass
return False
What i need to know the following: in case the if condition evaluates to true, will the function stop looking in the list and never return False? Or do i need a break statement?
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
for x in geodatabaseList:
if x == self.outputGeodatabase:
return True
break
else:
pass
return False
If the following code does not solve my problem, what can i use to do simulate that behavior?
Thanks
return is the end of the line, and nothing else will happen in that function afterwards. On the other hand, you could rewrite your function as
def testGeodatabase(self):
return self.outputGeodatabase in self.gp.ListWorkspaces("*","ALL")
You don't need the break keyword in the code above. Actually, you don't need the
else:
pass
either. The
return True
will exit the function.
The return statement will indeed cause the function to be exited at that point. No further code is executed in the function.
Here is a simple test which you could run to prove the point:
def someFunction(nums):
for i in nums:
if i == 1:
return "Found 1!"
return "Never found 1"
And running it:
>>> someFunction([2])
'Never found 1'
>>> someFunction([2,1,3])
'Found 1!'
I think that using any() is the best choice:
def testGeodatabase(self):
geodatabaseList = self.gp.ListWorkspaces("*","ALL")
return any(x == self.outputGeodatabase for x in geodatabaseList)
Related
The return true statement is executed only when the if statement is true, but shouldn't the code return False too, irrespective of the if statement because it is out of indentation? I don't understand how this works...
def booll(x):
if x == 0:
return True
return False
When a return statement is reached, the execution of the function is ended.
when output is returned by the function , the method is popped out of call stack hence no further executuin happens
The function will only return once, in either 1 of the scenarios:
If the if statement is satisfied, it returns True and the
function ends.
If the if statement is not satisfied, it will run to the end of
the function and return False.
When you call return, it stops a function and exits with the value provided to return.
For example,
def return_example():
print("This runs")
return 0
print("This doesn't run")
In the example, the function prints "this runs", and then exits with the value 0. In your example, booll returns True if x == 0. If x == 0, then booll exits with True. If x isn't 0, then it returns False. The return True doesn't run.
In your code , the phrase return False will be executed every time you call the code if your if conditional is false.
and return False totally independent of if statement. and the function execution stops when the first return statement is reached.
Your given code is similar to the code of if else block.
def booll(x):
if x == 0:
return True
else:
return False
make sure that indentation is correct otherwise you will run to error.
I am not clearly getting what logic you are trying to execute. Can you please explain a bit more about it.
Well, a function execution ends when it returns a value. So, when the function has returned True, its execution has stopped, and thus, it does not go to the next line.
If you want the function to 'return' multiple times, you can use the yield keyword, in this way:
def booll(x):
if x == 0:
yield True
yield False
How can I check if a number is composed by a single digit?
Here is what I have tried so far:
n=5
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if ???
return True
else:
return False
The output in this case should be `True
`
I'm not saying it's the best way to do it, but it's probably what you meant to do:
def digit(n):
for i in [0,1,2,3,4,5,6,7,8,9]:
if n == i:
return True
else:
return False
digit(5)
Output:
True
Please pay attention that the else clause is not part of the if, but part of the for, which means that it will be executed only if the loop ended without any return or break during the iterations. You can also not use the else at all, and just return False after the loop.
You can simply do
def isdigit(n):
return n in range(10)
I could look up the right answer, but I am just so certain I am correct as I get this to pass all my tests in IDLE, but on my online course it only partially passes - any reason why?
def is_isogram(txt):
if len(list(txt)) == len(set(txt)):
return True
else:
return False
It might be that you aren't accounting for a string with upper and lowercase letters. Using either str.upper or str.lower might be the solution. If that is the case, something like this could do it in one pass.
def is_isogram(txt):
seen = set()
for char in txt.lower():
if char in seen:
return False
seen.add(char)
return True
Mostly it is failing due to case sensitive issue. Why don't you add lower() to your code and try it:
def is_isogram(txt):
if len(list(txt.lower())) == len(set(txt.lower())):
return True
else:
return False
the below made me pass my quiz, I did need to account for lower/upper!
def is_isogram(txt):
txt = txt.lower()
if len(list(txt)) == len(set(txt)):
return True
else:
return False
I'm currently reading and doing each and every of the exercises in John Guttag's Introduction to Computation and Programming Using Python. One particular problem I cannot solve for the life of me:
Write a function isIn that accepts two strings as arguments and
returns True if either string occurs anywhere in the other, and False
otherwise. Hint: you might want to use the built-in str operation in.
I went through every discussion I could find here, tried with both in and find, constantly changing something in the code, but every time I would run my program to check if 'abc' occurs in 'efg' the answer would be True.
Any idea how to solve it? Again, I need to write a function, not simply go with in like:
x='abc'
y='efg'
if x in y:
# Blah
else:
# another Blah
The code I wrote (I'm adding this as apparently some would like to see it) was basically this:
def isIn(x,y):
if x in y or y in x:
return True
else:
return False
a='abc'
b='efg'
isIn(a,b)
if True:
print "True"
else:
print "False"
The problem is that you are completely ignoring the return value of the function isIn, and the reason why you always get True printed by the code is that the condition you are checking in the if statement is the boolean constant True, which is of course always True.
Try changing your code to:
a='abc'
b='efg'
r = isIn(a,b)
if r:
print "True"
else:
print "False"
Simply put:
x=input('Enter string #1: ')
y=input('Enter string #2: ')
#can also just define x and y separately in the console and invoke the
# function on those values
def isIn(x,y):
if x in y:
return True
elif y in x:
return True
else:
return 'False'
print(isIn(x,y)) #invokes and prints the results of the function evaluating
#the x and y the user inputs; otherwise nothing is returned
I'm getting the impression that you are a newcomer to Python, so here is the solution to your problem below laid out just as the question asks :)
def isIn(string_1, string_2): #This is the function that returns true/false
if (string_1 in string_2) or (string_2 in string_1):
is_in = True
else:
is_in = False
return is_in
if __name__ == "__main__":
string_1 = input ("String 1 here: ")
string_2 = input ("string 2 here: ")
is_in = isIn(string_1, string_2) #Calls function with strings as parameters
print (is_in) #Prints the evaluation of the function after it has run
The problem with your code was that you say if True, but you aren't giving it anything to check against. if True on its own is always true.
If you want me to explain how this code works in more detail I'd be happy to do so :)
you are not printing the isIn(x,y)
def is_in(x,y):
if x in y or y in x:
return True
else:
return False
print(is_in("hello","hello world"))
try this :)
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for i in range(2,x):
if x % i == 0:
return False
break
else:
return True
The above code is mine from codecademy's python course, and i get a prompt telling me that when 9 is passed to the argument, the function returns True instead of False. I can fix this by doing:
for i in range(2,x):
if x % i == 0:
return False
break
return True
I don't understand why the second bit of code works, and why the first bit doesn't. In fact, I would have thought the second bit of code wouldn't work: If the argument was 9, then when i == 3, x % i == 0. So the function gets a returned value of False, and the loop breaks. However, since the "return True" is NOT within the for loop, then after exiting the for loop, "return True" will execute anyway, so regardless of the input, the function will get returned a value of True, since that's the last line of code to be executed within the function?
Following that line of reasoning, I believed that my initial code would work, because if "return True" was within the for loop, then the break command would be executed (assuming the input was 9), AFTER the function has been returned a value of False. And since the "return True" line is within the the for loop, and since the break command will exit the for loop, then the last value given to the function would have been False, which would have been correct?
I apologise in advance if I have (very likely) misused certain terms, of have some flaw in my understanding of how the code works or is executed. I just can't seem to get my head around why the second bit of code works, but the first bit doesn't.
Cheers!
The for loop starts with i == 2. 9 % 2 == 1, so it goes into the else: branch, and returns True.
Only if the entire loop is run and none of the numbers divided 9 should you return True.
Also, following return ... by break is useless - the function has already returned, so that break statement is never reached.
That's also the answer to your last question -- when return is executed, this function ends. Nothing else is done anymore, and the program continues (returns to) wherever it was when it called the function.
The first version didn't work because , when ever the if condition is false it returns True.Thus, when x==9 and i==2, 9%2!=0, thus it returns true. Also, no need to use break statement as return statement returns the value from function and loop doesn't continue after return.
Following is the correct code
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for i in range(2,x):
if x % i == 0:
return False
return True