Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Tutorial on while and for loops
#1
For and while loops are great ways to repeat and action or perform an action for a purpose other than repeating
First off, while loops. A while loop will continuously repeat everything inside of until a certain criteria is not met. Ex -
count = 0
while count < 10:
    count += 1
    print(count)
The output is the numbers 1 - 10 because it kept looping through until count was 10 and then the while loop stopped and it continued on with the program. While loops will keep repeating and will not continue the code until they stop. I can be shown here -
count = 0
while count < 10:
    count += 1
    print(count)
print('Done')
The output is the same, but it printed "Done" at the end. Another way to use a while loop and still get the same result.
count = 0
while True:
    count += 1
    print(count)
    if count == 10:
        break
print('Done')
"break" is a module that will stop the while loop.
Now for loops. for loops work really well with list, tuples, dictionaries, etc. They also work with strings. Here is an example of a for loop used to copy everything from a tuple to a list (In the future though, use the module "tuple" or "list" for this)
aTuple = (1, 'oof', 32, 12, 'Hello')
aList = []
for x in aTuple:
    aList.append(x)
print(aList)
The result is everything from the tuple into the list. The part where I put "x" can be any word, not sure about a number. So instead of x I could use "character", "y", "word", "tup", etc. Let's say I changed it to "y". It would then read -
aTuple = (1, 'oof', 32, 12, 'Hello')
aList = []
for y in aTuple:
    aList.append(y)
print(aList)
The for loop works by repeating a certain amount of times. If you put a list or tuple it will run the code inside of it FOR every item in the tuple or list. It works the same with a dictionary but runs the code for every key in the dictionary. Here I will use tuples, lists, and dictionaries with a for loop.
aList = [1, 3, 'Hello', 'World']
aTuple = (-1, -3, 'World', 'Hello')
aDict = {}
for item in aList:
    for item2 in aTuple:
        aDict.update({item : item2})
I take an item from aList, make it the key, and take an item from aTuple and make it the definition.
Request 1 - List Comprehension. List comprehension can be used with for loops as followed.
List1 = [1, 2, 3, 4]
List2 = []
multiplier = int(input('Type a multiplier: '))
for num in List1:
    List2.append(num * multiplier)
Here we take a list of numbers from list 1. Then we make an empty list for our output. Next we get a multiplier from the person using this. Finally we take all the numbers in List1, and multiply them by the multiplier into List2. With input, the person can put a letter and that would cause an error when changing the input type to int and when multiplying in the for loop. To stop this we can incorporate a while loop and a try and except.
List1 = [1, 2, 3, 4]
List2 = []
while True:
    try:
        multiplier = int(input('Type a multiplier: '))
        break
    except:
        print('Invalid input, please use an int value for your answer')

for num in List1:
    List2.append(num * multiplier)
What we did here is first the loop. We want to keep asking them until they answer with a valid answer. With the try and except, we determined whether or not they answer validly. If we int their answer properly, the code will continue. If not, instead of giving us an error, it goes to except. We were just trying to do something, so no errors. If we tried it and it didn't work, we go to except, our alternative when we get an error. Then we repeat the same as we did before.

Hope this helped!
Reply
#2
You could add a sample with List Comprehension.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020