Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- def main():
- heading()
- rand_num = number()
- take_guess(rand_num)
- # This function shows the greetings
- def heading():
- print("Welcome to the my guessing game!\n")
- # This function generates the random number and displays it
- def number():
- number = random.randint(1, 100)
- print("(The answer is ", number, ")", sep="")
- return number
- # This function performs the logic required to keep track of the
- # guesses in addition to calling other functions that perform
- # checks for the boundaries
- def take_guess(rand_num):
- start = 1
- end = 100
- counter = 0
- guess = 0
- flag = True
- while flag:
- # TODO:
- # When an error is triggered, display only the exception
- # error prompt according to the requirement
- try:
- guess = int(input("Please guess a number between "
- + str(start) + " and " + str(end) + ": "))
- except ValueError:
- print("Your guess must be a number.\n")
- # This function call checks if the user is outside the
- # boundaries and keeps track of guesses
- # if within boundaries
- proceed = boundary_check(guess, start, end, counter)
- if proceed != -1:
- counter += 1
- # This function call takes in the start and end
- # boundaries, the guess, the random number, guess
- # counter, and continues if proceed isn't -1
- # here you set new_bound but never passed end so that it can be changed
- new_bound, new_end = high_low(start, end, guess, rand_num, proceed, counter)
- start = new_bound
- end = new_end
- if start == -1:
- flag = False
- # This function checks the boundaries and returns the proceed
- # code in which case -1 means "don't proceed".
- def boundary_check(guess, start, end, counter):
- if guess < start or guess > end:
- print("Your guess must be between " + str(start) +
- " and " + str(end), "\n")
- return -1
- else:
- counter += 1
- return counter
- # This function calculates if the guess is high or low and
- # resets the boundary based on the calculation
- # added end so that it can also be changed.
- def high_low(start, end, guess, rand_num, proceed, counter):
- if proceed != -1:
- if guess < rand_num:
- print("Too low!\n")
- start = guess
- elif guess == rand_num:
- print("You guessed it!")
- print("It only took you", counter, "guess(es)!\n")
- start = -1
- play_again()
- elif guess > rand_num:
- end = guess
- print("Too high!\n")
- return start, end
- # This function ensures the user types the requested string to
- # play again or quit
- def play_again():
- flag = True
- while flag:
- again = input(str("Play again? (Y/N): "))
- if again == "Y" or again == "y":
- flag = False
- main()
- elif again == "N" or again == "n":
- flag = False
- else:
- print("The only valid choices are (Y/N)\n")
- # TODO:
- # Thank the user for playing
- # display the user's best round
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement