Week 7 - More ways to use loops and strings

Liaw Bei Le · May 5, 2021

Loops:

  1. while
  2. break, continue
  3. else (with break, continue)

Strings:

  1. isalpha()
  2. isdigit()
  3. isalnum()

What I learnt:

Loops:

1. while loop
when a condition is fulfilled or if something is True

# Prints out 0,1,2,3,4
count=0
while count < 5:
    print(count)
    count+=1

2. break, continue

  • break is used to exit a “for” or “while” loop
    # Prints out 0,1,2,3,4
    count = 0
    while True:
      print(count)
      count += 1
      if count >= 5:
          break
    
  • continue is used to skip the current block, and return to the “for” or “while” statement
    # Prints out only odd numbers - 1,3,5,7,9
    for x in range(10):
      # Check if x is even
      if x % 2 == 0:
          continue
      print(x)
    

3. else in loops
If ‘break’ is executed inside the for loop, the ‘else’ part is skipped.
The ‘else’ part is executed even if there is a ‘continue’ statement.

# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
    print(count)
    count +=1
else:
    print(f"count value reached {count}")
# Prints out 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("this is not printed because for loop is terminated because of break")

Strings:

string.isalpha( ), string.isdigit( ), string.isalnum( )
Checks if the item is alphabetic, numeric, or alphanumeric
Then, it gives True or False

course_input = input("Please enter the course you are enrolled").upper()
if course_input.isalnum():
    print("your course input is:", course_input)
else:
    print("please input only alpha numeric")

Thoughts

It’s especially great to learn a new type of loop - the ‘while’ loop, in addition to the ‘for’ loop which I have been using. There are many statements in loops that can be used such as pass, break, continue, return, else … and I hope that I will be able to use them well in my codes.

Twitter, Facebook