Python Key Skills - 2
Table of Contents
1 Python Key Skills 2
Learn It - for loops and while loops
- The purpose of loops is to repeat a set of commands or a block of code
for loops
- for loops are normally used to repeat a set of commands for a specific known number of times.
for i in range(5): print("Hello world!")
- the above code will print out "Hello world!" 5 times with i starting from 0, increasing each loop by 1, up to 4.
- the range is a Python built-in function that produce a series of numbers.
while loops
- while loops are normally used to repeat a set of commands until certain condition(s) are no longer true.
- Example while loop 1:
i=0 while i < 5: print("Hello world!") i = i + 1
- Example while loop 2:
hungry = True while hungry: print("I need eat more.") answer = input("Are you still hungry?(Y/N)") if answer == "N": hungry = False
- The above loop will end if the user input "N", which changes the hungry variable to "False". This means, the condition is not true anymore.
Learn It - check if a whole number is even or odd
- We know from maths that all even numbers can be divisible by 2. In other words, any even number, when divided by 2, the reminder should be 0 - no reminder.
- In Python, we have learned that the reminder operator is %. For example: 24%2 = 0; 25%2=1; 1%2=1 etc
- So if the reminder is 0 when divided by 2, then the number is even.
myNum = int(input("Please give me a whole number: ")) if myNum % 2 == 0: print("The number you game to me is an even number") else: print("The number you game to me is an odd number")