how do i condense the loop and if else

  • Last Update :
  • Techknowledgy :

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

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

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()

Suggestion : 2

2018-04-11

Let’s say you have nine TV show titles put into three categories: comedies, cartoons, dramas. These are presented in a nested Python list (“lists in a list”):

my_movies = [
   ['How I Met Your Mother', 'Friends', 'Silicon Valley'],
   ['Family Guy', 'South Park', 'Rick and Morty'],
   ['Breaking Bad', 'Game of Thrones', 'The Wire']
]

How would you do that? Since you have three lists in your main list, to get the movie titles, you have to iterate through your my_movies list — and inside that list, through every sublist, too:

for sublist in my_movies:
   for movie_name in sublist:
   char_num = len(movie_name)
print("The title " + movie_name + " is " + str(char_num) + " characters long.")

Here’s the solution!

for i in range(100):
   if i % 3 == 0 and i % 5 == 0:
   print('fizzbuzz')
elif i % 3 == 0:
   print('fizz')
elif i % 5 == 0:
   print('buzz')
else:
   print('-')

Note 1: One can solve the task with a while loop, too. Again: since I haven’t written about while loops yet, I’ll show you the for loop solution.
Note 2: If you have an alternative solution, please do not hesitate to share it with me via email!

down = 0
up = 100
for i in range(1, 10):
   guessed_age = int((up + down) / 2)
answer = input('Are you ' + str(guessed_age) + " years old?")
if answer == 'correct':
   print("Nice")
break
elif answer == 'less':
   up = guessed_age
elif answer == 'more':
   down = guessed_age
else:
   print('wrong answer')

STEP 2) The script always asks the middle value of this range (for the first try it’s 50):

guessed_age = int((up + down) / 2)
answer = input('Are you ' + str(guessed_age) + " years old?")
if answer == 'correct':
   print("Nice")
break
elif answer == 'less':
   up = guessed_age
elif answer == 'more':
   down = guessed_age
else:
   print('wrong answer')

Suggestion : 3

The conditional statement can be used to combine with for loop and return the iterator based on the condition specified inside it.,The conditional statements can be used multiple times in combination with a for loop in List comprehension. It returns the iterator based on the conditions specified inside them.,In this example, we are creating a list comprehension to return the iterator only if the below conditions satisfy.,If you want to combine a for loop with multiple conditions, then you have to use for loop with multiple if statements to check the conditions. If all the conditions are True, then the iterator is returned.

Syntax:

[iterator
   for iterator in iterable / range(sequence) if (condition)
]
  1. Return only the elements that are divisible by 2, with the condition – if (iterator%2==0)
  2. Return only the elements that are divisible by 5, with the condition – if (iterator%5==0)
  3. Return only the elements that are greater than 4, with the condition – if (iterator>4)
# Create a list comprehension and
return only
# the numbers that are divisible by 2 from the list
# of 10 integers
mylist_comprehension = [iterator
   for iterator in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   if (iterator % 2 == 0)
]

#return the list
print(mylist_comprehension)

# Create a list comprehension and
return only
# the numbers that are divisible by 5 from the list
# of 10 integers
mylist_comprehension = [iterator
   for iterator in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   if (iterator % 5 == 0)
]

#return the list
print(mylist_comprehension)

# Create a list comprehension and
return only
# the numbers that are divisible by 4 from the list
# of 10 integers
mylist_comprehension = [iterator
   for iterator in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
   if (iterator > 4)
]

# Print the list
print(mylist_comprehension)

Output:

[2, 4, 6, 8, 10]
[5, 10]
[5, 6, 7, 8, 9, 10]
  1. Select the elements that are divisible by 2 from the list and replace others by 0.
  2. Select the elements that are divisible by 5 from the list and replace others by 0.
  3. Select the elements that are greater than 4 from the list and replace others by 0.
# Create a list comprehension and look
for
# numbers which are divisible by 2
myList = [num
   if (num % 2 == 0)
   else 0
   for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
]

# Print the list
print(myList)

# Create a list comprehension and look
for
# numbers which are divisible by 5
myList = [num
   if (num % 5 == 0)
   else 0
   for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
]

# Print the list
print(myList)

# Create a list comprehension and look
for
# numbers which are divisible by 4
myList = [num
   if (num % 4 == 0)
   else 0
   for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
]

# Print the list
print(myList)

In this example, we will check the elements are divisible by 2 or 5 from the list.

# Create a list and using comprehension look
for numbers which
# are divisible by 2 or 5
myList = [str(num) + ' is Multiple of 2'
   if num % 2 == 0
   else
      str(num) + ' is Multiple of 5'
   if num % 5 == 0
   else str(num) + ' is Not a Multiple of 5 & 2'
   for num in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
]

# Print the List
print(myList)

Suggestion : 4

As it turns out, we can use the ternary operator in Python that allows us to compress an if statement into a single line. ,Check out this tutorial on our blog if you want to learn more about the exciting ternary operator in Python. ,You can also modify the list comprehension statement by restricting the context with another if statement:,Being hated by newbies, experienced Python coders can’t live without this awesome Python feature called list comprehension.

Say, we want to write the following for loop in a single line of code:

>>>
for i in range(10):
   print(i)

0
1
2
3
4
5
6
7
8
9

We can easily get this done by writing the command into a single line of code:

>>>
for i in range(10): print(i)

0
1
2
3
4
5
6
7
8
9

Suppose, you have the following more complex loop:

for i in range(10):
   if i < 5:
   j = i ** 2
else:
   j = 0
print(j)

The answer is yes! Check out the following code snippet:

for i in range(10): print(i ** 2
   if i < 5
   else 0)

Say, we want to create a list of squared numbers. The traditional way would be to write something along these lines:

squares = []

for i in range(10):
   squares.append(i ** 2)

print(squares)
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]