I'm new to programming in general (Python is the first language I've tried learning) and I'm working my way through a collection of beginner's challenges. I'm having a little trouble wrapping my head around functions, positional arguments, and the way they interact with user input. I wrote this program to test my understanding. Is there any way it could be made more efficient?
This program does the following things:
- It generates a random 3 digit number.
- It tells the user how to play the game.
- It asks the user to guess the number.
- If the number is too low, it returns 'Higher' and if the number is too high it returns 'Lower'. Finally, if the user guesses the number correctly, it congratulates the user.
- Once the correct number has been guessed, it asks the user if he/she wants to play again.
- If the user says yes, the program generates a new random 3 digit number and the game starts again. If the user chooses no, it says goodbye and quits.
Here's the code:
import random
def instructions():
"""Tells user how to operate program."""
i = """
I have selected a random 3 digit number. Your goal is to guess my
number in the smallest amount of of moves. I will tell you if your
guess is too high or too low, but that's all the help you'll get
from me.
"""
print(i)
def guess():
g = int(input("Guess the number: "))
return g
def hint(x):
if x > ans:
print("Lower")
elif x < ans:
print("Higher")
else:
print(victory(x))
def victory(x):
if x == ans:
print("Congratulations! You got it!")
instructions()
ans = random.randint(100,999)
while True:
x = guess()
if x != ans:
hint(x)
elif x == ans:
victory(x)
replay = input("Would you like to play again? y/n: ").strip().lower()
if replay == "y":
ans = random.randint(100,999)
continue
else:
print("Okay then. Bye-bye.")
break
Again, just to clarify, I've tested the program and it does work, I'm just looking to see if there's a more efficient way of writing it which doesn't sacrifice any of its current functions. Thanks.