1
\$\begingroup\$
i=0
while i<=10:
    i+=1
    if i==5:
        continue
    print i*5

It prints the multiplication table of 5 as well as skips the 5th number in the series

\$\endgroup\$
  • \$\begingroup\$ A good trick is to use a for loop rather than needing to iterate through i in a while loop, for i in range(1, 12) will do this for you rather than needing the i+=1 and the i=0 \$\endgroup\$ – 13ros27 Mar 12 at 11:49
  • 1
    \$\begingroup\$ @13ros27 - that sounds like a review of the code ("Use for instead of while), so should be posted as an Answer, so we can give you some votes! \$\endgroup\$ – Toby Speight Mar 12 at 13:03
5
\$\begingroup\$

This is the longest possible answer to the shortest problem...

How to make better loops in python

  1. iterables
  2. for loops
  3. range
  4. list comprehensions
  5. Generator expressions

How to improve this particular code

  1. what is the simplest way possible of writing it
  2. what is the shortest way possible of writing it

How to make better loops in python

1. iterables

For loops can iterate over any iterables. What is an iterable? An iterable is a object we can iterate through.

More seriously, an iterable is an object that is itself a sequence of other objects. A list is an iterable, but it is not the only one as you will discover when you learn more about python.

2. for loops

A for loop can iterate over an iterable (in this case a list) like so:

for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
    print(i)

3. range

The previous example is ugly because: 1. Hard-coded values can't be easily changed and are prone to mistakes. 2. We stored the first 10 positive integers in memory which take 144 bytes but it isn't scalable as if I want the first 1000000 positive integer, I would need 9 mo of memory.

That's where range comes in, it is an iterable that doesn't take much space and is often used in loops:

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

note: in earlier versions of python, range created a list and was equivalent to the first example.

What if I only want the numbers between 22 and 42 and skip every odd number:

for i in range(22, 43, 2):
    # range(start, end, step) <- this is a comment
    print(i)

note: the range(22, 43) doesn't actually include 43

4. list comprehensions

But wait, I don't want a 5 in my range, how can I remove it ?

for i in range(10):
    if i==5:
        continue
    print(i)

The technical term for continue is "ugly".

What you can use instead is this:

for i in range(10):
    if i!=5:
        print(i)

Which is better, but isn't what I want to show you. What I want to show you is list comprehensions:

l = [n for n in range(10) if n!=5]
for i in l:
    print(i)

A list is an iterable remember. Well, I've created a list containing the first 10 number except 5.

5. Generator expression

Remember also that I've said that a list was a very bad choice due to the memory inefficiency. Well fortunately for us, we have a better solution, generator expressions:

l = (n for n in range(10) if n!=5)
for i in l:
    print(i)

What changed ? Parentheses ! As easy as that.

But wait, I want to do the table of 5. How can I do that ?

l = (n for n in range(10) if n!=5)
for i in l:
    print(i*5)

Yes, that works, but what if...

l = (n*5 for n in range(10) if n!=5)
for i in l:
    print(i)

Yep, that also works...

How to improve your particular code

1. what is the simplest way possible of writing it

for i in range(10):
    if i!=5:
        print(i*5)

2. what is the shortest way possible of writing it

print('\n'.join(str(n*5) for n in range(10) if n!=5))
or 
print(*(n*5 for n in range(10) if n!=5), sep='\n')

As you learn more about python, you might be tempted to use the second one. But it isn't pythonic because it violates at least 6 of Tim Peter's commandment:

Beautiful is better than ugly.<
Explicit is better than implicit.
Simple is better than complex.<
Complex is better than complicated.
Flat is better than nested.<
Sparse is better than dense.<
Readability counts.<
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.<
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

import this to read it at home

Some techniques of looping might be more appropriate in certain cases, but at least now you know what those techniques are.

\$\endgroup\$
  • 1
    \$\begingroup\$ i would have thanked you but stack exchange recomends me to not \$\endgroup\$ – uddhav saikia Mar 12 at 15:54
  • 2
    \$\begingroup\$ Stack Exchange is telling you that because the way you're supposed to thank is by upvoting 🔼 and/or validating ✅ on the left side of the answer. \$\endgroup\$ – Benoît Pilatte Mar 12 at 17:22
  • \$\begingroup\$ i can't upvote because i just started using the site \$\endgroup\$ – uddhav saikia Mar 13 at 11:20
0
\$\begingroup\$

I don't program in Python but this is a pretty simple problem to solve. Here is the code then I will break it down for you

for i in range(0, 10):
     if i != 5:
          print (i*5)

So let's go over this. The first line is a for loop. This kind of loop is kinda like the while loop but it creates and increments the variable for you and has a harder chance of going infinite. The range() part of that line is just saying to start i at 0 and to increment it by 1 until it reaches 10.

The next line is just checking if i == 5 and if so, it will not print that result.

The final line just prints i*5 if i is not 5.

\$\endgroup\$
  • 3
    \$\begingroup\$ Why did you change the equality comparison to use is instead of ==? Using is to compare numbers is unreliable (and therefore considered wrong). Example: print(-6 is (-5-1)) can produce False. \$\endgroup\$ – 200_success Mar 12 at 11:58
  • \$\begingroup\$ @200_success I did not know this. As I stated I do not program in Python and just assume it was one of those stile choices that was made to make the language more readable. Also I tried the example you gave me but Python handled it fine >>> print(-6 is (-5-1)) True \$\endgroup\$ – Tyler Gregorcyk Mar 12 at 12:15
  • \$\begingroup\$ Try the comparison with very large or very negative numbers then. Or with floating-point numbers. \$\endgroup\$ – 200_success Mar 12 at 12:16
  • \$\begingroup\$ @200_success All languages have problem with floating point values because of there inherent disabilities. Do you have any articles I can read talking about the difference of using is instead of ==and the downsides and upsides of each? \$\endgroup\$ – Tyler Gregorcyk Mar 12 at 12:20
  • 2
    \$\begingroup\$ See Is there a difference between "==" and "is"?. Short answer: is tests for identity, where == tests for equivalent values. Compare 1 == 0.5 * 2 and 1 is 0.5 * 2 \$\endgroup\$ – AJNeufeld Mar 12 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.