How to append function to a list then print it - python

I am creating a basic recipe viewer in python, I stumbled across a problem of which when I try to print my saved recipe it displays [None], as seen the recipe is firstly a function, then it is appended onto a list then I try to print it when loading it.
The code below can explain more. How do I stop the [None, None] from appearing? The code below is a sample I made which I could easily adapt to resolving my issue in my recipe rather than posting my entire code on here.
b = [] #this is meant to resemble my list
def function(): # this is meant to resemble my recipe
print("hi")
function()
a = input('write 1 = ') # this is meant to resemble the user to saving the recipe
if a == '1':
b.append(function()) # this is meant to resemble me saving the recipe onto a list
print(b) # this is meant to resemble me loading the recipe
When I run my code , sorry don't have enough reputation points to post an image but this is what comes up in the python shell
hi
write '1' = 1 #user input
hi
[None]

You are not returning anything from your function. You are printing, but that's not the same thing.
Use return to return the value:
def function():
return "hi"
print() writes to your terminal, the caller of the function is not given that output.
You can always use print() to print the return value:
print(function())

Related

passing values across functions yields no output

I have the code below where I use python package click to fetch some input from user. I then pass the user input to a function that has code to load a pre-trained model. I return a list of values that I pass to a second function that generates text using the model and other values. However the values aren't passed from first function to the second because when I try to print the list I get nothing. Could someone point out what I'm doing wrong, thanks a lot!!
#click.argument('email_template', nargs=1)
def load_model(email_template):
## code block here
list1 = [email_template, value1, value2]
return list1
def generate_text(value2):
# code block here
return result
if __name__ == '__main__':
list1 = load_model()
list2 = generate_text(list1)
print(list2)
You are missing a #click.command() decorator. It is not enough to use #click.argument(), then expect this to work. The #click.command()-decorated function becomes the entry point of your script, and should not be seen as something that'll return the user options.
Also, if email_template is the only option your script takes and it expects just one value, there is no point in using nargs=1.
So do this:
import click
#click.command()
#click.argument('email_template')
def load_model(email_template):
## code block here
# This is your *main script function*.
list1 = [email_template, value1, value2]
# don't return, continue the work you need doing from here
list2 = text_generator(list1)
print(list2)
def generate_text(result):
# code block here
return value2
if __name__ == '__main__':
load_model()
When load_model exits, your script exits.
Also, rather than use print(), consider using click.echo(), especially when you need to print text that uses non-ASCII characters and needs to work on a variety of platforms, or if you want to include ANSI colors in your output.

Python, making a function

I'm struggling a lot with my code. Now my teacher wants me to make a function out of this and I'm really trying but I can't figure it out.
So I need to make a function out of this and then call it again further down. Can someone please help me or give me some tips :) :)
opengraph = False
while opengraph is not True:
if len(sys.argv) == 2:
name = sys.argv[1]
g = openmap(name)
opengraph = True
else:
try:
name = raw_input('Please enter a file: ')
g = openmap(name)
opengraph = True
except:
print 'Not able to read the file you wrote, try another time.'
origdest = raw_input('Enter origin and destination (quit to exit): ')
There are tons of references, on the internet, on how you can do this. Like this one, or this one, or this one.
Anyways.. you need to use def, give it a name and its input parameters, like this:
def MyFunction(input1, input2):
# <Rest of the code here>
Don't forget identation and if you are expecting your function to return something you need to insert a:
return output1, output2, output3
in the end.
Once you function is defined, you just need to call it in your main code and pass the correct input arguments if there is any.
output1, output2, output3 = MyFunction(input1, input2)
I hope this link to this tutorial helps, functions must be defined and then called to execute. In Python, functions syntactically look like this...
def nameOfFunction (parameters):
code to perform task/tasks...
# Call your function...
nameOfFunction(parameter)
Follow this link to go to the tutorial and good luck! Link to tutorial

Python: Why my function returns None and then executes

So, I have a function which basically does this:
import os
import json
import requests
from openpyxl import load_workbook
def function(data):
statuslist = []
for i in range(len(data[0])):
result = performOperation(data[0][i])
if result in satisfying_results:
print("its okay")
statuslist.append("Pass")
else:
print("absolutely not okay")
statuslist.append("Fail" + result)
return statuslist
Then, I invoke the function like this (I've added error handling to check what will happen after stumbling upon the reason for me asking this question), and was actually amazed by the results, as the function returns None, and then executes:
statuslist = function(data)
print(statuslist)
try:
for i in range(len(statuslist)):
anotherFunction(i)
print("Confirmation that it is working")
except TypeError:
print("This is utterly nonsense I think")
The output of the program is then as follows:
None
This is utterly nonsense I think
its okay
its okay
its okay
absolutely not okay
its okay
There is only single return statement at the end of the function, the function is not recursive, its pretty straightforward and top-down(but parses a lot of data in the meantime).
From the output log, it appears that the function first returns None, and then is properly executed. I am puzzled, and I were unable to find any similar problems over the internet (maybe I phrase the question incorrectly).
Even if there were some inconsistency in the code, I'd still expect it to return [] instead.
After changing the initial list to statuslist = ["WTF"], the return is [].
To rule out the fact that I have modified the list in some other functions performed in the function(data), I have changed the name of the initial list several times - the results are consistently beyond my comprehension
I will be very grateful on tips in debugging the issue. Why does the function return the value first, and is executed after?
While being unable to write the code which would at the same time present what happened in my code in full spectrum, be readable, and wouldn't interfere with no security policies of the company, I have re-wrote it in a simpler form (the original code has been written while I had 3 months of programming experience), and the issue does not reproduce anymore. I guess there had be some level of nesting of functions that I have misinterpreted, and this re-written code, doing pretty much the same, correctly returns me the expected list.
Thank you everyone for your time and suggestions.
So, the answer appears to be: You do not understand your own code, make it simpler.

How to convert user input text to programming text in python 2?

So I was writing a function for Euler's Method for solving first order differential equations. My problem is that I have to change the code every time I want to change the differential function.
Is it possible to have the user input an expression and then get the program to use that input to carry out a calculation?
def derivative(a,b):
func=a**2+b**2
return round(float(func),4)
def euler(x_in,y_in,x_fin,step):
rounder = [x_in,y_in,x_fin,step]
for i in rounder:
i=round(i,4)
x=x_in
y=y_in
while not(x==x_fin):
der=derivative(x,y)
x=round(x+step,4)
y=round(y+(der*step),4)
print y
I would like to be able to change the func variable in the derivative function on user input.
ive had this problem today and got it to work using a dictionary.
What I did is:
1st step, defining functions:
def hello():
print('Hello')
2nd step, defining dictionary:
func_dict = {'goodbye':hello}
3rd step, asking for command:
command = input('Goodmorning Sir.')
4th step, asking for the translation of input to output (goodbye->hello in this case, you can also use the same words):
func_dict[command]()
Hope this was clear enough, ill put my full code below (from a different code though) if you want to see an example.
thanks DYZ for editting at first glance.
def test():
print('Test is successfull')
def help():
pass
func_dict = {'test':test,'help':help} # In this case the 1st is the input, 2nd output
command = input('> ')
func_dict[command]()
EDIT: Maybe using .int or .float will be better in this case.

Change python command to subtract value instead of add in MYSQL

Just got one other question for my python plugin.
Here is the code:
def cmd_give(self, data, client=None, cmd=None):
"""
^3<player> <money> - Give someone however much money you want.
"""
input = self._adminPlugin.parseUserCmd(data)
if not data:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
if len([x for x in data if x.isspace()]) < 1:
client.message('^7 correct syntax is !give <player> <money>')
return False
else:
input_data = data.split(' ',1)
scname = input_data[0]
ammount = int(input_data[1])
sclient = self._adminPlugin.findClientPrompt(scname, client)
if not sclient: return False
self.earn_money(sclient, ammount)
return True
Now this obviously adds the value given in the command to the user inputting into mysql.
I'm also wanting a command to subtract any value given in the command as well.
So this command above is a give and I also want a take.
My problem is I don't know what the change is to minus the amount off the value input instead of adding.
Hope someone can help,
Thanks guys.
Without modifying the function that does the actual addition, the suggestion by Rob Watts in a comment will work:
ammount = -int(input_data[1])
You can either create a new function, cmd_take, and do that there, or have a more general function (cmd_transaction?) that takes an extra argument (eg give) and has the appropriate logic:
if not give:
ammount = -int(input_data[1])
In the first case, it would be good practice to extract most of the code to a helper function, to avoid repetition, but if you don't know python and this is just a one time thing, having a cmd_take function that is exactly like command_give, except for that one line, is the simplest solution.

Categories

Resources