Python, making a function - python

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

Related

Repeating a function with another function

for an assignment we needed to make a function that flipped a coin and another to flip it 100 times. I was able to make a function that flipped a coin, but got stuck when trying to call it a 100 times with another function. This is what I have right now:
import random
def TC():
face = random.randint(0,1)
if face == 1:
return "head"
else:
return "tail"
print TC()
def ply(flips):
for i in range(flips):
return TC()
print ply(100)
When I run it it just says 'none.' Please tell me where I am going wrong. Thank You!
Just to start, your method naming is very bad. I doubt this is how your professor is teaching you to name methods and variables. It's ugly, against Python standards and hard to read I suggest you take some time and read PEP 8 it's how python was intended to be written.
So instead of TC you should use something like flip_coin and instead of ply use something like play_coin_flip or even simply play.
Next I don't know if I'm stepping outside of what you have learned but instead of using randon.randint you can use randon.choice.
And finally, as others have said, when you return you quit any other execution in a function and return whatever variable you retrun in that statement thus nullifying any other iterations of the loop you're performing. I suggest something like the below as a better program with corrections applied to make it function as intended.
from random import choice
faces = ['head', 'tail']
def flip_coin():
face = choice(faces)
return face
def play_coin_flip(flips = 1):
for i in range(flips):
print(flip_coin)
if __name__ == "__main__":
play_coin_flip(100)

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.

How would I make what the user typed for else into a variable/input?

else=(x = raw_input("Enter\n")):
print(x)
I have tried doing this basing it off of the correct statement...
x = raw_input("Enter\n")
print(x)
if your doing an if statement and you wanted the input after else is ran you would just run it as normal in the if/else flow.
But depending on what you are actually trying to do its likely to have a better way to do it. Not sure your skill level but i would HIGHLY recommend Jessica McKellers basic tutorials on youtube or the basic Python tutorial like Tigerhawk recommended.
if something:
print("Hello")
else:
x = raw_input("Enter Something ")
print(x)

How to append function to a list then print it

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

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