Exp5
Exp5
Objective of Experiment: The aim of this experiment is to understand the concepts of While Loops in python.
Pre-Requisite:
Tools: Any IDLE, Juypter Notebook / google colab/pycharm/VScode etc
Theory:
The while Loop
With the while loop we can execute a set of statements as long as a condition is true.
i=1
while i < 6:
print(i)
i += 1
The while loop requires relevant variables to be ready, we need to define an indexing variable, i, which we set to
1.
The break Statement
With the break statement we can stop the loop even if the while condition is true:
Example
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration, and continue with the next:
Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
print('Value of i :', i)
i=0
while i < 4:
i += 1
print(i)
else: # Executed because no break in for
print("No Break\n")
i=0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print("No Break")
while a != -1:
a = int(input('Enter a number (-1 to quit): '))
Python while loop with Python list
In this example, we have run a while loop over a list that will run until there is an element present in the list.
a = [1, 2, 3, 4]
while a:
print(a.pop())
*Write a program that takes a string input from the user and prints it in reverse order using a while loop.
s=input("enter a string")
print(s)
print(s[::-1])
* Create a program that takes a positive integer from the user and counts the number of digits in that
integer using a while loop.
y=int(input("enter a number"))
count=0
while y>0:
digit=y%10
count+=1
y=y//10
print(count)
* Write a program that asks the user for a sentence and counts the number of vowels and consonants
using a while loop
str="count the number of vowels and consonants"
vowel=0
conso=0
i=0
while i<len(str):
char=str[i]
if char in 'aeiou':
vowel+=1
else:
conso+=1
print(vowel)
print(conso)
* Write a program that sums all even numbers from 1 to a user-defined number using a while loop.
sum=0
n=int(input("enter the value of n"))
i=1
while i<=n:
if i%2==0:
sum=sum+i
i=i+1
print(sum)
* Implement a program that repeatedly asks the user to enter a temperature in Celsius and converts it to
Fahrenheit until the user decides to stop.
celsius=int(input("enter the temp in celsius"))
while True:
F = celsius * (9/5) + 32
print(F)
celsius=int(input("enter the temp in celsius"))
if celsius==-1:
break
Problem Description:
Number Guessing Game with Feedback
Develop a Python program that uses a while loop to create an interactive number-guessing game. The
program should generate or contain a predefined secret number, which the user must guess correctly.
The program should:
1. Provide meaningful feedback to the user after each guess:
o Indicate whether the guess is too high, too low, or correct.
2. Continuously prompt the user for input until the correct number is guessed.
3. Display a congratulatory message upon guessing the correct number and exit the loop.
Challenge (Optional):
Guess the Word Game
Develop a Python application that engages the user in a word-guessing game using a while loop. The game
should help the user understand and apply logic through repeated attempts and feedback.
The program should:
1. Contain a predefined secret word that the user must guess.
2. Prompt the user to input their guesses continuously until the correct word is guessed.
3. Provide feedback after each attempt:
o Indicate if the guess is correct or incorrect.
o Optionally, give hints (e.g., the length of the word or matching letters).
4. Display a congratulatory message when the user guesses the word correctly and exit the loop.
Input: 10, 50, 75, 90 & 95 Output:Welcome to the Number Libraries: random
Guessing Game!
I have selected a number
between 1 and 100. Can you
guess it?
Enter your guess: 10
Your guess is too low. Try again!
Enter your guess: 50
Your guess is too low. Try again!
Enter your guess: 75
Your guess is too low. Try again!
Enter your guess: 90
Your guess is too low. Try again!
Enter your guess: 95
Congratulations! You've guessed
the correct number!
Program:import random
def number_guessing_game():
# Generate a random secret number between 1 and 100
secret_number = random.randint(1, 100)
print("Welcome to the Number Guessing Game!")
print("I have selected a number between 1 and 100. Can you guess
it?")
# Initialize the user's guess
guess = None
Output:
Practice Programs:
1. Write a program that uses a while loop to print the numbers from 1 to 10.
2. Write a program that prompts the user for numbers and adds them to a running total
until the user enters 0. Print the total sum when the loop ends.
3. Write a program that calculates the factorial of a given number using a while loop. The
user should input the number.
4. Write a program that prints the Fibonacci sequence up to a certain number entered by
the user. Use a while loop to generate the sequence.
5. Create a program that repeatedly prompts the user for a password until they enter the
correct one. For this exercise, assume the correct password is "secret"
6. Write a program that counts down from a specified number to zero, printing each
number. The countdown should stop when it reaches zero.
7. Create a guessing game where the program randomly selects a number between 1 and
100, and the user has to guess it. The program should provide hints (too high or too low)
and continue until the user guesses correctly.
8. Write a program that asks the user for a number and prints the multiplication table for
that number (from 1 to 10) using a while loop.
9. Create a program that takes a string input from the user and removes all vowels from it.
Use a while loop to iterate through the string.
10. Write a program that continuously asks the user if they want to continue. If the user
types "yes," the loop continues; if they type "no," the loop ends.
2. Write a program that prompts the user for numbers and adds them to a running total until the
user enters 0. Print the total sum when the loop ends.
3. Write a program that calculates the factorial of a given number using a while loop. The user
should input the number.
4. Write a program that prints the Fibonacci sequence up to a certain number entered by the user.
Use a while loop to generate the sequence.
5. Create a program that repeatedly prompts the user for a password until they enter the correct
one. For this exercise, assume the correct password is "secret"
Correctness & Logic & Problem Use of Python Timeline Total
Functionality Solving Approach Features (1 Marks) (10)
(3 Marks) with creativity (3 Marks)
(3 Marks)
References:
Study Materials Online repositories:
1. Yashvant Kanetkar, “Let us Python: Python is 1. Python 3 Documentation: https://docs.python.org/3/
Future, Embrace it fast”, BPB Publications;1 3. "The Python Tutorial",
st edition (8 July 2019). http://docs.python.org/release/3.0.1/tutorial/
2. Dusty Phillips, “Python 3 object-oriented 4. http://spoken-tutorial.org
Programming”, Second Edition PACKT 5. Python 3 Tkinter library Documentation:
Publisher, August 2015. https://docs.python.org/3/library/tk.html
3. John Grayson, “Python and Tkinter 6. Numpy Documentation: https://numpy.org/doc/
Programming”, Manning Publications (1 March 7. Pandas Documentation: https://pandas.pydata.org/docs/
1999). 8. Matplotlib Documentation:
4. Core Python Programming, Dr. R. Nageswara https://matplotlib.org/3.2.1/contents.html
Rao, Dreamtech Press 9. Scipy Documentation :
5. Beginning Python: Using Python 2.6 and Python https://www.scipy.org/docs.html
3.1. James Payne, Wrox publication 10. Machine Learning Algorithm Documentation:
6. Introduction to computing and problem solving https://scikit-learn.org/stable/
using python, E Balagurusamy, 11. https://nptel.ac.in/courses/106/106/106106182/
McGrawHill Education 12. NPTEL course: “The Joy of Computing using Python”
13. https://www.w3resource.com/python-exercises/list/
14. https://www.geeksforgeeks.org/python-dictionary-
methods/
15.
https://www.shiksha.com/online-courses/articles/for-
loop-in-python-examples/
Video Channels:
https://www.youtube.com/watch?v=t2_Q2BRzeEE&list=PLGjplNEQ1it8-0CmoljS5yeV-GlKSUEt0
https://www.youtube.com/watch?v=7wnove7K-ZQ&list=PLu0W_9lII9agwh1XjRt242xIpHhPT2llg
Data Visualization:
https://www.youtube.com/watch?v=_YWwU-gJI5U