how to fix "<function choice at 0x105303320>" in visual studio code? - python

I wanted to make an adventure game sort of thing and it consists mostly of print and time. sleep statements. but the only if statement with a def statement is messing it up, to a point that is. everything works perfectly fine until that end.
I have no clue what is causing this to happen. I mean with some certainty I can say that the if statement is the issue but I don't know how/why.
def choice():
input("so whats for breakfast, salad, eggs, or fish")
#many lines or print and sleep statements later
if str(choice) == "salad":
#insert if code
else:
print("try again")
expected - "hey what's for breakfast?" ans = salad. "then you have three options for salads
actual - < function choice at 0x10de89560 >
the above is what gets printed in the debug console and I have no idea why. there are no warnings or errors that VS code had told me about. I am too much of a beginner to already be getting these sorts of things, please help me.

It must be.. str(choice()).
choice is a function.

fixed code, choice is a function and requires a return
# Functions
def choice():
return input("so whats for breakfast, salad, eggs, or fish")
# Entry Point
decision = str(choice())
if decision == "salad":
#insert if code
pass
else:
print("try again")
screenshot of code running

Related

Problem with restarting function over again

I started to learn coding with python couple days ago. I dont have any previous coding experience so im a total beginner. Im watching youtube tutorials and every time i learn something new, i try to play with those learnt things. Now i tried to make kind of a guess game and im having a problem with it. (jokingly first question is asking "are you idiot" lol).
I tried to make it so that you have 3 lives per question (there will be multiple questions which are just copies of this code with different questions and answers) Once you run out of lives, it asks if you want to start over and if answered yes, it starts from the question number 1. The problem is if you answer "yes", it starts over but it does not give the lives back and even if you answer correctly, it says game over. However if you answer correctly the first time without restarting, it works just fine and continues to the next question.
What am i missing here? Thanks for the answers!
def question1():
secret_word = "yes"
guess = ""
guess_count = 0
guess_limit = 3
out_of_guesses = False
game_over_question = ""
while guess != secret_word and not out_of_guesses:
if guess_count < guess_limit:
guess = input("Are you idiot?: ").lower()
if guess == secret_word:
print("correct! Next question:")
else:
guess_count += 1
if guess_count <= 2:
print("Try again")
else:
out_of_guesses = True
if out_of_guesses:
while game_over_question not in ("yes", "no"):
answer = input("Game over, want to start over?: ")
if answer == "yes":
question1()
elif answer == "no":
exit()
else:
print("Its yes or no.")
question1()
To understand this, you best use a debugger. To use a debugger, you need an IDE that has one, e.g. PyCharm. The screenshots in this question are from PyCharm. Other IDEs (like Visual Studio Code) will differ in usability but the concept will be the same.
Some background on using a debugger
When debugging, you set breakpoints, typically by clicking on the left of the line of code, e.g. like so:
With breakpoints enabled, you use the Bug icon instead of the Play icon.
The flow of execution will stop whenever the code hits a line with a breakpoint. You can then choose how to go on using these icons:
Step over this line of code
Step into this line (if there's a method call)
Step into (my code)
Step out (run the function until the end)
Run to cursor
Debugging your code
In your case, let's set a breakpoint on line 24. In this case I chose it, because it's the beginning of a recursion. However, I doubt that you have heard that term before. Without knowing it, it'll be hard to find a good line. Finding a good line for a breakpoint is a skill that develops over time.
Next, enter whatever is needed to reproduce the problem. On my machine, it looks like this:
Now, the breakpoint is hit and interesting stuff will happen.
Before that interesing stuff happens, let's look at the state of your program. As we have the call stack frames and variables:
One important thing to notice: your code is currently running line 31 (the actual method call) and while running that line, it is now running line 24.
Debugging the recursion
Now click the "Step into" button once. Note how the call stack changed and all variables seem to be lost.
We see that the same method ("question1") is called again. That's what programmers call a recursion.
Also: the variables are not lost, they are just "local" to that method. If you select the method from before, the variables will still be there:
Now, click "Step over" a few times, until you're asked for input again.
Enter "yes" as you did before.
Then, click "Step over" once. You are inside if guess == secret_word: at the print statement now.
Then, click "Step over" once. The text was printed and you are at the while loop.
In the next step, the condition guess != secret_word will no longer be met and the code will continue after the while loop, which is where the method ends.
Hitting "Step over" one more time will bring you back to where the method was before, your code has left the recursion:
Your code is back in line 24, within the while loop that asks you if you want to start over again.
Now that you understand what your code does, it should be possible to find a fix.
Takeaways
Typically it's not the computer who doesn't understand your code. It's you who doesn't understand your code :-)
A debugger will help you understanding what you told the computer. If there is a method on the call stack, then you called that method. Cool thing: you can look at each method and their variables and that'll allow you to make conclusions on how it arrived there.
Even cooler: you could change the values of these variables in order to play a "what-if" scenario.
IMHO, real debugging is more powerful than printf debugging (but still, a log file is an important concept of its own).

Code that consistently asks a question until proper input that can be repeated many times + the ability to accept multiple inputs? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
Firstly, sorry for the long title.
So... I am making a text adventure game in Python for learning purposes. I spent most of last night trying to squash a bug in my game where no matter what you typed it would take you 'north'. I could input "sadjbfl" and it would just take me "north" instead of giving an error. (But I could also put "south" and it would take me south...)
I figured out a "while True" loop by searching for how to do this online but then I ran into another couple of problems with it, the first being that I could not make it accept multiple inputs. I could not allow it to accept "'north' OR 'n'"; it would then just accept literally anything as the first choice. The second problem is that I believe I would need a "while True" loop for every choice in the game.
The other way I have tried to accomplish this is a simple "ask for 'north' or 'n' and if it's none of that then print 'error'" but when it prints an error the program stops running when I need it to re-ask the question.
"Solution" 1:
# this code works perfectly fine
# if you don't type what it wants
# it keeps asking the question again
while True:
user_input = input("Enter 'test': ")
if user_input.lower() == "test":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 1b (problem):
while True:
user_input = input("Enter 'test': ")
# With '"test" or "t"', it allows ANY input;
# it does not give an error and just prints
# 'Correct!'.
if user_input.lower() == "test" or "t":
print("\nCorrect input!")
break
else:
print ("\nInvalid input!")
"Solution" 2:
# "ch" means "choice".
# (naming scheme for less space)
ch_1 = input("\nGo north or south? ")
if ch_1.lower() in ["north", "n"]:
print("\nYou went north!")
elif ch_1.lower() in ["south", "s"]:
print("\nYou went south!")
# if this 'else' prints it ends the program instead of re-asking
# the question of 'which way to go?'
else:
print("I don't know what that means.")
EDIT: Nothing I've read on this site has actually helped me concerning this problem, not even the "duplicate" of this one (which I read before posting this).
My problem:
When I use the "while True" loop, my code becomes incredibly restrictive.
Every single choice using this method needs to be wrapped in an "while True" statement and it limits my options severely. It works perfectly if I only have one choice/path in that block BUT as soon as I add another choice/path, the new path experiences the same exact problem that I made this post for to begin with.
If there's some way to just always spit out a predefined message saying "ERROR! Check for misspellings!" or whatever every time the user does not put in what I want them to then that would be fantastic. (The "duplicate" of this post had something like this (I think) but it didn't work. /shrug)
But in the meantime I just cannot figure this out. Maybe I should just go back to the basics for a while.
In solution 2 only the loop is missing:
while True:
# name your variables correctly and no comment is needed.
choice = input("\nGo north or south? ")
if choice.lower() in ["north", "n"]:
print("\nYou went north!")
break
elif choice.lower() in ["south", "s"]:
print("\nYou went south!")
break
else:
print("I don't know what that means.")
You can write a function to reuse the loop:
def ask(question, answers):
while True:
choice = input(question).lower()
if choice in answers:
break
print("I don't know what that means.")
return choice
choice = ask("\nGo north or south? ", ["north", "n", "south", "s"])
if choice[0] == "n":
print("\nYou went north!")
else: # the only other choice is "south"
print("\nYou went south!")

Does this Dice rolling Code have good style

Hi guys I just recently started doing my own projects and I'm hoping that as I work through these things that I can make sure to make the code as neat and polished as possible since I am mostly teaching myself.
So I was wondering if this was the best way to do this Dice rolling code:
Game = input("Hello there! Would you like to bet your luck on a dice roll?\n")
if Game == "yes"or"Yes":
print("Well great! Here we go!");
import random;
print(random.randint(1, 6));
else:
print("I guess next time then...");
specifically around the "if statement" and trying to account for people using capitalization or non-capitalization. Or just how to create a better way for people to put in a variety of answers.
Thank you
So I was wondering if this was the best way to do this Dice rolling
code:
To be short: No.
Game = input("Hello there! Would you like to bet your luck on a dice roll?\n")
This will work, but it you should use lowercase for your 'Game' variable, as this style (called 'CapWords' in PEP 8) are reserved for class names.
if Game == "yes"or"Yes":
This is basicly executed as:
if (Game == "yes") or "Yes":
You see what will go wrong here? You probably want something like:
if Game == "yes" or Game == "Yes":
But even better would be to this:
if Game.lower() == "yes":
This converts the input to lower case first, so basicly ignoring any capitalization used by the user.
print("Well great! Here we go!");
Nothing wrong with this line, except the ';' are not needed in Python.
import random;
Imports should be at the top of the file.
print(random.randint(1, 6));
Again, the ';' should not be used.
else:
print("I guess next time then...");
Again, the ';' should not be used.
If I were to write this program, it would look as follows:
import random
answer = input("Hello there! Would you like to bet your luck on a dice roll?\n")
if answer.lower() == "yes":
print("Well great! Here we go!")
print(random.randint(1, 6))
else:
print("I guess next time then...")
Or just how to create a better way for people to put in a variety of answers.
If you were to expand the possible answers, your if statement would get pretty long and ugly:
if game.lower() == "yes" or game.lower() == "y" or game.lower() == "uh huh" # and so on...
So, it would be best to put these in a tuple, and then check if their answer is in the tuple:
if game.lower() in ("yes", "y", "uh huh"):
# the rest of your code here...

Python Else won't work with Modules imported?

I've been testing stuff with modules specifically time module,
and I tried doing "Else", but I just get a syntax error over the "Else", I've looked over the internet a lot, and on here, and I can't find anything, so I decided to ask Myself, I'm probably going to sound like the stupidest person on earth because of this.
Here's my code,
import time
input ("Hello, would you like to sleep?")
if input == "Yes":
time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")
else:
print("Alright.")
Your program should be like,
import time
inputString = input("Hello, would you like to sleep?")
if inputString.lower() == "yes":
time.sleep(0.5)
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
print("You have awoken!")
else:
print("Alright.")
input is a keyword in python, you can use that to refer something else, but it is highly discouraged. Also, input() returns string in python 3.x and eval(input()) in python 2.x
You know, indentation is very important in Python.
You may need to review your indentation for this. Remember, Python uses whitespace to denote code blocks. It may be that the editor has mangled your code, but it should look like:
import time
inputString = input("Hello, would you like to sleep?")
if input == "Yes":
print("Sleeping.")
print("Sleeping..")
print("Sleeping...")
time.sleep(0.5)
print("You have awoken!")
else:
print("Alright.")
Note that the if and the else are at the same level of indentation, and everything inside of there block is indented one level.

Python program, how to make an atm program loop

How do i make it loop back to the start after doing this? After each transaction, it ends and doesn't go back to see if you can pick another option.
Thanks and it's greatly appreciated.
balance=7.52
print("Hi, Welcome to the Atm.")
print("no need for pin numbers, we already know who you are")
print("please selection one of the options given beneath")
print("""
D = Deposit
W = Withdrawal
T = Transfer
B = Balance check
Q = Quick cash of 20$
E = Exit
Please select in the next line.
""")
option=input("which option would you like?:")
if option==("D"):
print("How much would you like to deposit?")
amount=(int(input("amount:")))
total=amount+balance
elif option ==("W"):
print("How much would you like to withdrawl?")
withdrawl=int(input("how much would you like to take out:?"))
if balance<withdrawl:
print("Error, insufficent funds")
print("please try again")
elif option == "T":
print("don't worry about the technicalities, we already know who you're transferring to")
transfer =int(input("How much would you like to transfer:?"))
print("you now have", balance-transfer,"dollars in your bank")
elif option=="B":
print("you currently have",balance,"dollars.")
elif option=="Q":
print("processing transaction, please await approval")
quicky=balance-20
if balance<quicky:
print("processing transaction, please await approval")
print("Error, You're broke.:(")
elif option=="E":
print("Thanks for checking with the Atm")
print("press the enter key to exit")
It seems like you are asking about a loop with a sentinel value.
Somewhere right before you print your menu, set a sentinel value:
keep_going = True
Then, preferably on the next line (before you print the first thing you want to see when it loops), you start your loop.
while keep_going: # loop until keep_going == False
As written, this is an infinite loop. Everything in the indented block beneath the while statement will be repeated, in order, forever. That's obviously not what we want -- we have to have some way to get out so we can use our computer for other things! That's where our sentinel comes in.
Build in a new menu option to allow the user to quit. Suppose you key that to "Q", and the user picks it. Then, in that branch:
elif option == 'Q':
keep_going = False
Since that's all there is in that branch, we "fall off" the bottom of the loop, then go back to the while statement, which now fails its check. Loop terminated!
By the way, you should think about reading The Python Style Guide. It's very easy to read and gives you an idea how to make your code also very easy to read. Most every Python programmer abides by it and expects others to do the same, so you should too! If you want help learning it, or aren't sure if you're doing it right, there are tools to check your code to help you keep it clean and error-free.
Happy programming!

Categories