Computer Science UK Programming Guide Python While Loops







- Slides: 7

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) Programming Guides www. computerscienceuk. com

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) Think about when you log in… “While the password you enter, doesn’t equal the password on your account, the program will repeatedly ask you to enter your password. ” This is an example of a while loop in action! www. computerscienceuk. com

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) ‘While Loops’ in Python While Loops are set up using the following statement: while x < == != > <> >= <= 0: These are called conditions Lets take a look more closely… www. computerscienceuk. com

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) ‘While Loops’ in Python The x is simply a variable. It could have any name. It is however a special kind of variable known as the ‘most recent value’ while x == != > < We must finish the statement with a colon n: The n is simply representing a value that we want x to either equal, not equal, be greater than etc depending on the while loop condition. If n=5 and the condition was while x != 5 (not equal to 5) then the loop would repeat until x equals 5. www. computerscienceuk. com

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) ‘While Loops’ in Python Hello World x=0 while x == 0: print(“Hello World”) Hello World Here is an example of a while loop that will never end. Hello World Because there is never a situation when x can change, the loop will repeat forever. www. computerscienceuk. com

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) ‘While Loops’ in Python 51 -5 122 0 Remember: If you create a condition where a variable is being checked against an integer, you must remember to convert the variable’s input into an integer (e. g. int()) x=0 while x != 5: x = int(input(“Please type in a number”)) Please type in a number: 1 Please type in a number: -5 Please type in a number: 122 Please type in a number: 5 Loop has ended print(“Loop has ended”) Here is an example of a while loop that will stop. Because the statement in the loop is asking for a new value for x, it means that x can be changed and so can stop if the correct value is entered. www. computerscienceuk. com

Computer. Science. UK Programming Guide - Python While Loops (Iteration 2) Example of a while loop in action: www. computerscienceuk. com