How do I get a Python program to do nothing with if statement?
if (num2 == num5):
#No changes are made
You could use a pass statement:
if condition:
pass
Python 2.x documentation
Python 3.x documentation
However I doubt you want to do this, unless you just need to put something in as a placeholder until you come back and write the actual code for the if statement.
If you have something like this:
if condition: # condition in your case being `num2 == num5`
pass
else:
do_something()
You can in general change it to this:
if not condition:
do_something()
But in this specific case you could (and should) do this:
if num2 != num5: # != is the not-equal-to operator
do_something()
The pass command is what you are looking for. Use pass for any construct that you want to "ignore". Your example uses a conditional expression but you can do the same for almost anything.
For your specific use case, perhaps you'd want to test the opposite condition and only perform an action if the condition is false:
if num2 != num5:
make_some_changes()
This will be the same as this:
if num2 == num5:
pass
else:
make_some_changes()
That way you won't even have to use pass and you'll also be closer to adhering to the "Flatter is better than nested" convention in PEP20.
You can read more about the pass statement in the documentation:
The pass statement does nothing. It can be used when a statement is required syntactically but the program requires no action.
if condition:
pass
try:
make_some_changes()
except Exception:
pass # do nothing
class Foo():
pass # an empty class definition
def bar():
pass # an empty function definition
you can use pass inside if statement.
if (num2 == num5):
for i in []: #do nothing
do = None
else:
do = True
or my personal favorite
if (num2 == num5):
while False: #do nothing
do = None
else:
do = True
You can use continue
if condition:
continue
else:
#do something
Related
In JavaScript, using the switch statement, I can do the following code:
switch(true){
case 1 === 1:
console.log(1)
break
case 1 > 1:
console.log(2)
break
default:
console.log(3)
break
}
And it's going to return 1, since JavaScript switch is comparing true === (1 === 1)
But the same does not happen when I try it with Python Match statement, like as follows:
match True:
case 1 = 1:
print(1)
case 1 > 1:
print(2)
case _:
print(3)
It returns:
File "<stdin>", line 2
case 1 = 1:
^
SyntaxError: invalid syntax
And another error is returned if I try it this way:
Check1 = 1 == 1
Check2 = 1 > 1
match True:
case Check1:
print(1)
case Check2:
print(2)
case _:
print(3)
It returns:
case Check1:
^^^^^^
SyntaxError: name capture 'Check1' makes remaining patterns unreachable
What would be the cleanest/fastest way to do many different checks without using a lot of if's and elif's?
In JavaScript, using the switch statement, I can do the following code
I definitely wouldn't be using JavaScript as any form of litmus or comparator for python.
If you used 1==1 in your first test case, the below is what both of your test cases are ultimately doing.
match True:
case True:
print(1)
case False: #will never get hit
print(2)
case _: #will never get hit
print(3)
This is why you get the error for the second version. True will only ever be True, so no other case will ever be hit.
Based on your example, it seems like you are trying to use match/case just to determine the "truthiness" of an expression. Put the expression in the match.
match a==1:
case True:
pass
case False:
pass
If you have a lot of expressions, you could do something like the below, although I don't think this is very good.
a = 2
match (a==1, a>1):
case (True, False):
print('equals 1')
case (False, True):
print('greater than 1')
case _:
print(_)
#OR
match ((a>1) << 1) | (a==1):
case 1:
print('equals 1')
case 2:
print('greater than 1')
case _:
print(_)
cases should be possible results of the match, NOT expressions that attempt to emulate the match. You're doing it backwards. The below link should tell you pretty much everything that you need to know about match/case, as-well-as provide you with alternatives.
Match/Case Examples and Alternatives
If you don't want to use the match statement from Python 3.10, you can create a switch-like statement with a one line function and use it with a one-pass for loop. It would look very similar to the javascript syntax:
def switch(v): yield lambda *c:v in c
for case in switch(True):
if case(1 == 1):
print(1)
break
if case( 1 > 1):
print(2)
break
else:
print(3)
Note that if you don't use breaks, the conditions will flow through (which would allow multiple cases to be executed if that's what you need).
Check if you are using Python 3.10, if not then use this instead and
also the match case isn't meant to be used liked this, you're better off using switch case if you're just trying to print something out
The switch case in python is used by creating a function for an 'if-else-if' statement and declaring the case above like:
match = int(input("1-3: "))
def switch(case): #Function
if case == 1:
print(1)
elif case > 1:
print(2)
else:
print(3)
switch(match) #Main driver
else is the 'default' and you can add as many elif statements.
variable_type = type(variable)
match variable_type:
case list:
pass
case int:
pass
Been trying implement a match-case statement similar to the one above.
case list: -> Irrefutable pattern is allowed only for the last case
case int: -> "int" is not accessed
My current workaround has been using if-elif statements such as below, but I'm confused why the match-case statement is invalid but the if-elif works.
variable_type = type(variable)
if variable_type == list:
pass
elif variable_type == int:
pass
Match won't work in the way you're trying to use it. You can work around it though:
lst = [1, 2]
variable_type = type(lst)
match (variable_type,):
case (list,):
print("It's a list")
case _:
print("It's something else")
As far as I can tell you are using match-case correctly. Are you using the correct version of python?
Match-Case is only available in python 3.10+
I'm trying to make a function where two variables are in one if statement. followed by a(n) == True. It doesn't work, but here's what I tried in a better format.
if var1, var2 == True:
print("This function is correct")
else:
print("This function doesn't work")
but it returned this message:
Invalid Syntax
Is there a way to make this function possible?
Keep in mind that you can take advantage var1 and var2 are booleans, so:
if var1 and var2:
# your logic
Alternative, you can use the all function
if all([var1, var2]):
# your logic
Note: you don't need to check equality for True in a conditional, the point is to take advantage of that.
For determine if both statements are true you can use "and" logical operator.
https://www.w3schools.com/python/python_operators.asp
if var1 and var2:
print("This function is correct")
else:
print("This function doesn't work")
And, if you need to look whether it is true, you don't need to add == True.
For a more general solution to testing if multiple variables are all True, you can use the all function instead of performing multiple and operations:
if all((var1, var2, var3, var4)):
print("This function is correct")
If you are trying to find whether both of the variables are true or false in python you can simply type 'and' between the two arguments(variables) in your if conditions.
I suggest using all().
#Note: all takes only one argument, therefor we have to add var1 and var2 to a iterable.
var1,var2 = True,True
if all((var1, var2)):
print('all true')
output
all true
Another option would be to use .count().
var1,var2 = True,True
trues = [var1,var2]
if trues.count(trues[0]) == len(trues):
print('all true')
for instance say i wanted to print "var is true" only if a variable named myVar = True how would this be possible I've tried a if myVar = True and other methods but none of them seem to work
one = sign is assigning a value, while == is for comparison. so: if myVar == True: is the right way to check that.
Also, in Python you can simply use if myVar: to the same effect.
You might want to use something like this:
if myVar == True:
print("var is true")
You use == to check equality in Python (not to be mistaken with =).
You can also ditch the True and use:
if myVar:
print("var is true")
In Python you can do it in 3 different ways:
if myVar == True:
# code here
if myVar is True:
# code here
if myVar:
# code here
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)