How to tell which part of code should be inside a function? - python

I'm having a problem understanding which part of my code belongs to a funtions and which does not. My code is messy and I know I need to use functions to clean it up.
The code below is a console game whereby a computer generates a random integer between 1 and 100 and the user user guesses that number with a limited number of guesses.eg. 5 for hard. 10 for easy.
How can I use funtions in this code?
#TODO 1: Generate a random number between 1 and 100
import random
GUESS = random.randint(1, 100)
#TODO 2: Print the guess(,for debugging)
#TODO 3: Choose the difficulty("easy" or "hard")
difficulty = input("Choose a difficulty. Type 'easy' or 'hard': ")
#TODO 4: Loop 5 times if the user typed 'hard' or 10 times if the user typed 'easy'
if difficulty == "hard":
try:
#TODO 4.1: User inputs the guesses the random number
print("You have 5 attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
#TODO 4.2: Compare the guess and the random number
if guess == GUESS:
print(f"{guess} is the correct guess")
elif guess > GUESS:
print(f"{guess} is too high")
#Count dowm
for _ in range(5, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
elif guess < GUESS:
print(f"{guess} is too low")
#Count dowm
for _ in range(5, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
except ValueError:
print("Please input a number")
elif difficulty == "easy":
#TODO 4.1: User inputs the guesses the random number
try:
print("You have 10 attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
#TODO 4.2: Compare the guess and the random number
if guess == GUESS:
print(f"{guess} is the correct guess")
elif guess > GUESS:
print(f"{guess} is too high")
#Count dowm
for _ in range(10, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
elif guess < GUESS:
print(f"{guess} is too low")
#Count dowm
for _ in range(10, 1, -1):
print(f"You have {_-1} attempts remaining to guess the number.")
guess = int(input("Make a guess: "))
if guess == GUESS:
print(f"{guess} is the correct guess")
break
elif guess > GUESS:
print(f"{guess} is too high")
elif guess < GUESS:
print(f"{guess} is too low")
#I probably have to use exceptions
#So im going to do a google search real quick
#value errors
except ValueError:
print("Please input a number")

In pseudo code, here's an example of one function that might be useful:
function CheckGuess (INTEGER guess, INTEGER answer) returns an STRING
if guess > answer
return "too high"
if guess < answer
return "too low"
else
return "exactly"
Now, keeping in mind that a function accepts 0 or more inputs and always returns single output, and that output should always be the same, given the same input, lets see how this can be used as a functional object.
if CheckGuess(7, 10) != "exactly"
guesses = guesses - 1;
This is only one way of dozens that could be useful. Hope this helps!

this could work, though i might have missed some functionality.:
def prompt(prompt):
prompt(input)
def guessing_game:
num_to_guess = random.randint(1,100)
while number_of_guesses > 0:
os.system("cls")
guessed_number = prompt("guess between 1 and 100")
if gessed_number == num_to_guess:
os.system("cls")
number_of_guesses = 0
print("you got it!")
else:
if number_guessed < num_to_guess:
os.system("cls")
print("to low...")
number_of_guesses =- 1
else:
os.system("cls")
print("too high...")
number_of_guesses =- 1
if number_of_guesses == 0:
print("you lost...")
quit()
if this dosent work, check for typos.

Related

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

On the First guess nothing is being registered even if i get it right

This is the code:
print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")
while not out_of_guesses:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print("You have", str(guess_limit - guess_counter), "tries left")
# exit clause
if guess_limit == guess_counter:
out_of_guesses = True
print("Game over, sorry")
And even if I get it correct on the first try it does something like this:
Welcome to my guessing game can you get the magic number
hint,
it's between 1 and 100
47
Enter your guess: 47
You have 4 tries left
Enter guess: 47
Well done you got it!!
As you can see even though i was correct on the first try it wasn't counted. Ps.(That is what shows up at the bottom of my screen where the code is executed.)
You do not check if guess == Magic_number after reading input on line 4.
Like this
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess = int(input("Enter your guess:"))
if guess == Magic_number:
print ("You won")
exit(0)
You don't need all those variables, check this.
import random
Magic_number = random.randrange(1, 100)
print(Magic_number)
guess_limit = 5
guess_counter = 0
while True:
guess = int(input("Enter guess: "))
if guess == Magic_number:
print("Well done you got it!!")
exit(0)
elif guess < Magic_number:
print("That number is too small, try again")
elif guess > Magic_number:
print("That number is too high try again")
guess_counter += 1
print(f"You have {guess_limit - guess_counter} tries left")
if guess_counter == guess_limit:
print("Game over, sorry")
exit(0)

Why is the return for number to high or to low is incorrect in my guessing game

When my game returns the the computers answer for whether its number is too high or too low it will say that the number is to high but the actual number is higher. For example, it will say computer guessed 7 which is too high and the number is 10.
The user input for option to is randomly changing numbers as well. So this could be linked to the previously stated issue.
"""
Displays the main menu then reads in the user choice.
Depending on user choice program may have user guess a number
generated by the computer, computer guesses a number given by user,
or user exits program.
"""
def main():
display_menu()
option = int(input("Enter a menu option: "))
if option == 1:
import random
number = random.randint(1,10)
counter = 0
while True:
try:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
print()
if guess < 1 or guess > 10:
raise ValueError()
counter += 1
if guess > number:
print("Too high.")
print()
elif guess < number:
print("Too low.")
print()
else:
print("You guessed it!")
print("You guessed the number in", counter, "attempts!")
break
except ValueError:
print(guess, "is not a valid guess")
print()
"""
Option 2., User enters a number for the computer to guess.
Computer guesses a number within the range given.
Outputs computer guesses and number of guesses until computer gets
the correct number.
"""
if option == 2:
import random
print("Computer guess my number")
print()
while True:
try:
my_num = input("Enter a number betrween 1 and 10 for the computer to guess: ")
my_num = int(my_num)
print()
counter = 1
comp = random.randint(1,10)
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
comp = random.randint(1,10)
elif comp < my_num:
print("Computer guessed", comp,"to Low")
comp = random.randint(1,10)
print("Computer the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
except ValueError:
print(my_num, "is not a valid guess")
print()
if option == 3:
print("Goodbye")
"""
Defines menue and user choices.
"""
def display_menu():
print("Welcome to my Guesss the Number Program!")
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it.")
print("3. Exit")
print()
if __name__ == '__main__':
main()
The user input for option to is randomly changing.
if comp > my_num:
print("Computer guessed", comp,"to High")
comp = random.randint(1,10)
because of the third line generating a new random number.
while True:
try:
the loop exited because the "try" block succeed,not because the guess was right.
counter = 1
the counter should be instanced then incremented, otherwise it will remain at zero.
Working example after few changes :
"""
Displays the main menu then reads in the user choice.
Depending on user choice program may have user guess a number
generated by the computer, computer guesses a number given by user,
or user exits program.
"""
import sys
import random
def main():
display_menu()
option = int(input("Enter a menu option: "))
if option == 1:
number = random.randint(1,10)
counter = 0
while True:
try:
guess = input("Guess a number between 1 and 10: ")
guess = int(guess)
print()
if guess < 1 or guess > 10:
raise ValueError()
counter += 1
if guess > number:
print("Too high.")
print()
elif guess < number:
print("Too low.")
print()
else:
print("You guessed it!")
print("You guessed the number in", counter, "attempts!")
break
except ValueError:
print(guess, "is not a valid guess")
print()
"""
Option 2., User enters a number for the computer to guess.
Computer guesses a number within the range given.
Outputs computer guesses and number of guesses until computer gets
the correct number.
"""
if option == 2:
print("Computer guess my number")
print()
my_num = input("Enter a number betrween 1 and 10 for the computer to guess: \n")
my_num = int(my_num)
comp = 0
counter = 0
while comp != my_num:
counter += 1
comp = random.randint(1,10)
if my_num < 1 or my_num > 10:
print(my_num, "is not a valid guess")
sys.exit(0)
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low ")
print("Computer the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
if option == 3:
print("Goodbye")
"""
Defines menue and user choices.
"""
def display_menu():
print("Welcome to my Guesss the Number Program!")
print("1. You guess the number")
print("2. You type a number and see if the computer can guess it.")
print("3. Exit")
print()
if __name__ == '__main__':
main()
The code block
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
comp = random.randint(1,10)
elif comp < my_num:
print("Computer guessed", comp,"to Low")
comp = random.randint(1,10)
print("Computer the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
seems to be the cause of your issue (although it's not exactly what you describe). No matter what happens, it will always say the computer got the correct number. You should add an else like such:
if my_num < 1 or my_num > 10:
raise ValueError()
if comp > my_num:
print("Computer guessed", comp,"to High")
comp = random.randint(1,10)
elif comp < my_num:
print("Computer guessed", comp,"to Low")
comp = random.randint(1,10)
else:
print("Computer the right number!" , comp)
print("Computer guessed the right number in", counter, "attempts!")
break
Furthermore, the start of the block of code also needs some fixing. The code will ask you to fill in a new number for every cycle and the counter needs to be updated every cycle. If you implement this, the start of the code ends up looking something like this:
if option == 2:
import random
print("Computer guess my number")
print()
my_num = input("Enter a number betrween 1 and 10 for the computer to guess: ")
my_num = int(my_num)
counter = 1
while True:
try:
counter += 1
print()
comp = random.randint(1,10)
This also means this:
if comp > my_num:
print("Computer guessed", comp,"to High")
comp = random.randint(1,10)
elif comp < my_num:
print("Computer guessed", comp,"to Low")
comp = random.randint(1,10)
Can be changed to:
if comp > my_num:
print("Computer guessed", comp,"to High")
elif comp < my_num:
print("Computer guessed", comp,"to Low")
Because the computer will make a new guess anyway.
FYI I recommend doing all your imports at the top of your file, not halfway through the code.
Also, it's 'too high/low' not 'to high/low' ;)

Is there a way to limit the amount of while loops or input loops?

I was just wondering if there is a way to limit the amount of times a user can input something on a while loop. This is simply a guess a number 1-100 game. I have the found variable = False.
while not found:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")
I wanted to see if i could make this code seem more like a game by limiting the amount a user can guess for the input. Ive had some ideas i just cannot wrap my head around it. do i have set a variable value for the input to set the amount of times it can run? Im new to programming so i am struggling a bit.
count = 0
max_guesses_allowed = pick your max here
while not found or count < max_guesses_allowed:
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif user_guess > random_number:
count += 1
print("Guess lower")
else:
count += 1
print("guess higher")
The standard way would be to count the number of loops, and then exit if they exceed the maximum.
max_allowed = 10
attempt = 0
while not found:
attempt += 1
user_guess = int(input("Your guess: "))
if user_guess == random_number:
print("you got it!")
found = True
elif attempt == max_allowed:
print("You've reached the maximum number of guesses.")
break
elif user_guess > random_number:
print("Guess lower")
else:
print("guess higher")

Asking the user if they want to play again [duplicate]

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 4 years ago.
Basically it's a guessing game and I have literally all the code except for the last part where it asks if the user wants to play again. how do I code that, I use a while loop correct?
heres my code:
import random
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
while guess == number:
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == yes:
guess= eval(input("Enter your guess between 1 and 1000 "))
if again == no:
break
One big while loop around the whole program
import random
play = True
while play:
number=random.randint(1,1000)
count=1
guess= eval(input("Enter your guess between 1 and 1000 "))
while guess !=number:
count+=1
if guess > number + 10:
print("Too high!")
elif guess < number - 10:
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = eval(input("Try again "))
print("You rock! You guessed the number in" , count , "tries!")
count=1
again=str(input("Do you want to play again, type yes or no "))
if again == "no":
play = False
separate your logic into functions
def get_integer_input(prompt="Guess A Number:"):
while True:
try: return int(input(prompt))
except ValueError:
print("Invalid Input... Try again")
for example to get your integer input and for your main game
import itertools
def GuessUntilCorrect(correct_value):
for i in itertools.count(1):
guess = get_integer_input()
if guess == correct_value: return i
getting_close = abs(guess-correct_value)<10
if guess < correct_value:
print ("Too Low" if not getting_close else "A Little Too Low... but getting close")
else:
print ("Too High" if not getting_close else "A little too high... but getting close")
then you can play like
tries = GuessUntilCorrect(27)
print("It Took %d Tries For the right answer!"%tries)
you can put it in a loop to run forever
while True:
tries = GuessUntilCorrect(27) #probably want to use a random number here
print("It Took %d Tries For the right answer!"%tries)
play_again = input("Play Again?").lower()
if play_again[0] != "y":
break
Don't use eval (as #iCodex said) - it's risky, use int(x). A way to do this is to use functions:
import random
import sys
def guessNumber():
number=random.randint(1,1000)
count=1
guess= int(input("Enter your guess between 1 and 1000: "))
while guess !=number:
count+=1
if guess > (number + 10):
print("Too high!")
elif guess < (number - 10):
print("Too low!")
elif guess > number:
print("Getting warm but still high!")
elif guess < number:
print("Getting warm but still Low!")
guess = int(input("Try again "))
if guess == number:
print("You rock! You guessed the number in ", count, " tries!")
return
guessNumber()
again = str(input("Do you want to play again (type yes or no): "))
if again == "yes":
guessNumber()
else:
sys.exit(0)
Using functions mean that you can reuse the same piece of code as many times as you want.
Here, you put the code for the guessing part in a function called guessNumber(), call the function, and at the end, ask the user to go again, if they want to, they go to the function again.
I want to modify this program so that it can ask the user whether or not they want to input another number and if they answer 'no' the program terminates and vice versa. This is my code:
step=int(input('enter skip factor: '))
num = int(input('Enter a number: '))
while True:
for i in range(0,num,step):
if (i % 2) == 0:
print( i, ' is Even')
else:
print(i, ' is Odd')
again = str(input('do you want to use another number? type yes or no')
if again = 'no' :
break

Categories