According to Data Science Topic-14 While loop examples
# While loop example -> program to print the table
# Program -> Sum of all digits of a given number
# Program -> Keep accepting numbers from users till he/she enters a 0 and then find the average
number = int(input('enter the number'))
i = 1
while i <= 11:
print(number, 'x', i, '=', number * i)
i = i + 1
Result: enter the number11
11 x 1 = 11
11 x 2 = 22
11 x 3 = 33
11 x 4 = 44
11 x 5 = 55
11 x 6 = 66
11 x 7 = 77
11 x 8 = 88
11 x 9 = 99
11 x 10 = 110
# while loop with else11
x = 1
while x < 3:
print(x)
x += 1
else:
print('limit crossed')
Result:1
2
limit crossed
# guessing game
# generate a random integer between 1 and 100
import random
jackpot = random.randint(1, 100)
guess = int(input('Guess the number: '))
counter = 1
while guess != jackpot:
if guess < jackpot:
print('Incorrect! Guess higher.')
else:
print('Incorrect! Guess lower.')
guess = int(input('Guess again: '))
counter += 1
print('Correct guess!')
print('Attempts:', counter)
Result: Guess the number: 60
Incorrect! Guess lower.
Guess again: 50
Incorrect! Guess lower.
Guess again: 40
Incorrect! Guess lower.
Guess again: 30
Incorrect! Guess higher.
Guess again: 33
Incorrect! Guess higher.
Guess again: 32
Incorrect! Guess higher.
Guess again: 35
Incorrect! Guess lower.
Guess again: 34
Correct guess!
Attempts: 8
Comments
Post a Comment