#🔒 Loops in Python
24 messages · Page 1 of 1 (latest)
@peak tangle
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.
you use loops whenever you need to iterate through something or repeat something, more or less anything, and you will do that very often while programming
have you learned about strings and lists and maybe any other collections yet?
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
Yes
have you seen that you can .split() a string into individual words?
no i haven't learned string functions yet
!e
my_string = "this is a string"
print(my_string)
print(my_string.split())
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | this is a string
002 | ['this', 'is', 'a', 'string']
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)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
001 | this
002 | is
003 | a
004 | string
so now each print in the for loop prints the current word in the list that the loop is iterating through
For => Use it when you know in advance how many times you want it to repeat (for ex: 5times or every element in a list)
while => use it when you don't know in advance how many times it has to be repeated
Okay thanks i will try that
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)
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
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
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.