Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doing "nothing" in else command of if-else clause [duplicate]

Code:

for i in range(1000):
    print(i) if i%10==0 else pass

Error:

File "<ipython-input-117-6f18883a9539>", line 2
    print(i) if i%10==0 else pass
                            ^
SyntaxError: invalid syntax

Why isn't 'pass' working here?

like image 795
Mysterious Avatar asked Apr 25 '18 10:04

Mysterious


People also ask

Can I use if else if without else?

Answer 526897a4abf821c5f4002967 If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed. On the other hand if you need a code to execute “A” when true and “B” when false, then you can use the if / else statement.

How do I make else do nothing in C?

If you want your last else to do nothing, you can use the continue keyword inside it. For any conditional you can define the conditional to do nothing by defining an empty code block {} for it or by simply ommit the case.

How do you make an if statement do nothing in C++?

Answer: use _ = 0 .

How do you do nothing in an else statement in Java?

Simply remove else { return false } .


2 Answers

This is not a good way of doing this, if you see this problem the structure of your code might not be good for your desires, but this will helps you:

 print(i) if i%10==0 else None
like image 96
Mehrdad Pedramfar Avatar answered Oct 18 '22 07:10

Mehrdad Pedramfar


This is not a direct answer to your question, but I would like suggest a different approach.

First pick the elements you want to print, then print them. Thus you'll not need empty branching.

your_list = [i for i in range(100) if i%10]
# or filter(lambda e: e%10 == 0, range(100))
for number in your_list:
    print number
like image 41
marmeladze Avatar answered Oct 18 '22 06:10

marmeladze