You are on page 1of 2

SEN1011, Lab Manual – Week7

Loops

Step1: For loop

Sample For Loops:

for var in range(3):


print(i) #0,1,2

for var in range(1,4):

1. Display even numbers between 2 given limits:

Note: Use % operator to find out a remainder when a


number is divided by another
Sample:remainder = n1 % n2

2. Display the multiplication table of the given number

Note:
• With + operator to add a int statement to a String statement,
int value’s type must be changed to String.
print(String + String) (ok)
print(int + int) (ok)
print(String + int) (wrong)
print(String + str(int)) (ok)
print(int + String) (wrong)
print(int(String) + int) (ok)

• with “,” operator type changing is not necassary.


print(int, String) (ok)
print(String, int) (ok)
Step2: While Loop

Sample While Loop

while password != userInput: #repeats until the correct password is


entered
userInput = input(“enter your password again!”)

1. Guess my number:
User tries to find the number that is assigned to a variable (by
the programmer).
Program gives outputs such as “too low”, “too high” or “you
guessed it”. Program finishes when user finds the number.

In the sample code the hidden number is 50.


Note: break keyword stops the current loop.

2. Calculate the sum of first 9 integers:


Output: 45

Note: Use the following structure to increase a numeric variable a curtain amount of value(2):
number += 2 or number = number + 2

You might also like