codingstreets
Search
Close this search box.

Python while loop Beginner Project

Python-while-loop-Beginner-Project
Credit: Canva

Overview

Python while loop beginner project is designed to solve a couple of Python while loop projects. In this project, you will learn to explore the concept as well as challenge the problems. While loop in Python is used to repeat a condition over and over.

What’s Next!

In this comprehensive Python while loop beginner project, we will go through various common examples to understand how Python while loop can be used in real-life practical questions.

Table of Contents

Project 1: Number Guessing Game

Create a number-guessing game where the computer picks a random number between 1 and 100, and the user has to guess the number. The program should provide feedback to the user (too high, too low, or correct) and keep track of the number of guesses using a while loop.

				
					import random
n = 3
while n  > 0:
    n = n-1
    random_number = random.randint(1,101)
    user_number = int(input("Enter a number: "))

    print("Computer's number:",random_number)
    print('User_number:',user_number)

    if  user_number == random_number:
        print("Congratulations! You guessed the correct number.")
        print() #for one line space
        
    elif user_number > random_number:
        print("Your number is too high. Try again.")
        print()
        
    else:
        print("Your number is too low. Try again.")
        print()
				
			

Explanation: The program starts with asking a number from the user using the input() function. Next, according to the module random and from randint() function, the computer generates a random number between 1 to 100.

Next, as per the Python if-else statements, the user’s number is compared with the computer’s number, and according to the condition is matched, the Python interpreter displays the statement.

Now, since the steps are repeated over time, the while loop counts the number of times the user has guessed the number. The limit for guessing a number is 3. Every time the user asks the number will decrease the guessing chance by 1 and when n = 0, the loop breaks and the Python interpreter stops.

Let’s take another example:

				
					import random
while True:
    random_number = random.randint(1,101)
    user_number = int(input("Enter a number: "))

    print("Computer's number:",random_number)
    print("User's number:",user_number)

    if  user_number == random_number:
        print("Congratulations! You guessed the correct number.")
        print()
        break

    elif user_number > random_number:
        print("Your number is too high. Try again.")
        print()
        break
        
    else:
        print("Your number is too low. Try again.")
        print()
        break
				
			

Explanation: In this example, while loop is always True, therefore; the program will stop by using the ‘break’ keyword when any of the conditions will match.

Project 2: Password Generator

Write a program that generates a random password for the user. The program should ask the user for the length of the password and generate a password of that length using a while loop.

				
					import random
import string
ask_password_length = int(input("Enter a number from 6 to 10: "))

random_character = string.ascii_letters+string.digits+string.punctuation
random_password = "".join(random.choice(random_character) for i in range(ask_password_length))
    
while (ask_password_length) >=6 and ask_password_length <=10:
    print("Here is your password:", random_password)
    break
else:
    print("Password length exceeds.")
				
			

Explanation: First we import some necessary modules i.e., random and string to choose password characters randomly and generate random passwords in string. The program starts by asking for the password length from the user. Next, using the string module, a random string is generated, and using the random module with function choice, random characters of the password are chosen. The for loop is defined to limit the number of characters in the password i.e., equal to the password length.

Now, while loop is used to check the password length and if the condition is matched the print() function displays the result, otherwise, else statement will be executed.

Let’s take another example:

				
					import random
import string
ask_password_length = int(input("Enter a number from 6 to 10: "))

random_character = string.ascii_letters+string.digits+string.punctuation
random_password = "".join(random.choice(random_character) for i in range(ask_password_length))

if (ask_password_length) <6:
    print("Password length is short.")
    
elif (ask_password_length) >=6 and ask_password_length <=10:
    print("Here is your password:", random_password)
else:
    print("Password length exceeds.")
				
			

Explanation: In this example case is the same except for the while loop. Now, a Python conditional statement is used to check the length of the password. In this case, if the password length is between 6 to 10 characters, then the password is displayed.

Project 3: Factorial Calculator

Develop a program that calculates the factorial of a given number. The program should ask the user to input a number and then calculate and print the factorial of that number using a while loop.

				
					number = int(input("Enter a number, you want factorial of: "))
Factorial = 1
while number < 0 :
    print("No Factorial of negative number.")
    break
else:
    for  i in range(1,number+1):
        Factorial = Factorial*i
    print(Factorial)
				
			

Explanation: The program starts with asking the number of factorials. By using the while loop the condition is checked if number < 0, then, we have no factorial for negative numbers.

Otherwise, a for loop is used to access each number from 1 to number (a number defined by the user to generate the factorial of a particular number).

In each iteration, the Factorial is multiplied by i and is updated. When the for loop finishes iterating all numbers within the range() function, then the Python interpreter displays the Factorial of the number defined by the user.

Let’s take another example:

				
					number = int(input("Which number of Factorial, you want: "))

if number == 0:
    print("Factorial of",number, "is zero")
elif number < 0:
    print("Sorry! Factorial is not defined for negative numbers.")
else:
    factorial = 1
    i=1
    while i <= number :
        factorial = factorial * i
        i += 1
    print("The factorial of",number,"is",factorial)
				
			

Explanation: The program starts with asking the number for a Factorial. Then the Python conditional statement is used to define the factorial. In this case, if the number is equal to 0, then no factorial, also if the number is less than 0, then no factorial for negative numbers. But if the number is a positive integer, then while loop checks that till then i <= number, it will multiply factorial by i and update the value of factorial.

In this process in each iteration, the i value is incremented by 1, and finally, when the i > number, the while loop is broken and the Python interpreter displays the factorial. For example, if the user enters a number = 5, then the program finds the factorial as follows: 1*2*3*4*5 = 120.

Let’s take another example:

				
					number = int(input("enter a number: "))

if number == 0:
    print("Factorial of",number, "is zero")
elif number < 0:
    print("Sorry! Factorial is not defined for negative numbers.")
else:
    fact = 1
    while  number > 0 :
        fact = fact*number
        number -= 1
    print(fact)
				
			

Explanation: Everything is the same as the previous example except the one thing that is while loop, till then number > 0, factorial is multiplied by the number, and in each iteration the value of the number will be decremented by 1.

Hence, when the while loop condition goes false i.e., when number == 0, the Python interpreter displays the factorial. For example, if the user enters number = 5, then the program finds the factorial as follows: 5*4*3*2*1 = 120.

Project 4: Multiplication Table

Create a program that generates a multiplication table for a given number. The program should ask the user to input a number and then print the multiplication table for that number using a while loop.

				
					Number = int(input("Which number, you want table of: "))

n = 1
while n<=10:
    print(Number,"*",n,"=",Number*n)
    n = n+1        
print("Loop is over.")
				
			

Explanation: The program starts with a number to generate the table. Then while loop is used to check the condition till n<=10, in each iteration print() statement will be performed (i.e. Number*n until n > 10)  and the n value is incremented by 1.

When the condition goes false i.e., n > 10, then loop is broken and the Python interpreter displays the statement “Loop is over.”.

Project 5: Simple Calculator

Write a simple calculator program that performs basic arithmetic operations (addition, subtraction, multiplication, division) on two numbers. The program should ask the user to input the operation and the two numbers, and then perform the calculation using a while loop.

				
					while True:
    num1 = int(input("Enter the first number: "))
    num2 = int(input("Enter the second number: "))

    operator = input("Choose any one operator: + , - , * , / : ")

    addition = num1+num2
    subtraction = num1-num2
    multiplication = num1*num2
    division = num1/num2

    if operator ==  '+' :
        print(num1,'+',num2,"=",addition)
        break
    elif  operator == '-' :
        print(num1,'-',num2,"=",subtraction)
        break
    elif  operator == '*' :
        print(num1,'*',num2,"=",multiplication)
        break
    else:
        print(num1,'/',num2,"=",division)
        break
				
			

Explanation: The program starts with asking two numbers, from the user and selecting any one operator to perform the calculation. Next, arithmetic operations (addition, subtraction, multiplication, division) are defined.

Now, the Python conditional statement is used to perform the calculation based on the operator chosen by the user. Since the whole code is inside the while loop, therefore; once any of the conditions are matched and displayed, the command is stopped using the ‘break’ keyword. If we don’t use the ‘break’ keyword, then the while loop will never be broken and the Python interpreter will always continue to perform the calculation.

Recent Articles