a = [1,2,3,4]
while True:
print(a[2])
Hey @wleong9, welcome to the forums!
To stop a loop you use the break argument!
So your code will be this :
a = [1,2,3,4]
while True:
print(a[2])
break
welcome to the community @wleong9!
You can use an if
statement and the break
argument
while True:
print(a[2)
if something == somethingelse: #you can change this.
break #end loop
When using loops, you should add a condition to your loop rather than doing while True
there are only a few cases where while True
is a good thing.
Most of the time your while loops should look like this:
while # some condition:
# do some code
# e.g.
while a < b:
print(a)
a += 1
Hii @wleong9, Welcome To The Community
Also You Can Use for loop
To Print All Characters From Variable a
Like This :
a = [1,2,3,4]
for i in a:
print(i)
After Printing All Characters This Loop Breaks Automatically Without Break Argument
If You Want To Stop This Loop After A Specific Character So You Can Use if
Statement With break
Argument Like This :
a = [1,2,3,4]
for i in a:
print(i)
if i == 2:
break
Note : I Don’t Know English So Much
Hey there! Welcome to the community first of all!
Second of all, you said you are new to python. I would suggest using freecodecamp to learn. Hope you have a good time here!
Hello there, @wleong9. There are several ways to break the loop, such as the break
.
Examples:
a = [1, 2, 3, 4]
for x in a:
if x in (2, 4):
break
or
a = [1, 2, 3, 4]
while True:
print(a[2])
break # abruptly stops the code from proceeding.
Oh!!! no wonder, I haven’t learn till that lesson, that’s why I don’t know how to stop it. Thank you for the answer. Appreciate.
Gotcha!! Thank you. The lesson haven’t teach till break yet. no wonder! Thank you.
Thank you!! Will go to the page and learn from it, sorry because I am interested in Programming but don’t know where to start from, so I choose start with Python.
Hey @hugoondev , Thank you for reply me with the solution, and sorry because I am interested in Programming but don’t know where to start from, so I choose start with Python.
Your very welcome! Keep coding!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.