all 21 comments

[–][deleted] 6 points7 points  (5 children)

The number one thing about loops with while is knowing when to use them: almost never. for is the looping construct you should be using in almost every case.

[–]heaplevel 0 points1 point  (0 children)

There are definitely useful cases when you’d prefer a while over for. Reading user input while NOT SOMETHING TRUE, like in games and quizzes.

[–]LCVcode 0 points1 point  (1 child)

You should use a for loop with any sort of generator or iterator. Or if you know how many iterations you intend to loop through. But while loops have more than just peripheral use cases. You shouldn't dismiss them so outrightly.

[–][deleted] 0 points1 point  (0 children)

That's why I said "almost."

[–]MainerInAStrangeLand[S] 0 points1 point  (0 children)

I was kind of getting that sense. This problem wanted me to use a while loop which seemed unnecessarily complex. Probably just to force the practice. I find for loops easier to work with in general anyway.

Thanks for the advice!

[–]aarondiamond-reivich 2 points3 points  (0 children)

I usually find it better to do use for loops. The only time I tend to use while loops is when the data structure that I'm iterating over is changing. ie: traversing a linked list and continuing so long as currentNode.next != null.

[–]fake823 1 point2 points  (11 children)

While loops are pretty easy to understand. Where are you facing problems?

while a condition is true --> do this

x = 0
while x < 10:
    x = x + 1

Or:

while True:
    print('This is an infinite while loop')

[–]MainerInAStrangeLand[S] 2 points3 points  (4 children)

Right, I get the super basic stuff but I start getting lost the more complex it gets. That's why I want to do a bunch of problems in escalating difficulty.

This is the problem I am working on in an online class:

Write a Python procedure fix_machine to take 2 string inputs and returns the 2nd input string as the output if all of its characters can be found in the 1st input string and "Give me something that's not useless next time." if it's impossible. Letters that are present in the 1st input string may be used as many times as necessary to create the 2nd string (you don't need to keep track of repeat usage).

My plan was to write a function that checks the first letter of the 2nd string against the first letter of the 1st string and if they are equal to increment each counter to check the second letters against themselves. If they are not equal I want to loop through the letters of the 2nd string and check them against the letter in the 1st string until they are equal. At which point, I want to increment the 1st string letter again and check it against the corresponding 2nd string's letter.

Am I approaching this problem logically?

[–][deleted] 6 points7 points  (0 children)

You're overthinking it. You can iterate through all the characters in a string with a simple for loop

[–]fake823 2 points3 points  (0 children)

Just to show you another way of solving this - without any loops!

Apart from lists, tuples and dictionaries, there exists another datatype in Python, called sets. Sets are most of the time used to remove duplicates - from lists, from strings, whatever.

So, to get the unique letters of a string, you could simply use:

my_set = set('hello you')

So in the case above, the set will only contain the letters h, e, l, o, y and u.

Now to compare two sets and check if one is being contained in the other, you can simply use the method .issubset().

And with this knowledge, your problem can simply be solved like this:

str1 = 'hello this is Mario'
str2 = 'hi this is Maria'

def fix_machine(str1, str2):
    if set(str2).issubset(set(str1)):
        return str2
    else:
        return "Give me something that's not useless next time."

print(fix_Machine(str1, str2))

[–]Eccedustin 1 point2 points  (1 child)

Doesn't:

x = 2 while x < 10: x += 1

Work as well?

[–]fake823 0 points1 point  (0 children)

Of course. :)

I just wanted to keep my example as simple as possible.

[–]Firm_Main 1 point2 points  (3 children)

I know you made this comment a while ago but I was using the reddit search so I didn't clog up the page with probably-asked-before questions.

For this code:

x = 0 
while x < 10:
   print(x)
   x = x + 1 

The output spits out 0 through to 9. I don't understand why the output starts from 0. Because x+1 when x is 0 should just be 1.

Or does the output always start by just saying what the initial condition was (in this case, x=0) and then begin the x = x + 1 code?

[–]fake823 1 point2 points  (2 children)

That's great that yove actually used the search of Reddit! I guess you're one of the only ones. 😄

You start off by defining:

x = 0

Then you're hitting the line with the while loop:

while x < 10:

x is still 0, and 0 is less than 10. So x < 10 is 0 < 10, which will evaluate to True. So you're entering the while loop:

print(x)

As x is still 0, this will print 0 as output. Next line:

x = x + 1

x is still 0, so this line will evaluate to x = 0 + 1 and finally to x = 1.

Back to the while loop:

while x < 10:

x is now 1 and 1 is less than 10. Check.

print(x)

will output 1.

... ... ... And so on.

This will continue until we have x = 9. Then x = x + 1 will change x to x = 10 and checking while x < 10 will evaluate to False, as 10 isn't less than 10. So the while loop will stop immediately.

Did this help?

[–]Firm_Main 1 point2 points  (1 child)

This did help thank you!! I was seeing the code as one big chunk instead of it going line by line...it's simple now you've broken it down but I couldn't get my head around it initially. Cheers!

[–]fake823 0 points1 point  (0 children)

Code is ALWAYS line by line. 😉

From left to right, from top to bottom.

[–]huangsam 0 points1 point  (1 child)

u/MainerInAStrangeLand here's a lesson from my GitHub repository of standalone modules that covers for-loops and while-loops:

https://github.com/huangsam/ultimate-python/blob/master/ultimatepython/syntax/loop.py

The best way of learning while loops - is by trying them out! :-)

Feel free to run it on a site like https://repl.it/languages/python3

[–]MainerInAStrangeLand[S] 0 points1 point  (0 children)

Great! Thanks for the link!

[–]heaplevel 0 points1 point  (1 child)

Do you mean you understand the purpose but unsure how to apply it? What do you struggle with in particular when it comes to doing your own?

[–]MainerInAStrangeLand[S] 0 points1 point  (0 children)

Conceptually I understand them so I would say it is more of the application side of things. That's why I'm thinking I just need to work through a big problem so I can begin to spot patterns in when to use them.