Match True in python - python

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.

Related

Please explain what "while True !=0 mean

Is while True !=0: valid , if so what does it mean? Because in my program using that or "while True" (by itself) provides the same output. I can't remember why I used it before in my code.
Thanks in advance.
This is used to create infinite loops (or loops that exit via a break or return statement within the loop body). The standard way to do this is:
while True:
...
The other version you showed, while True != 0:, is equivalent, but needlessly convoluted. It works because, when treated as an integer, True has the value 1, so it's equivalent to while 1 != 0: which, in turn, is equivalent to while True:, which is the most direct way to express it.
Yes, while True != 0: is valid and it has the same meaning as while True: which you should use from now on.
This works because int(True) evaluates to 1.
It's simple, true != 0 => 1 != 0 is always 1 (true) .

Is there anyway a return statement can contain an if, elif conditionals without the else at the end?

I've been trying to find the answer everywhere but I can't seem to find it. I want to be able to return a statement in my function with an if and (an) elif/s but without an else (just for learning purposes). I am aware that you can do something like this:
def my_func(s):
return "a list" if type(s) == list else "a string" if type(s) == str else "not list or string"
The above shows how python allows you to have an if, as many elifs and an else, but is there any way to be able to have an if and (an) elif/s without the need of an else at the end?
Something to note is that I am speaking about having it on the same line as the return statement, not an expanded one checking on multiple lines.
If it is single line you can have:
def f(x):
if x > 10: return 10
and you do not (explicitly) have a else keyword being used.
Note that this cannot be chained.
Note also that this is anyway equivalent to:
def f(x):
return 10 if x > 10 else None
as any function not returning explicitly otherwise will just return None.
If you consider multi-line constructs, please note that you can do something like:
def f(x):
if x > 10:
return 10
elif x < -10:
return -10
which does not have an explicit else but is equivalent to both:
def f(x):
if x > 10:
return 10
elif x < -10:
return -10
return None
and:
def f(x):
if x > 10:
return 10
elif x < -10:
return -10
else:
return None
So, all in all, there is not much value in not having an else at the end or not using the a if condition else b expression.
It is probably not ideal for readability to chain multiple if-else expressions anyway. Just use multiple lines and enjoy the readability of the code.
If your sole concern is to know if the conditional expression requires else as part of the Python grammar, then the answer is: Yes it does. See the relevant PEP308 for more info.
No it's not possible. See the language specs and the corresponding pep 308
In case of return just add return something if condition else None
As noted, this is a "conditional expression". Expressions always have to resolve to an object but without the else this expression would not. else None is reasonable.
You can write the same idea using return inside the if statement
'' if (type(s) == list): return ....''
In return x, x is an expression which has to be evaluated to some object, no matter what. So you cannot omit the else part of the ternary operator (that's why it's called ternary and not "ternary or binary" ;-) ). That being said, you could shorten your code:
def my_func(s):
return {list: "a list", str: "a string"}.get(type(s), "not list or string")

Why "if-else-break" breaks in python?

I am trying to use if-else expression which is supposed to break the loop if the if condition fails, but getting an invalid syntax error.
Sample code:
a = 5
while True:
print(a) if a > 0 else break
a-=1
Of course, if I write in the traditional way (not using the one liner) it works.
What is wrong in using the break command after the else keyword?
If I run this, I get the following error:
... print(a) if a > 0 else break
File "<stdin>", line 2
print(a) if a > 0 else break
^
SyntaxError: invalid syntax
This is because
print(a) if a > 5 else break
is a ternary operator. Ternary operators are no if statements. These work with syntax:
<expr1> if <expr2> else <expr3>
It is equivalent to a "virtual function":
def f():
if <expr2>:
return <expr1>
else:
return <expr3>
So that means the part next to the else should be an expression. break is not an expression, it is a statement. So Python does not expect that. You can not return a break.
In python-2.x, print was not a function either. So this would error with the print statement. In python-2.x print was a keyword.
You can rewrite your code to:
a = 5
while True:
if a > 5:
print(a)
else:
break
a -= 1
You can read more about this in the documentation and PEP-308.
If is an expression, break similar to return is a statement. You can't use two statements in a single sentence (unless you use a semicolon which is ugly). I know it would have been really cool if we can do that, but alas that's the way it is.
To put it in slightly simpler terms, you're misusing the 'one-line if statement' (ternary operator). It always evaluates to an expression (i.e., a value). That is,
<expr1> if <condition> else <expr2>
evaluates to <expr1> if <condition> is True, and to <expr2> if <condition> is False. This resulting value can then be used like any Python value, for example:
y = 0
x = (5 if (y > 0) else 6)
print(x) # 6
Of course, the parentheses are completely unnecessary (even discouraged), but hopefully are useful for understanding the meaning of that line.
Therefore,
print(a) if a > 0 else break
tries to evaluate print(a) (which, by the definition of print() in Python 3, always returns None – perfectly valid, but probably not what you usually want) and then break, which does not evaluate to anything because it is a statement (action), not an expression (value), hence the invalid syntax error.
Hence, if you want to execute one of two statements depending on a condition, you really need the multi-line solution proposed by
Willem Van Onsem. There may be hacky ways to do it in one line, but multiple lines is the usual solution for something like this in Python.

Error when trying to return True/False values to a definition in python

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

How do I get a python program to do nothing?

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

Categories

Resources