Week 4

All the function learnt this week 

While :
While loops if we need to put a condition on the how many times we want to repeat it.
(this loop says while i is less than 3, print i.)
Example -  
i = 0while i < 3:  print(i)  i = i + 1012
Looping Breakdown: 
Starting: Are there any variables we need to setup before the loop starts (loop initialisation)? In our example, this was the line:
i = 0
Stopping: How do we know when to stop? called the stopping or termination condition. In our example, this was:
while i < 3:
Doing: What do we want to repeat? This will become the body of the loop control structure. In our example, this was:
print(i)
Changing: Do the instructions change in the state in any way in each repetition? For example, we might need to keep track of how many times we have repeated the body (the number of iterations). In our example, this was:
i = i + 1
Bigger than 1 -Looping :
Example - 
i = 1
while i < 7:
  print(i)
  i = i + 2
1
3
5

Counting
Example - 
j = 6
while j > 3:
  print(j)
  j = j - 1
6
5
4
Checking a string
Example -
msg = 'e'
while msg != 'eeeee':
  print(msg)

  msg = msg + 'e'
Reading multiple lines from the user
Example -
command = input('Enter a command: ')
while command != 'quit':
  print('Your command was:', command)

  command = input('Enter a command: ')
Enter a command: help
Your command was: help
Enter a command: Grok
Your command was: Grok
Enter a command: quit
Looking for blank lines 
Example -
line = input('Enter line: ')
while line:
    print('Still running')
    line = input('Enter line: ')

print('Stopped')
Enter line: f
Still running
Enter line: 

Stopped
Counters Counters count how many times it with loop in while
Example -
guess = input('Guess my favourite colour: ')
counter = 1
while guess.lower() != 'yellow':
  counter = counter + 1 # adds one to the counter
  guess = input('Try again: ')
print('You got it in', counter, 'tries.')
Guess my favourite colour: red
Try again: blue
Try again: orange
Try again: yellow
You got it in 4 tries.
Lopping over characters This combines len functions with the while loop.
Example -
word = 'Grok'
i = 0
while i < len(word):
  print(i, word[i])
  i = i + 1
0 G
1 r
2 o
3 k
Do you use for or while when looping 
When you know how many iterations you need it is easier to use for. It is quicker to write but if not the same program can be written in a while loop, which is longer to write about 4 lines compared to 2.When you don't know how many iterations using while is the better option.

Comments 
If you ever need to write some notes or comments in your coding then use the # sign and python will ignore it.
Example -
# read in a number from the user

No comments:

Post a Comment