Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #607: Input validation in Number Guessing App #608

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/Python-Projects.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

109 changes: 76 additions & 33 deletions projects/Number Guessing App/main.py
Original file line number Diff line number Diff line change
@@ -1,44 +1,66 @@
# Importing the 'random' module to generate random numbers
import random


# Function to play a guessing game where the user tries to guess the number chosen by the computer
# Function for the user to guess the number generated by the computer
def guess():
'''
This function generates a random number between 1 and 20 (inclusive)
and allows the user to guess the number. It continues to prompt
the user for input until the correct number is guessed.

Returns:
None
'''
# Generate a random number between 1 and 20 (inclusive)
n = random.randrange(1, 20)

# Request user input to guess the number
varGuess = int(input("Enter any number: "))

# Continue the loop until the user guesses the correct number
while n != varGuess:
if varGuess < n: # If the user's guess is too low
print("OOPS! Too low")
varGuess = int(input("Guess again: ")) # Ask for another guess
elif varGuess > n: # If the user's guess is too high
print("OOPS! Too high!")
varGuess = int(input("Guess again: ")) # Ask for another guess
else:
break # Exit the loop when the correct number is guessed
# This loop continues until the user guesses the correct number.
while True:
user_input = input("Enter your number: ")
try:
varGuess = int(user_input)
if n == varGuess:
print(f"Congratulations!! You guessed the number {n} correctly")
break
elif varGuess < n:
print("OOPS! Guess something higher!")
elif varGuess > n:
print("OOPS! Guess something lower!")
except ValueError:
# Handle invalid input (not an integer)
print("Invalid input. Please enter a valid integer.")


# Display a congratulatory message when the user guesses the correct number
print(f"Congratulations!! You guessed the number {n} correctly")


# Function for the computer to guess the number chosen by the user
def computer_guess():
'''
Play the guessing game where the computer tries to guess the user's number.

This function prompts the user to enter a number, and then the computer will make guesses
and adjust the guessing range based on the user's feedback until it correctly guesses the number.

Returns:
None
'''
global CompGuess
# Variable to store the user's feedback on the computer's guesses
CompAns = ""

# Request user input to get the number to be guessed by the computer
x = int(input("Enter your number: "))
# Get the number to be guessed by the computer, validating the input
while True:
try:
# Request user input to get the number to be guessed by the computer
x = int(input("Enter your number: "))
break
except ValueError:
print("Invalid input. Please enter a valid integer.")

# Initialize the lower and upper bounds for the computer's guessing range
low = 1
high = x

# Variable to store the user's feedback on the computer's guesses
CompAns = ""

# Continue the loop until the computer guesses the correct number
while CompAns != "c":
if low != high:
Expand All @@ -53,6 +75,13 @@ def computer_guess():
CompAns = input(
f"Is {CompGuess} too high (h), too low (l), or correct (c)? \n=>"
).lower()
# Ask the user if the computer's guess is too high, too low, or correct
while CompAns not in ["h", "l", "c"]:
CompAns = input(
f"Is {CompGuess} too high (h), too low (l), or correct (c)? \n=>"
).lower()
if CompAns not in ["h", "l", "c"]:
print("Invalid input. Please enter 'h', 'l', or 'c'.")

# Adjust the guessing range based on the user's feedback
if CompAns == "h": # If the computer's guess is too high
Expand All @@ -63,16 +92,30 @@ def computer_guess():
# Display a message when the computer guesses the correct number
print(f"Yay! The computer guessed your number, {CompGuess}, correctly!")

def main():
"""
Main function to initiate the number guessing game.

This function allows the user to select the gaming mode and start either the number guessing
game or the computer guessing game based on the user's choice.

Returns:
None
"""
while True:
# Display options to select the gaming mode
Gmode = int(input("Select gaming mode\nPress 1 to guess the number\nPress 2 to choose the number\n"))

if Gmode == 1:
guess()
break
elif Gmode == 2:
computer_guess()
break
else:
print("Invalid choice. Please enter 1 or 2.")



if __name__ == "__main__":
# Display options to select the gaming mode
print(
"Select gaming mode\n Press 1 to guess the number\nPress 2 to choose the number"
)
Gmode = int(input())

# Call the appropriate function based on the selected gaming mode
if Gmode == 1:
guess()
if Gmode == 2:
computer_guess()
main()