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.
Related
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 1 year ago.
Improve this question
I'm making a simple program in order to compare the currentdate to another date, and I need to separate the "/" and remove trailing zeros; I made a function for that:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return
The code works just fine but i want to save the DaysLeft, Monthsleft to print it/edit it ETC..
so i do this:
correctdate(compare,Dayslist,Monthslist)
print(correctdate.Daysleft)
and i get this:
AttributeError: 'function' object has no attribute 'Daysleft'
There was a typo in printing the object attribute
I wrote:
print(correctdate.Daysleft)
Its supposed to be:
print(correctdate.DaysLeft)
Sorry for the inconvenience
You ve to return it in your function, and outside it get it into variables:
def correctdate(compare, Dayslist, Monthslist):
for day in compare:
if day == "/" or day == "\\":
compare.remove(day)
break
else:
Dayslist.append(day)
for removenum in Dayslist:
#* Removing the numbers from the list
compare.remove(removenum)
for month in compare:
Monthslist.append(month)
#* Joining the numbers into a string
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
#* Stripping leading zeros
correctdate.DaysLeft = correctdate.DaysLeft.lstrip("0")
correctdate.MonthsLeft = correctdate.MonthsLeft.lstrip("0")
return correctdate.DaysLeft,correctdate.MonthsLeft
This for return outside function, now you ve to call function correctly:
DaysLeft,Monthsleft = correctdate(compare,Dayslist,Monthslist)
print(DaysLeft,Monthsleft)
Anyway this code "correctdate.MonthsLeft" looks like you want use class and not only functions, so you should use like that https://www.w3schools.com/python/python_classes.asp
def correctdate(compare, Dayslist, Monthslist):
You declare a function with name correctdate that accepts 3 parameters.
correctdate.DaysLeft = "".join(Dayslist)
correctdate.MonthsLeft = "".join(Monthslist)
Then you try to assign a value to a function, which is not possible because correctdate is not a variable, not an object. You just declared it as a function.
What are you trying to achieve?
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making a hangman game and testing how different letter picking algorithms fare, but to do this, the guessing algorithm function has to feed a letter into the hangman function's input('Select a letter').
How do you make it so that a function detects when another function is waiting for an input ?
Assuming you are doing input() in a loop inside your hangman function, you could switch that to a yield and let an external function drive input as needed. In this example I have a hangman function that uses yield to get data. Now its a generator and driving function can use next and the generator's .send method to pump data into it.
def hangman(chances=5):
for i in range(chances):
letter = yield "prompt"
if letter == "quit":
yield "quit"
return
print("letter", letter)
# do all the things
solved = False
if solved:
yield "solved"
yield "failed"
def command_line_prompt_hangman():
feeder = hangman()
state = next(feeder)
while state == "prompt":
state = feeder.send(input("Next letter: "))
def test():
# after years of testing the best algorithm is
test = ['a', 'b', 'c', 'd', 'e', 'f']
feeder = hangman()
assert next(feeder) == "prompt"
for count, letter in enumerate(test, 1):
state = feeder.send(letter)
if state == "solved":
print("did it in ", count, "tries")
break
if state == "failed":
print("exceeded count")
break
command_line_prompt_hangman()
test()
Instead of using the input function, write a custom function to pull an output from whatever algorithm you are using. That would look something like this:
user_input = algo_obj.get_input(game_state)
In this case, algo_obj would be an object storing the current state of the algorithm/generator (if such a state exists, otherwise you can just call the function normally). game_state would be some representation of the game's current state (available letters, the word-form -- ie. blanks & letters).
You can then feed user_input to your Hangman function.
This should be as simple as:
Define both functions.
Pass one function return value to the other one as argument.
This can be done by using input() as according to this
e.g. Define the functions
def first_function():
input_variable = input("Please enter some data")
return input_variable
def second_function(a):
print(a) # Do some calculations here
And use them:
second_function(first_function())
I wouldn't say that this is necessarily the best way to go about but it solves Your problem. If You would like to receive a more detailed answer please provide code samples.
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 ... :-)
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 have this code, but if I type nam(2,3) it doesn't do anything. What is the problem?
def nam(a, y):
a = int(input())
y = int(input())
e = a+y
print(e)
EDIT
How to make the insert only integers not be an infinite loop and just declare it once and expect a valid input??
def aa(nam, x):
na = (nam)
while True:
try:
age = int(x)
except ValueError:
print("Insert only integers")
continue
else:
break
print(na,age)
aa("nic", "adeg")
You're calling input(), so the program is waiting for the user input. Moreover, the function will use this user input to override the a and y values it was passed, which probably isn't want you meant to do. Remove the input calls and you should be OK:
def nam(a, y):
a = int(a)
y = int(y)
e = a+y
print(e)
You are passing the arguments to the function but then asking the user for input (which is why "nothing happens". The program waits for that input).
Simply use the arguments you are passing in.
def nam(a, y):
e = a + y
print(e)
nam(2, 3)
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"