Random Number Guesser not running as intended - python

import random
input = input("Guess the number from 1 to 20 Computer is thinking: ")
if input.isdigit():
int(input)
else:
print("Error")
exit()
computer = int(random.randrange(1, 5))
print("Computer thinks of number", str(computer) + ".", end = " ")
if input == computer:
print("You Win!")
elif input != computer:
print("You Lost.")
Whenever I guessed the right number, It says that I lost. This is a simple project I made as a beginner so please explain in the simplest way possible

The key issue in your code is the variable not being stored.
In your provided picture here, you call int(input) to convert the input number into an integer, showing that you understand that input() returns a string (not many beginners know this!), however, you did not store the result returned by int() to a variable. In your case, it seems like you want to store it back to the input variable.
Because you did not store it, calling int(input) will not modify the value in the existing input variable, making it still string, and thus failing the comparison with the computer generated number which is an integer.
To fix this, simply replace the int(input) with input = int(input)
On a side note, it is not advisable to use variable names that are same as built-in functions, like input, or str, as doing so will override the built-in function, causing the subsequent calls to the input() function to return error, since now input is a variable, not a function anymore.

Related

unexpected function return different type / number only checker

I'm trying to make a quick and simple function to check if an entered value is an int/bool. I've had a quick look around and even the solution elsewhere comes to the same issue.
I have this in my test script and it seems to work, but when copying the exact code to my main program it will return the first value entered (say I entered hello instead of a number it will exit with "hello" after typing a number and save that to file).
Is there something with a function calling another function that causes it to fail?
I can post my actual code later, there's a lot of calls in it so it may be quite long. Will try with these short examples first and if we can't figure I can post the long one.
#option 1
import json
with open("settings.json", "r") as f:
pref_file = json.load(f)
def float_check(t):
if t.isdigit():
global prompt
prompt = float(t)
return #I have tried 'return prompt' too
else:
prompt = input ("Enter numerical value only:\n")
float_check(prompt)
prompt = input ("Enter a number: ")
float_check(prompt)
#I'm saving the value to JSON file.
#\\ settings.json
#{
# "o2_percent": 0.0
#}
pref_file["o2_percent"] = prompt
with open("settings.json", "w") as f:
json.dump(pref_file, f, indent=4)
In option 2 I tried calling a function from a function as I thought that was the issue. But this also seems to work.
#option 2
import json
def num_check(t):
if t.isdigit():
global prompt
prompt = float(t)
pref_file["o2_percent"] = prompt
with open("settings.json", "w") as f:
json.dump(pref_file, f, indent=4)
runit()
else:
prompt = input ("Enter numerical numer only:\n")
num_check(prompt)
def runit():
prompt = input ("enter a number: ")
num_check(prompt)
runit()
I found this solution (How to validate a users input to Numbers only?) and have adapted it a little but I'm having the exact same issue - my main code will return the first value entered not the number when exiting the loop.
enter number: hello
enter number: elephant
enter number: why
enter number: 5
saves value to settings.json "hello"
Also why does the first print return float as expected but the second is an str, I've done no further processing? I'm new to all this - is there some jenky thing if using variables in a function even if declared global?
def mk_float(answer):
while True:
try:
answer = float(answer)
print (type(answer)) #returns float
break
except ValueError:
answer = input ("Enter number!")
answer = input ("number: ")
mk_float(answer)
print (type(answer)) #returns int
I'm about ready to table flip.
Edit
This was my comment that I deleted, as Prune pointed out its a seperate question. But will throw it on the edit so people know what it was in reference to.
def t_check(prompt):
while True:
try:
prompt = int(prompt)
return int(prompt)
break
except ValueError:
prompt = input ("Enter a number only: ")
continue
prompt = input ("enter something: ")
t_check(prompt)
print (prompt)
print (type(prompt))
The surface problem is because, when you repeat the request for valid input, instead of using a simple loop-until-valid approach, you use recursion. As you wind back up the stack on final return, you can easily get a reversal of the data you want.
The next problem is using global variables. Use parameters for input to your function; return the result. Global variables usually indicate poor design.
Note that print returns None, not a float.
Finally, you should trace your program's execution, as well as intermediate results, using simple print commands. This is the simplest and most immediately effective debugging tool.
Does that help you get going?
I am not sure I can help with the json part of your code, however you may use this function to ask the user to input a number (float or int) :
def input_number():
try:
return float(input ("Enter numerical value only:\n"))
except ValueError:
return input_number()
When the user input something, input_number will try to return the input as a float (which cover the int type).
If the conversion to float fails, a ValueError will be catch and input_number will ask the user to enter the value again.
In your very specific case you may do pref_file["o2_percent"] = input_number()
Edit:
Looking at Prune's answer, recursion might not be the best good solution. ^_^

UnboundLocalError when making sure the input is an integer

def main():
prompt = input('How many players? ')
if prompt.isdigit():
num_players = int(prompt)
else:
print('Invalid input!')
main()
print(num_players)
main()
If I enter a valid integer from the first time, everything works as expected, but if I enter a string first, the 'else' executes and I get prompted again, However, I get the UnboundLocalError when I actually input an integer. Any help is appreciated
The problem is because this function is recursive. When you correctly enter an integer the second time, the innermost instance of main returns to the outer instance of main just after your else block. The next thing it tries to do is print(num_players) which worked fine in the inner instance but is unbound in the outer one.
Try moving the print inside the if
Note, it's not really the recursion that's the issue, it will still error if you remove the recursive call to main . The recursion just means you don't see the error until you finally enter an integer
You shouldn't be using recursion for this at all.
def main():
while True:
prompt = input('How many players? ')
if prompt.isdigit():
break
print('Invalid input!')
print(num_players)
There's no reason to use isdigit and int; you never use the int value, as it is immediately turned into a str again by print.
You can, however, use int instead of isdigit (especially if plan to use the int value later, rather than just printing it.
def main():
while True:
prompt = input('How many players? ')
try:
num_players = int(prompt)
break
except ValueError:
pass
print(num_players)

Have the boolean value of var follow into another file

I have two files in my text-based game. The variable that is being assigned will be keep_note.
If you enter "Take" the boolean value True is assigned to the have_note-001
but in the next file when if have_note_001 == True I get an error saying
have_note-001 is undefined
If keep_note is == "Take":
have_note_001 = True
Then in the next file I want that True value to travel over to the next file.
If have_note_001 == True: print("This Value Is True")
keep_paper = input("Do you want to Leave the piece of paper or Take it? > ")
if keep_paper == "Take":
have_note_01 = True
if have_note_01 == True:
print("You have chosen to keep the piece of paper")
print("You leave the house with the note(" + note_001 + ")")
This is my next file
from intros.intro_001 import have_note_001
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
In the file, the import is working.
I am importing the have_note_001. It is just not transferring the value True over. It doesnt seem to remember when you give it that value you in the first file, to the second
How can I have the value assigned to a variable carry over to another file when imported?
I'm not sure what you are asking for is in your best interest. The values stored in variables are already carried over by default when you import the file they are from. However, this type of sporadic architecture is not really considered good practice. Let me give you some feedback on your program. First lets give it some input validation:
# start off setting keep_paper to nothing
keep_paper = ''
# As long as the player does not enter 'take' or 'leave' we are going to
# keep asking them to enter a proper response.
while keep_paper not in ['take', 'leave']:
# here we are going to "try" and ask the player for his choice
try:
# here we are getting input from the user with input(...)
# then converting it into a string with str(...)
# then converting it to lowercase with .lower()
# all together str(input(...)).lower()
keep_paper = str(input("Do you want to Leave the piece of paper or Take it? > ")).lower()
# if the player entered an invalid response such as "53" we will go back
# to the beginning and ask for another response.
except ValueError:
print("Sorry, I didn't understand that.")
# ask the user to provide valid input
continue
if have_note_01 == True:
print("True")
elif have_note_01 == False:
print("False")
Now let's address the main topic of your question. Having the value assigned to a variable carry over on imports. As I've already mentioned, this is generally not something that you want, which is why most Python programs have code including:
if __name__ == "__main__":
# do xyz....
This ensures that xyz is only run if the file is being ran, and will not run if the file is imported.
For good measure, I recommend you checkout: https://github.com/phillipjohnson/text-adventure-tut/tree/master/adventuretutorial, reading over the code in this project will give you a better idea at how you might want to tackle your own project. (The basics of functions, classes and inheritance)

Python: Break statements for while blocks

import random
def get_num ():
return random.randrange (999,9999)
print ("{}".format (get_num ()))
def get_user_input():
while True:
user_input = input
print("Please enter a four digit number")
return user_input
if False:
print ("Length of string:" , len (str))
Here in this piece of coding I am trying to make a random 4 digit number which will tell user whether or not s/he has guessed the right number (essentially),
specifically though: It will tell the user (at the end of the game) if s/he has guessed certain digits correctly but not which position.
I want 'break' statement to be fitted into this which will separate the while block from the if False. How do I do this correctly? I have tried maany times but I have 4 problems:
1- I don't know where to insert the break
2- When I run the program it doesn't print the second print function.
3- When I run the program it doesn't tell me the length of the string so I don't know if the user is even enterring the correct number of digits.
4- How do I set a limit on python (i.e. how many goes a player can have before the game ends?
I guess you are new to programming and this may be one of your very first codes. It would be great if you start by learning syntax of programming language which you have decided to use as well as working of loops, return statements, etc. I personally preferred reading any basic programming language book. For your case, it would be any book of python which is for beginners. For the sake of completeness, i have added the below code which is probably not exactly what you asked for:
import random
def get_num():
return random.randrange (999,9999)
def get_user_input():
user_input = int(input())
return user_input
while True:
comp_num = get_num()
print("The computer gave: {}".format(comp_num))
print("Your turn:")
user_num = get_user_input()
if user_num == comp_num:
print("Done it!")
break
else:
print("No, it's different. Try again!")
print()
In the above code, there are two functions and a while loop. One of the functions takes input from the user while the other generates a random number. The while loop is set to run for infinite iterations in case the user doesn't give the same input as the computer. As soon as the user gives the same input as the computer (which is displayed on the screen before he is asked to give input), the if condition evaluates to true, some things are printed and the break statement breaks the loop. And since, there is no further code, the program terminates

User inputted script

I am trying to run a script which asks users for their favorite sports teams. This is what I have so far:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
Whenever I run this script, the last "else" function takes over before the user can input anything.
Also, none of the teams to choose from are defined. Help?
Input is a function that asks user for an answer.
You need to call it and assign the return value to some variable.
Then check that variable, not the input itself.
Note
you probably want raw_input() instead to get the string you want.
Just remember to strip the whitespace.
Your main problem is that you are using is to compare values. As it was discussed in the question here --> String comparison in Python: is vs. ==
You use == when comparing values and is when comparing identities.
You would want to change your code to look like this:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
print("Good choice, go Yankees")
elif input == "Knicks":
print("Why...? They are terrible")
elif input == "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
However, you may want to consider putting your code into a while loop so that the user is asked the question until thy answer with an accepted answer.
You may also want to consider adding some human error tolerance, by forcing the compared value into lowercase letters. That way as long as the team name is spelled correctly, they comparison will be made accurately.
For example, see the code below:
while True: #This means that the loop will continue until a "break"
answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower()
#the .lower() is where the input is made lowercase
if answer == "yankees":
print("Good choice, go Yankees")
break
elif answer == "knicks":
print("Why...? They are terrible")
break
elif answer == "jets":
print("They are terrible too...")
break
else:
print("I have never heard of that team, try another team.")

Categories

Resources