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.
Related
I am trying to add together two user inputs for numbers and show the results of the two added together.
This is what my code currently looks like:
number1= eval(input("total price of cleaning for your house size:"))
number2= eval(input("Price for the cleaning type:"))
def addition(a,b):
addition =a-b
return addition
print("You owe:",addition(int(number1),int(number2)))
both user inputs are based on earlier calculations within my code.
I had submitted a code almost identical to this, and it had performed correctly, so I am not sure why this one is not.
In the "assistant" it shows "str" is not callable, and redefining the name "addition" from the outer scope.
I have tried multiple different ways to make this code work and have not been able to have it run successfully to where it calculates and displays the cost.
eval return int try this :
number1= eval(input("total price of cleaning for your house size:"))
number2= eval(input("Price for the cleaning type:"))
def addition(a,b):
addition =a-b
return addition
print("You owe:",addition(number1,number2))
I suspect you don't want to use eval, just:
number1= input("total price of cleaning for your house size:")
number2= input("Price for the cleaning type:")
def addition(a,b):
addition =a-b
return addition
print("You owe:",addition(int(number1),int(number2)))
input will present a prompt and read the value entered by the user into a string. eval will parse the expression the user enters and will try to execute it as a python script; the return value will be the results of evaluating the text as a python script. So, for example, x = 1; eval("x+1") will return 2.
I assume you just want to read an integer value, so:
number = int(input("Price for the cleaning type:"))
I am facing challenges implementing OOP in python to enable me to call the functions whenever i want , so far i have no syntax errors which makes quite challenging for me . The first part of the code runs ehich is to accept data but the function part does not run.
I have tried different ways of calling the function by creating an instance of it.
print (list)
def tempcheck(self,newList):
temp=newList[0]
if temp==27:
print ("Bedroom has ideal temperature ")
elif temp>=28 or temp<=26:
print ("Bedroom Temperature is not ideal ,either too low or too cold. ")
print ("Please to adjust the temperature to the optimum temperature which is 27 degree Celsuis")
# now to initialize args
def __init__(self,temp,puri1,bedwashroom,newList):
self.temp=temp
self.puri1=puri1
self.bedwashroom=bedwashroom
tempcheck(newList)
# now calling the functions
newvalue=tempcheck(list)
# where list contains the values from the input function.
I expected the function to to check the specific value at the location in the list provided which is called list and also for the function to return a string based on the if statements.
i got it right ,i figured out an alternative to my bug thanks for the critique however any further addition is welcome,
the main goal was to create a function that takes input and passes it to list to be used later i guess this code is less cumbersome
the link to the full code is pasted below
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)
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())
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.