#🔒 Loops in Python

24 messages · Page 1 of 1 (latest)

peak tangle
#

I still don’t really understand loops, even after several attempts.
I get what while and for loops do in theory, but I struggle to know when and how to use them correctly in code.
What should I do to finally understand them?

magic solarBOT
#

@peak tangle

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

wicked canopy
#

have you learned about strings and lists and maybe any other collections yet?

peak tangle
#

no i learned the basics like print, operators, variables, input, if elif else and everything that has to do with that and now im stuck at loops

wicked canopy
#

you surely have seen strings

#
"this is a string"
peak tangle
#

Yes

wicked canopy
#

have you seen that you can .split() a string into individual words?

peak tangle
#

no i haven't learned string functions yet

wicked canopy
#

!e

my_string = "this is a string"
print(my_string)
print(my_string.split())
magic solarBOT
wicked canopy
#

first line of output is the string, the second line has now turned that string into a list of strings where each string is only one word

#

we can use a loop to iterate through such a list

#

!e

my_string = "this is a string"
for word in my_string.split():
    print(word)
magic solarBOT
wicked canopy
#

so now each print in the for loop prints the current word in the list that the loop is iterating through

viral radish
peak tangle
#

Okay thanks i will try that

wicked canopy
#

and even when you don't know how many times you will need to iterate through for still the one you will be using a lot of the time (iterating through generators, which is a more advanced concept for later, for example)

viral radish
#

indeed, I'll add that while is mostly for you want to stay in a infinite loop until a condition is true. Basic example, open a window and maintain it opened. Then if the X button is pressed boom shut the window

wicked canopy
#

yeah, while is great for loops that should end when a certain condition isn't meet anymore or an infinit loop that you you might break out of when some specific condition is meet

magic solarBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.