recursion and object recreation [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I am new to python and I am curious to why this error is occurring. This error only occurs when I input a number (selection) greater than 3. When the input is 1,2, or 3 it works as if it is supposed to
error:
File "/Users/username/Development/foodcalc/interface.py", line 12, in display_options
display_options()
NameError: global name 'display_options' is not defined
code
from interface import Interface
interface = Interface();
print "welcome"
print "what would you like to do?"
interface.display_options()
my interface.py
class Interface:
#options = ["1 - create a meal plan","2 - add food","3 - look up food"]
def display_options(self):
options = ["1 - create a meal plan","2 - add food","3 - look up food"]
for choice in options:
print choice
selection = int(raw_input())
if selection > 3:
print "Incorrect selection. Please try again."
display_options()
else:
if selection == 1:
print "meal"
elif selection == 2:
print "add"
else:
print "search"

When you attempt to call a member function or method you need to preface it with self.. Otherwise the interpreter looks for a global function with the name you've requested.

It is because you didn't use an instance to call the function. add self. in-front of the function.
As a side note; it would be better to implement this in a while loop seeing as a continuous entry of incorrect values will cause your program to crash due to reaching the recursion limit.
To prevent this bug, consider writing the function like this:
def display_options(self):
options = ["1 - create a meal plan","2 - add food","3 - look up food"]
selection = 0
while selection > len(options) or selection <= 0:
for choice in options:
print choice
try:
selection = int(raw_input())
if selection > len(options) or selection <= 0:
raise Exception()
except:
print "Incorrect selection. Please try again."
if selection == 1:
print "meal"
elif selection == 2:
print "add"
else:
print "search"

Related

New to Python looking for some assistance Assistance [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
For my class we have been instructed to execute the following:
"Create a program called ph.py that determines the acidity or basicity of a solution. It should ask the user to enter a numeric pH value. It should then call a function that accepts the value as a parameter and returns a string indicating that the solution is acidic (pH less than 7), basic (pH greater than 7), or neutral (pH is 7); it should return "invalid" if the value is greater than 14 or less than zero*. Finally, your script should then output the returned string for the user to see."
This is what I was able to come up with:
def water_ph() -> object:
ph: int = int(input("Enter the numeric value for your water: "))
if ph >= 14 or ph <= 0:
return f"{ph} invalid"
elif ph < 7:
return f"{ph} is acidic"
elif ph > 7:
return f"{ph} is basic"
elif ph == 7:
return f"{ph} is neutral"
ph = water_ph()
print(ph)
Does this look correct? it works I'm just worried I'm not answering the above question correctly.
call a function that accepts the value as a parameter
def water_ph()
I do not see any arguments in your function declaration.
returns a string
def water_ph() -> object:
Then why are you declaring the function to return an object ?
ask the user to enter a numeric pH value. It should then call a function
You are first calling the function and then asking the user for input iside this function.

Need a code to allow the user to restart my python quiz at any time [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I would like to know how I could allow my code to let the user restart the quiz at any time throughout the program however, I have no idea how to do this from scratch. It preferably needs to be fairly simple. Would it be easiest doing it as an if statement and if so what would I put in it? I tried this:
while True:
# main program
while True:
answer = raw_input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print 'Invalid input.'
if answer == 'y':
continue
else:
print 'Goodbye'
break
breaking your problem down into parts is the first step
# 1. ask a question and validate the response
def ask_question(prompt,possible_choices):
while True:
result = raw_input(prompt)
if result in possible_choices:
return result
print "Invalid Response Please Enter One Of:",possible_choices
# 2. run a whole quiz (ask all our questions)
def do_quiz():
answers = []
for question_text in questions_list:
answer = ask_question(question_text,['a','b','c','d','quit','restart')
if answer == "restart":
return False
# instead of returning false we could also simply call recursively
# return do_quiz()
elif answer == "quit":
print "Adios muchacho"
sys.exit(0)
else:
answers.append(answer)
return answers
# 3. play forever (or atleast until the user wants to quit...)
while True:
results = do_quiz()
if not results:
print "Lets Start Over!!"
continue
else:
check_answers(results)
if raw_input("Play again?")[0].lower() == "n":
print "Goodbye!"
sys.exit(1)

Why does my while loop not stop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
RANDOM_COR=random.randrange(5,6)
def check_xy_data():
global COUNT
COUNT=0
input_xy=input("input(x,y) : ")
think_xy=list(map(int,input_xy.split(",")))
if(random_array[think_xy[0]][think_xy[1]] == "C"):
screen_array[think_xy[0]][think_xy[1]] = "O"
COUNT=COUNT+1
else:
screen_array[think_xy[0]][think_xy[1]] = "X"
def main():
make_intro()
init_screen_array ()
init_random_array ()
make_random_num(RANDOM_COR)
while(True):
check_xy_data()
draw_outline_start(TOTAL_COL_NUM//2)
draw_out_rowline(TOTAL_COL_NUM//2, "Input : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Correct : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Error : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Total : ")
draw_outline_mid(TOTAL_COL_NUM//2)
if(COUNT==RANDOM_COR-1):
break
The if at the bottom of my code is supposed to get me out of the while loop, but I'm stuck in an infinite loop. Help?
(assignment, 2016) 예고편 The Assignment | 어싸인먼트 감독: 월터 힐 각본: 월터 힐, 데니스 해밀 출연: 김성훈 출연 현빈, 유해진, 김주혁 개봉 2016 한국 상세보기 그간...
Try this change:
RANDOM_COR=random.randrange(5,6)
COUNT = 0
def check_xy_data():
global COUNT
With COUNT inside check_xy_data, you set it back to 0 on every call. It can never reach more than 1. Your check is whether it's in the range 5-6. This is never true, so you can never leave the loop.
Note that trivial debugging skills would have found this: just stick a print statement before you test your loop condition, to see what the values are. Use that next time ... :-)

Newbie query about conditional statements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm learning Python and can't work out why the following doesn't work.
Can anyone advise? code below
thanks
# Make sure that the_flying_circus() returns True
print "What is your number?"
num = input()
print "What is bla?"
bla = input()
def the_flying_circus():
if num ==4 and bla=="bla": # Start coding here!
return True
print "Well done!"
# Don't forget to indent
# the code inside this block!
elif num == 2 or bla== zog:
print "OK"
# Keep going here.
# You'll want to add the else statement, too!
else:
print "Bad luck!"
the_flying_circus()
The return True is probably not what you want to have on the top of the if block. Try removing it.
The only condition that will return True is num==4 and bla=='bla'. Otherwise, the return value is None. However, 'Well done!' will never be printed since the return statement occurs first.
Couple of things...
1) return True should be moved to the end of the function (as mentioned by others)
2) watch how you collect input... use raw_input for your string, use input for the number.
This works for me:
def the_flying_circus():
if a==4 and b=='bla':
print "Well done!"
elif a==2 or b=="zog":
print "OK"
else:
print "Bad luck!"
return 1
a = input("What is your number? ")
b = raw_input("What is bla? ")
the_flying_circus()

Python 2.7.3: if statements not working within a function [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
Having a problem here with trying to add if statements to a function I am defining. To put things in context, I am programming a Black Jack simulation for a school project.
Here's what I'm having trouble with:
def getDecision():
getDecision = raw_input("What will you do? \n - Hit \n - Stand")
if getDecision = "Hit":
return hit()
I want it so that I can set two conditions in the function when it is called in main: if the player selects Hit, it returns the function hit in which the player receives a card. If the player selects Stand, the turn will transfer to the opponent (CPU).
What do I have to do to fix this? I get a syntax error on my if statement.
And here is the rest of the program as of now if you wish to scrutinize:
import random
def showMenu():
userInput = raw_input("Welcome to the game of Black Jack! Please choose an option from the following: \n - Start Game \n - Rules \n - Exit")
def getInitialMoney():
initialdough = 5000
def cardGenerator():
#Assign a random suit
suit_card = ["Hearts", "Spades", "Clubs", "Diamond"]
from random import choice
#Assign a random number between 1-13 (Ace to King)
number_card = random.randrange(1,14)
print choice(suit_card), str(number_card)
def getPlayerCards():
return cardGenerator(), cardGenerator()
def getCPUcards():
return cardGenerator(), cardGenerator()
This is where you are going wrong
if getDecision = "Hit":
should be
if getDecision == "Hit":
= is assignment and == is comparison.
This is how your final code should look like
def getDecision():
getDecision = raw_input("What will you do? \n - Hit \n - Stand")
if getDecision == "Hit":
return hit()

Categories