Program restarts when a function returns - python

I've made a program which does Pythagoras theorem for you if you just insert the lengths of the sides.
from math import *
def pythag(a , b):
c = sqrt(a^2 + b^2)
return c
print(pythag(3,4)) # added this as recommended in comment
But when I run it, this happens:
RESTART: C:/Users/Andrei/Documents/USB Backup/Python/Ultimate Calculator/functions2.py
5.0
I'm a noob at python so I don't really see the problem with the code.

You've written a function that does what you say but you're not actually calling it anywhere. The top level statements in your program are an import and a def and only those are called when you "run" it.

You have to run the function after the code you already have (e.g. for values 3 and 4):
from math import *
def pythag (a, b):
c = sqrt(a**2 + b**2)
return c
print(pythag(3,4))

Rather than importing math you could use the power signs.
For example:
def pythag(a , b):
c = (a**2 + b**2)**0.5
return c
print(pythag(3,4))

Related

Rewriting a multivariable function in python as a single variable one using sympy

def cost(d,c):
return [insert formula]
cost=sp.lambdify([d,c],cost(d,c))
In the context of the problem, there is a way to write c in terms of d. I called this formula for c "rs". I am trying to change cost to a function dependent on only d with the below code.
cost=sp.lambdify(d,cost(d,rs))
However, if I were to run cost(8) or whatever, I am told
"String fallback in sympify has been deprecated since SymPy 1.6. Use
sympify(str(obj)) or sympy.core.sympify.converter or obj.sympy
instead. See https://github.com/sympy/sympy/issues/18066 for more
info."
So what is the proper way to attack this problem?
Maybe something like this?
>>> def cost(a, b):
... return a + b
...
>>> def rs(a):
... return a**2
...
>>> cost_a = lambda a: cost(a, rs(a))
>>> cost_a(2) # cost(a, rs(a)) = cost(a, a**2) = a + a**2 = a*(1 + a)
6

print depending how many arguments given

Python beginner here trying to learn by doing, here i have two functions 'main','area'.
the one which has two arguments should print y = math.pi *a*b and the one which does not have two arguments should print x = math.pi *a**2 in my code it is currently printing like this " First (153.93804002589985, 0.0)
Second (78.53981633974483, 62.83185307179586) " (why its printing these 0.0 and 78.53981633974483?), how to make it check that if one parameter is given do this and if two do that ?
import math
def area(a,b=0):
y = math.pi *a*b
x = math.pi *a**2
return x,y
def main():
print("First", area(7))
print("Second", area(5, 4))
main()
If I understand you correctly, you want something like this:
import math
def area(a, b=None):
if b is None:
# b not specified:
x = math.pi * a**2
else:
# b specified:
x = math.pi * a*b
return x
def main():
print("First", area(7))
print("Second", area(5, 4))
main()
Output is
First 153.93804002589985
Second 62.83185307179586
When b is not specified, it is set to None. Then you test for that in the function.
The reason it prints e.g. (153.93804002589985, 0.0) in your original example is that you return a tuple (x, y) from the function with return x,y.
Your function returns a tuple, but the caller of the functions does not know which value to use. Instead, your function should just return either one or the other value, depending on the provided inputs. Also, I would suggest using None as the default for b since 0 might be a valid value.
def area(a, b=None):
if b is None:
return math.pi * a**2
else:
return math.pi * a * b
Alternatively, you could also use a ternary ... if ... else ... for either the entire expression or just the part that is different:
def area(a, b=None):
return math.pi * a * (b if b is not None else a)
The output will then be just
First 153.93804002589985
Second 62.83185307179586

Create a function that accepts an expression as an input in python

I am busy just doing some code on the bisection method. It is easy of course to just write the script and run it. However, the trick comes in when I want to define a function that will take an expression such as x**2 as an input. I've scrapped something together though. It sort of gets the job done but then at my first if statement it complains about not being able to multiply a function by a function. How would I solve this problem as well?
I really tried doing my homework on this problem before asking and unfortunately cannot find the solution. I would just love to know how to do this though.
from sympy.abc import x
def bisect(f, a, b):
f = lambda x: f
f_a, f_b = f(a), f(b)
tol = 1e-4
count = 0
print '\t'.join( ['Step' , 'a', 'b', 'c', 'f(c) ' , '(b-a)/2)'])
while (b-a)/float(2) > tol:
c = (a+b)/2
f_c = f(c)
print '\t'.join( [str(count) , str(a) , str(b) , str(c), str((b-a)/float(2) )])
if f_a*f_c < 0:
b = c
f_b = f_c
else:
a = c
f_a = f_c
count = count + 1
Is this what you need to know?
>>> def demo(func):
... for i in range(5):
... print func( float(i))
...
>>> demo( lambda x: x**2 + 2*x - 5 )
-5.0
-2.0
3.0
10.0
19.0
You can also pass in a function created with def as well as a one-liner defined with lambda. the above is the same as
def foo(x):
return x**2 + 2*x - 5
demo( foo)
The other thing you might want to know is that
definition = "x**2 + 2*x - 5" # or read it from the user as text input
demo( eval( "lambda x: " + definition))
works ...
obligatory warning, "eval is evil", accepting Python code from a user and executing it is generally regarded as a security no-no-NO! However, if this code is run by the same user who is experimenting with plotting mathematical forms, no great harm can come of it. He can't do anything worse than what he could do with python at the command line. If you were to do anything like this in a web-server or suchlike, I would fear for your employment and future prospects thereof!
Let's assume you have created an expression for function f using sympy:
f = x**2-0.1
Your bisect function will work if you change the lambda definition:
def bisect(fexpr, a, b):
f = lambda xval: fexpr.subs(x,xval)
f_a, f_b = f(a), f(b)
...

Function handle to a built-in operator in Python

Given the following minimal snippet of code:
def cmp(a, b, cmp):
return cmp(a, b)
a = 1
b = 2
print(cmp(a, b, operator.__eq__))
I'd just like to give a built-in operator like == or > as a function handle into a function. This would be useful for example, if comparisons all need some pre-checks.
The last line gives an error, as it does not know operator.__eq__. How do I correctly name (and import) that == operator on that line?
Just add import operator and the code is working.
import operator
def cmp(a, b, _cmp):
return _cmp(a, b)
a = 1
b = 2
print(cmp(a, b, operator.__eq__))
I have renamed the function parameter for clarity.

Python returning variables from various functions

from __future__ import division
import math
def main():
the_discriminant = discrim(1,0,-4)
print the_discriminant
the_rest(discrim,b,a)
def discrim(a,b,c):
discriminant = math.sqrt(math.pow(b,2)-4*a*c)
return discriminant, b,a
def the_rest(discrim,b,a):
x = ((-b + discriminant) / 2*a)
y = ((-b - discriminant) / 2*a)
print x,y
if __name__ == '__main__':
main()
I am fairly new to Python, and I'm playing with writing functions and returning variables, I'm a little confused on how to correct the code. I am writing a quadratic solver program, but I need to use the discriminant and a,b,c values in "the rest" function. (which does the rest of the equation.) I'm kind of confused on how to return the values and use them in another function. Thanks!
the_rest(*the_discriminant)
or (and I prefer this method):
d, b, a = discrim(1, 0, -4)
the_rest(d, b, a)
I believe this is what you're trying to do. your discrim function returns a tuple (similar to an array). Then when you call the_rest using a * indicates that you want to send the elements of the tuple, rather than the tuple itself as one argument
from __future__ import division
import math
def main():
the_discriminant = discrim(1,0,-4)
print the_discriminant
the_rest(*the_discriminant)
def discrim(a,b,c):
discriminant = math.sqrt(math.pow(b,2)-4*a*c)
return discriminant, b,a
def the_rest(discrim,b,a):
x = (-b + discrim) / (2*a)
y = (-b - discrim) / (2*a)
return x, y
if __name__ == '__main__':
main()
while jamylak's answer is correct, it can also be much more maintainable to return a simple class. Then if you ever change your function/return values/representation, the calling code:
is name/identifier-based; it is very flexible to change; its not order dependent, or tuple length dependent. It is also saves you typing and unnecessary duplication of ordering implied rules throughout your code.
if there IS a breaking change the interpreter will error on module load instead of at runtime, so you are not going to miss the error. This is because you are trying to access named members, and are not relying on some "hidden" or "implied" rule like tuple ordering that is not formalised anywhere in the code.
For a larger project this is definitely the way to go.
There's nothing wrong with returning tuples like in your version of discrim. But the code just doesn't make as much sense (IMO) that way.
Try it like so:
#!/usr/bin/env python
from __future__ import division
import math
def main():
a = 1
b = 0
c = -4
the_discriminant = discrim(a, b, c)
print the_discriminant
x, y = the_rest(the_discriminant,b,a)
print x, y
def discrim(a,b,c):
discriminant = math.sqrt(math.pow(b,2)-4*a*c)
return discriminant
def the_rest(d, b,a):
x = ((-b + d) / 2*a)
y = ((-b - d) / 2*a)
return x,y
if __name__ == '__main__':
main()

Categories