Python - Function creation with arguments that aren't recognised [closed] - python

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)

Related

Confused about how the return works in python [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
The program runs and the function works but I am not able to see my docCountryList in the output. Can someone tell me why?
I have this code
def ViewByCountry(docID,user_selection):
docCountryList=[]
for x in jfile:
if x.get('subject_doc_id') == docID:
docCountryList.append(x['visitor_country'])
if user_selection == '2a':
x = []
y = []
#Insert countries and number of occurences in two seperate lists
for k,v in Counter(docCountryList).items():
x.append(k)
y.append(v)
plt.title('Countries of Viewers')
plt.bar(range(len(y)), y, align='center')
plt.xticks(range(len(y)), x, size='small')
plt.show()
return docCountryList
and in my main
from program import ViewByCountry
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
docID = input("Enter required document ID: ")
user_selection = input("Enter selection")
ViewByCountry(docID,user_selection)
You never print out the value of docCountryList, so try this:
print(ViewByCountry(docID,user_selection))
This will print out the value.
You can do this as well:
lst = ViewByCountry(docID,user_selection)
print(lst)
In your main you can change to myView = ViewByCountry(docID,user_selection) and then add print(myView). This saves the list created by your function to a variable to be printed or used later.

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.

How to have a function feed another function's input [closed]

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.

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()

Categories