Create an interactive Number Guessing Game where the computer generates a random number, and the user tries to guess it. The program will provide feedback on whether the user’s guess is too high, too low, or correct.
For example:
42
.50
→ Output: “Too high!”30
→ Output: “Too low!”42
→ Output: “Correct! You guessed it!”This challenge reinforces concepts such as:
Building this game is also a great introduction to interactive programming and can easily be extended with additional features to make it more dynamic.
import random
print("Welcome to the Number Guessing Game!")
print("I have selected a number between 1 and 100. Can you guess what it is?")
# Generate a random number
target_number = random.randint(1, 100)
attempts = 0
while True:
try:
# Get the user's guess
guess = input("Enter your guess (or type 'exit' to quit): ")
if guess.lower() == "exit":
print("Thanks for playing! Goodbye!")
break
guess = int(guess)
attempts += 1
# Check the guess
if guess < target_number:
print("Too low!")
elif guess > target_number:
print("Too high!")
else:
print(f"Correct! You guessed the number in {attempts} attempts!")
break
except ValueError:
print("Please enter a valid number.")
import java.util.Scanner;
import java.util.Random;
public class NumberGuessingGame {
public static void main(String[] args) {
Random random = new Random();
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Number Guessing Game!");
System.out.println("I have selected a number between 1 and 100. Can you guess what it is?");
// Generate a random number
int targetNumber = random.nextInt(100) + 1;
int attempts = 0;
while (true) {
System.out.print("Enter your guess (or type -1 to quit): ");
int guess = scanner.nextInt();
if (guess == -1) {
System.out.println("Thanks for playing! Goodbye!");
break;
}
attempts++;
// Check the guess
if (guess < targetNumber) {
System.out.println("Too low!");
} else if (guess > targetNumber) {
System.out.println("Too high!");
} else {
System.out.println("Correct! You guessed the number in " + attempts + " attempts!");
break;
}
}
}
}
console.log("Welcome to the Number Guessing Game!");
console.log("I have selected a number between 1 and 100. Can you guess what it is?");
// Generate a random number
const targetNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
while (true) {
const input = prompt("Enter your guess (or type 'exit' to quit):");
if (input.toLowerCase() === "exit") {
console.log("Thanks for playing! Goodbye!");
break;
}
const guess = parseInt(input);
if (isNaN(guess)) {
console.log("Please enter a valid number.");
continue;
}
attempts++;
// Check the guess
if (guess < targetNumber) {
console.log("Too low!");
} else if (guess > targetNumber) {
console.log("Too high!");
} else {
console.log(`Correct! You guessed the number in ${attempts} attempts!`);
break;
}
}
In Day 26: Password Generator, you’ll create a program that generates random, secure passwords based on user-defined criteria.