This question already has answers here:
Using statements on either side of a python ternary conditional
(4 answers)
Closed 4 years ago.
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?
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
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
Related
This question already has answers here:
fit "break IF condition" statement into one line
(3 answers)
Closed 4 months ago.
I'm looking for options of shortening syntax for breaking (and continuing) a loop on a condition
for _ in range(10):
if condition:
break
...
I supposed that short curcuits should work, e.g. x == 2 and break, but they cause SyntaxError.
What are Python's options for one-line conditioning, except if condition: break?
You could use itertools.takewhile to combine aspects of a for and while loop, moving the (negated) break condition to the loop's head. The condition in the lambda can use both variables from the enclosing scope and the current item from the iterable.
from itertools import takewhile
for x in takewhile(lambda x: not condition, iterable):
...
However, while this is shorter (at least in terms of lines), I would not consider it more readable. I would just stick with the explicit break.
This question already has answers here:
How to reuse an expression in a comprehension expression?
(2 answers)
Closed 2 years ago.
I have a code that looks like this:
x = ["hello","world","if"]
test = [len(word) for word in x if len(word)>4]
print(test)
in my original code "len" is much complicated function, is there a way to do the calcualtion of len only once?
in a traditional for loop it can be done like this:
test = []
for word in x:
temp= len(word)
if temp > 4:
test.append(temp)
can you please advise how to achieve the same result without using a traditional for loop.
Thanks
You can use := operator (in case of Python 3.8+):
def my_len(s):
# ...other complicated computations...
return len(s)
x = ["hello","world","if"]
test = [l for word in x if (l:=my_len(word))>4]
print(test)
Note: don't overwrite default built-in functions, in this case len(). Other functions may depend on it.
This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 5 years ago.
I'm trying to create a function that uses a while loop to count up from one to a number given by a user. The code executes as I intend it to but returns None at the end. How do I get rid of the None? Here's the code.
def printFunction(n):
i = 1
while i <= n:
print(i)
i+=1
print (printFunction(int(input())))
You can use this code to prevent none, tough its just the last line changed
def printFunction(n):
i = 1
while i <= n:
print(i)
i+=1
printFunction(int(input()))
In the last line you were using
print(printFunction(int(input()))) which was getting you None after printing the results.
Instead just use printFunction(int(input())). This will not print None. You can also use a message to ask user like printFunction(int(input("Enter a number"))). Since there is noting getting returned you no need to use print.
This question already has answers here:
Syntax error on print with Python 3 [duplicate]
(3 answers)
Closed 6 years ago.
n = [3, 5, 7]
def double_list(x):
for i in range(0, len(x)):
x[i] = x[i] * 2
return x
print double_list(x)
The double_list call on the last line is giving me a SyntaxError.
In Python 3, the print syntax has been changed in order to bring more consistency with the rest of the Python syntax, which uses the brackets notation to call a function.
You must always do print(....) with the brackets, hence the SyntaxError.
print(double_list(x))
However, I do not see the rest of your code, so maybe you also have another iterable called x.
Otherwise you must also replace x by n, to avoid getting a NameError this time.
What is x in double_list(x), and why do you think it has that value?
Did you mean double_list(n)?
This question already has answers here:
Does Python have a ternary conditional operator?
(31 answers)
Closed last month.
How might I compress an if/else statement to one line in Python?
An example of Python's way of doing "ternary" expressions:
i = 5 if a > 7 else 0
translates into
if a > 7:
i = 5
else:
i = 0
This actually comes in handy when using list comprehensions, or sometimes in return statements, otherwise I'm not sure it helps that much in creating readable code.
The readability issue was discussed at length in this recent SO question better way than using if-else statement in python.
It also contains various other clever (and somewhat obfuscated) ways to accomplish the same task. It's worth a read just based on those posts.
Python's if can be used as a ternary operator:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Only for using as a value:
x = 3 if a==2 else 0
or
return 3 if a==2 else 0
There is the conditional expression:
a if cond else b
but this is an expression, not a statement.
In if statements, the if (or elif or else) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting-style.