Can i call my function in the while loop? - python

Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (_Hint: remember to use the user input lessons from the very first exercise
Extras:
Keep the game going until the user types “exit”
Keep track of how many guesses the user has taken, and when the game ends, print this out.
I actually cant figure out why my program is not printing the prints in the if clauses. Did i call wrong the first fucntions in my while loop?
import random
def cpu_guess():
cpu_number=random.randint(1,9)
return cpu_number
print(cpu_guess())
def player_guess():
player_number=input('Digit a number between 1 and 9\n')
return player_number
def game():
r_guesses=0
w_guesses=0
while player_guess()!='exit':
if int(player_guess())>int(cpu_guess()):
print('Higher value than generated')
w_guesses+=1
elif int(player_guess())<int(cpu_guess()):
print('Lower value than generated')
else:
print('You have entered the right value')
r_guesses+=1
return r_guesses,w_guesses
print(game())
I am not sure i can do this while player_guess()!='exit': Do i need to creat a variable like this
guess=player_guess() and write while guess!='exit'

You're calling player_guess over and over, and each time you call it, it will stop and wait for input. It's getting stuck waiting for input potentially three times per loop. Call the function once and save the result in a variable:
def game():
r_guesses = 0
w_guesses = 0
guess = None # Save it here
while guess != 'exit':
guess = player_guess()
if guess > int(cpu_guess()):
print('Higher value than generated')
w_guesses+=1
elif guess < int(cpu_guess()):
print('Lower value than generated')
else:
print('You have entered the right value')
r_guesses += 1
return r_guesses, w_guesses
print(game())
And then, as noted in the comments, do something similar for the computer's guess. The computers turn is changing constantly, so you may get through all the checks and get unexpected results for that reason. Think about what happens when those functions are called.

You keep changing the values in the middle of the loop; this is chaos, not a logic game.
# Get a player guess and see whether it's "exit"
while player_guess()!='exit':
# Get a new guess; also make a new target number.
if int(player_guess())>int(cpu_guess()):
print('Higher value than generated')
w_guesses+=1
# Get a new guess; also make a new target number.
elif int(player_guess())<int(cpu_guess()):
print('Lower value than generated')
else:
print('You have entered the right value')
r_guesses+=1
Instead, you need to make one target number the player is trying to guess. Do not change it during the game. Within the loop, have the player guess once: do not ask for more input until you've properly evaluated that guess and responded.
# Get a player guess and see whether it's "exit"
target = int(cpu_guess())
player_input = player_guess()
while player_input != 'exit':
guessed_num = int(player_input)
if guessed_num > target:
print('Higher value than generated')
w_guesses+=1
elif ...
See how that works? Don't go back to your input routine until you're done with the current guess. Don't go back to the target generation routine until the player is done guessing the previous number.

Related

How to make random integer reroll each time

I am a beginner to coding in general and am trying to learn python and so I have been learning how to make a few basic games to figure things out and practice my basics... I have made a game to guess the number that is generate at a random interval of 0-100 and give feedback on if you guessed higher or lower to narrow it into your results. I managed to make the game work and I started trying to add a replayability framework so when you guess correct the game restarts automatically and a new number is generated to guess, however I am not able to make a new number generate. Originally I made the number generate outside the loop and made a loop that seemed effective but the number stayed the same, added it into the loop and it changed with every guess. so I tried adding a secondary def and pointing to it and making the number regenerate there but it doesnt seem to be making a new number still, and if I remove the generation outside of def replay def game no longer sees num as a valid variable. I am unsure how to accomplish this, any advise would be helpful....
import random
num = random.randint(0,100)
def Game():
print("Guess the Number: ")
guess = input()
guess = int(guess)
if guess==num:
print ("CORRECT!!!!!")
Replay()
elif guess>num:
print ("Sorry to high... Try again")
Game()
elif guess<num:
print ("Sorry to low... Try Again")
Game()
def Replay():
num = random.randint(0,100)
Game()
Replay()
This is a example of your code written more correctly according to me:
from random import *
def Game():
replay = 0
while replay == 0:
num = randint(0, 100) # if you want the number to revert every time you make a mistake, leave the line as it is otherwise put this assignment before the loop.
guess = int(input("Choose a integer number from 0 to 100: "))
if guess == num:
print(f"{guess} is mysterious number")
replay = 1
elif guess > num:
print(f"Sorry but {guess} is high, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
elif guess < num:
print (f"Sorry but {guess} is low, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
Game()

How to have a value decrease or stay the same after a general function call?

So I am creating a hangman game. I want the remaining number of guesses to remain the same if the player guesses a letter that is in the puzzle, and I want it so decrease by 1 if they do not guess correctly. The issue I am having is since my function which checks whether the guess is in the word or not is defined outside of the main() function, each time it is called it will simply reset the value of the number of guesses remaining to what it is at the time of the function call. How do I change it so that it will still call the function when it's supposed to but decrease the remaining guesses accordinly?
def update_puzzle_string(puzzle,answer,guess):
update_bool=False
if guess in answer:
update_bool=True
for i, letter in enumerate(answer):
if answer[i]==guess:
puzzle[i]=guess
return update_bool
def play_game(puzzle,answer):
guess=get_guess()
did_update=update_puzzle_string(puzzle,answer,guess)
update_puzzle_string(puzzle,answer,guess)
print(did_update)
display_puzzle_string(puzzle)
def main():
# general identifiers
answer_update_msg='The answer so far is '
#instruction identifiers
instruct_filename='instructions.txt'
mode='r'
#puzzle word list identifiers
list_filename='word_list.py'
#choose word identifiers
correct_answer=[]
#puzzle_string identifier
puzzle_state=[]
#print instructions
print_instruction(instruct_filename,mode)
#stores correct answer as a string, identifier answer
correct_answer=choose_word(correct_answer,list_filename,mode)
#number of guesses the player has
num_guesses=4
for letter in correct_answer:
puzzle_state.append('_')
while num_guesses>=0:
play_game(puzzle_state,correct_answer)
main()
Return a value from play_game that will update your guesses
while num_guesses>=0:
num_guesses = play_game(puzzle_state, correct_answer, num_guesses)
So Over here you check if the word was correct.. ( i am guessing did_update holds the Boolean value for this).
so you check if it didnt update( answer provided was wrong.. in which case you decrements the num_guesses and return it.
def play_game(puzzle, answer, num_guesses):
guess=get_guess()
did_update=update_puzzle_string(puzzle,answer,guess)
update_puzzle_string(puzzle,answer,guess)
print(did_update)
display_puzzle_string(puzzle)
if not did_update :
num_guesses -= 1
return num_guesses

How do I add different levels & a quit option to my guess a number game?

So I'm a freshman in high school trying to figure out Python coding, and I need to make a guess a number game.
My first level works fine, but I need to make it so it has 3 different levels, and a quit option. I don't understand these while loops.
I'm really sorry if I posted something wrong or this is an already asked question, but any help would be much appreciated!
Here's my code so far:
import random
print("let's play guess a number!")
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
while number1!=guess1:
print
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
#this is where i want to be able to quit
if guess1==number1:
print("you guessed it!")
if myLevel == 2:
nextumber2= random.randint (1,100)
guess2=int(input("guess an integer from 1 to 100"))
while number2!=guess2:
print
if guess2<number2:
print("guess is too low!")
guess2=int(input("guess again!"))
elif guess2>number2:
print("guess is too high!")
guess2=int(input("guess again!"))
print("you guessed it!")
Welcome to Python! Since you're new I'll go over the fundamentals of everything you need to learn to complete this game.
Your code looks good so far. Since your question is mainly about a while loop, you'll need to learn what exactly that does. A while loop is a block of code that first checks the provided condition, then executes the indented code block if the condition evaluates to true. Then, it checks the condition again, and executes the code again if it's still true. This continues until the condition evaluates to false.
x = 0
while x < 5:
print(x)
x += 1
Try this code out. It should print 0 to 4 then stop when x = 5.
What's actually happening:
x = 0
# loop starts here
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #true
print(x)
x += 1
if x < 5: #false
# At this point, x is not longer < 5, so the repeating stops and the code continues to run as normal.
Imagine if you wanted to print numbers from 1 to 50. Would you rather have a loop, or do each number by hand like the above? In fact, if you want to print from 1 to x, where you don't know what x will be beforehand, you'll need a loop!
While loops are extremely powerful and are used all over the place. The idea is that you want to do something until some sort of flag or condition occurs, then stop doing the thing. I hope that makes sense.
Secondly, you need to learn about the input function.
x = input()
The input function is just a regular function that returns a string with the user input. If you want to make it into a number, then you have to typecast it to the type of number you want.
x = int(input())
You're already doing this. But what if you want a string?
Let's get back to your code:
myLevel=int(input("would you like to play level 1, 2, 3, or quit?"))
# User inputs "quit"
>> ValueError: invalid literal for int() with base 10: 'quit'
This happens because we already converted our input to an int. However, at no point are we doing any math with MyLevel. Here's a better way:
myLevel = input("would you like to play level 1, 2, 3, or quit?")
if myLevel == "quit":
exit() # this exits a python program entirely.
if myLevel == "1":
#do level 1 stuff
if myLevel == "2":
#do level 2 stuff
if myLevel == "3":
#do level 3 stuff
Our lives are made easier by not converting this variable. However, it's correct to convert the guess-a-number input() results because those need to be compared to other numbers.
Finally, this project is meant to teach you a very valuable lesson! Don't repeat yourself in the code. If you find yourself doing ANYTHING twice (or any number of times more than one), then use a function, loop, or other construct to condense it. We'll use your project as an example. I updated the code to get it working.
if myLevel == 1:
number1= random.randit(1,10)
guess1=int(input("guess an integer from 1 to ten"))
# This whole while loop needs to be within the "if" statement's indented block.
# Why? Because we only want to execute the code *if* we're on level 1.
while number1!=guess1:
print(str(number1) + " isn't correct.") #fixed this
if guess1<number1:
print("guess is too low")
guess1=int(input("guess again! or would you like to quit?"))
elif guess1>number1:
print("guess is too high!")
guess1=int(input("guess again! or would you like to quit?"))
# The last if statement isn't needed so I took it out.
# Why? Because if the loop ends, it's because guess1==number1. So our condition
# always returns true. Therefore, we can just move the print statement outside of the
# while loop.
print("you guessed it!")
This is a fine start and it should be working. Now, what do we do for level 2? The first thing that comes to mind is to copy paste this whole code block... but that would be repeating ourself! We're going to reject that idea straight out because we don't repeat ourselves.
Instead, let's use a function to wrap up the core of the game into a nice little repeatable action. Functions are just repeatable actions.
# define a function with a variable to hold the highest possible guess
def guess(max):
# get a random number based on our max
number = random.randint(1,max)
guess = int(input("guess an integer from 1 to " + str(max)))
while number != guess: # Guess is wrong
if guess < number:
print("guess is too low")
elif guess > number:
print("guess is too high!")
# Since guess is wrong, we can just assume we'll always do this.
# I removed the int() wrapper for the next step
guess = input("guess again! or would you like to quit?")
# Adding "quit" as an option:
if guess == "quit":
exit()
else:
guess = int(guess) # Now we can convert to int for our comparisons.
print("you guessed it!")
With this defined, now we just need to call the function itself at the correct difficulty.
if myLevel == "1":
guess(10)
if myLevel == "2":
guess(100)
if myLevel == "3":
guess(500)
If you're still alive after reading all this, hopefully you noticed a problem here -- we're repeating ourselves with 3 different if statements. We can do better, but that's a lesson for another day!
tl;dr:
1) Input returns a string, so you converted it to an int immediately. However, a string of "quit" is a valid choice and this will give you an error if you convert it to an int. Instead, test for "quit" first, then convert to an int if needed.
2) A while loop is for repeating something until some sort of condition is cleared. Loops and if statements can be nested within other statements. Think about when you want your code to run and honestly just practice a bit to make this more natural.
3) If you're repeating something in your code (copy/pasting similar things over and over again), strongly consider making a function or loop or something similar to do the work for you!
For the quit it's simple. Either use quit(), or, if you don't want to reload the program, put everything in a while loop and have the quit function set it to false, and then true after a while. For the 3 levels, you could either write 3 entirely separate programs or use if statements to change numbers or something. I'm not sure that would work, though.
As for your while problem, just use while some_variable='whatever_you_want': and you're done.

PYTHON Why is my if statement always returning false

I am new to python and trying to write a program that requires the user to guess a number, 1 - 6 and then they are told if they guessed right or not. However, even when the user guesses right the else statement is still returned.
I apologise for the beginner question, although this really has me stuck because the 'guess' variable is being assigned correctly, I tested this by moving the print("Your guess was: ",guess) outside of the function and executed after the function was called which always returned with the same value that the user inputs.
#Function to take guess
def userGuess (guess):
guess = input("Take a guess.\n")
print("Your guess was: ",guess)
return guess
#Define Variables
diceNum = random.randint(1,6)
guess = 0
#Call Function
guess = userGuess(guess)
#Check answer
if guess == diceNum:
print("You guessed right!, the number was: ",diceNum)
else:
print("You did not guess it right, the number was: ",diceNum)
You need to convert the user input to an integer prior to comparing:
guess = int(input("Take a guess.\n"))
If you want an explanation as to why your if statement returned false for a comparison between an integer and a string, take a look at this question.

Python 'Guess Your Age' Remember Last Integer

I am relatively new to programming with python (actually programming in general). I am making this 'Guess My Age' program that only has one problem:
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
num = 80
min_num = 6
tries = 1
number = random.randint(min_num, num)
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower()
while guess != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif guess == "higher":
print("Let me think...")
min_num = number + 1 #### Here is my trouble - Don't know how to limit max number
time.sleep(3) # pause
elif guess == "lower":
print("Let me think...")
num = number - 1
time.sleep(3) # pause
number = random.randint(min_num, num) #<- Picks new random number
print("\nLet me guess... You are", number, "years old?")
guess = input("'Higher', 'Lower', or was it 'Correct'? ")
guess = guess.lower() #<- Lowercases
tries += 1 #<- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)
As you can see, I have 'num' as the max number for the random integer getting picked, but with:
elif guess == "higher":
print("Let me think...")
min_num = number + 1
it can go back up to however high it wants.
I want it to remember the last integer that 'num' was.
Say the program guessed 50 and I said 'Lower'. Then it said 30 and I said 'Higher'
I know I am probably sounding confusing, but please bear with me.
You need to define a maximum number as well as a minimum number. If they say their age is lower than a given age, you should set that age minus 1 as the maximum.
Of course, you also need to set an initial maximal age.
You might find it more useful to look into recursive functions for this kind of problem. If you define a function which takes min_age, max_age and tries_left as parameters, which comes up with a random number with between min_age and max_age and queries the user, you can then rerun the function (within itself) with a modified min_age, max_age and tries_left - 1. If tries_left is zero, concede defeat. This way you might get a better understanding of the logical flow.
I have left code out of this answer because, as you are a beginner, you will find it a useful exercise to implement yourself.
Cant you split out your guess into something like
max_num = 0
min_num = 0
elif guess =="lower":
max_num = number
if min_num!=0:
number = min_num+(max_num-min_num)/2
else:
number = max_num-1
elif guess =="higher":
min_num = number
if max_num!=0:
number=min_num+(max_num-min_num)/2
else:
number=min_num+1
Sorry it's not meant to be fully rigorous, and its a slight change on the logic you have there, but splitting out your variables so you have a higher and lower cap, that should help a lot?
Cheers
Please let me know if you need more elaboration, and I can try to write out a fully comprehensive version
It seems as though I was wrong in the fact that it did not remember the older integers. Before when running the program it would guess a number higher than the 'num' had specified. I don't know what I changed between then and now? But thank you for the help! #.#
This seems to work.
The only changes I really made:
-Variable names were confusing me, so I changed a couple.
-Note that if you try to mess with it (lower than 5, higher than 3... "Is it 4?" if you say it's higher or lower, you'll get an error).
The first time you set min and max numbers, you do it outside of the loop, so this script does "remember" the last guess and applies it to the new min, max inside of the loop. Each time it runs, the min will get higher or the max will get lower, based on the feedback from when the user checks the guess. If you had stuck the "min_num=6" and the "num=80" inside of the loop, the guesses would never get better.
import random
import time
import sys
print("\tAge Guesser!")
print("\t8 tries only!")
name = input("\nWhat's your name? ")
max_num = 10
min_num = 1
tries = 1
guess = random.randint(min_num, max_num)
print("\nLet me guess... You are", guess, "years old?")
check = raw_input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower()
while check != "correct":
if tries == 8:
print("\n I guess I couldn't guess your age....")
print("Closing...")
time.sleep(5)
sys.exit()
elif check == "higher":
print("Let me think...")
min_num = guess + 1
time.sleep(3) # pause
elif check == "lower":
print("Let me think...")
max_num = guess - 1
time.sleep(3) # pause
guess = random.randint(min_num, max_num) # <- Picks new random number
print("\nLet me guess... You are", guess, "years old?")
check = input("'Higher', 'Lower', or was it 'Correct'? ")
check = check.lower() # <- Lowercases
tries += 1 # <- Ups the tries by one
print("\nPfft. Knew it all along.")
time.sleep(10)

Categories

Resources