0
Q:

python what is the syntax for while loops

while 10 > 8:
  print("Hello")
while not False:
  print("Hello")
while True:
    print("Hello")
1
# While Loops
# Basic syntax:
while condition_to_check:
  something you want to do as long as condition_to_check is true
  something else you want to do as long as condition_to_check is true

# Note, make sure that the condition_to_check will return false at some
# 	point, otherwise you'll be stuck in an infinite loop
# Note, for more complicated conditions_to_check, you may need to use
# 	parentheses to clarify the argument. E.g.:
#	while (i < 10 and (j >= 5 or k == "some_text")):
# Note, the stuff you do during each iteration is indicated by indenting
# 	it (tab or 4 spaces) - you don't need to surround it in braces { }
# Note, use break to exit the loop entirely if some condition is true and
# 	use continue to skip to the next iteration if some condition is true

# Example usage:
i = 0
while i < 3: # Continues as long as i less than 3 = TRUE
  print(i)
  i += 1 # += is shorthand for: i = i + 1
--> 0 # Python is 0-indexed, so zero is printed first
--> 1
--> 2

# Example usage 2:
i = 0
while i < 3:
  print(i)
  i += 1
else:
  print("Something to do once, immediately after the loop terminates")
--> 0
--> 1
--> 2
--> Something to do once, immediately after the loop terminates

# Example usage 3:
i = 0
while i < 6:
  if i == 2:
    i += 1
    continue # If i = 2, continue skips to the next iteration of the loop
  if i == 4:
    break # If i = 4, break exits the loop entirely
  print(i)
  i += 1
--> 0
--> 1
--> 3
2
while <Condition>:
  <code>
  
  #example
  i = 10
  while i == 10:
    print("Hello World!")
2
a = 0
while a < 11:
  a += 1
  print(a)
0

New to Communities?

Join the community