stacked functions / one in another - python

I am a fresh beginner in learning Python, and need some hints to understand the following exercise :
the goal is to write a script that uses the cube function in the calculus of the volume of a sphere.
Also please don't mind my grammar errors as English is not my first language. Thank you !
r = float(input("choose a number :"))
def volume_sphere(cube(r)):
pi = 3.14
cube = int(r**3)
return(cube)
volume_sphere = float(4/3*pi*cube(r))
return(volume_sphere)
volume_sphere(r)
#volume_sphere = volume_sphere(cube(r))
Is this possible to do ? This is how I understand the relationship between both functions
print("the volume of the sphere is : , volume_sphere(r)")

You would define two separate functions, and then one function can call the other. In this case volume_sphere can call cube.
import math
def cube(x):
return x**3
def volume_sphere(r):
return math.pi * cube(r)
Then you would just call this like
radius = float(input("choose a number :"))
volume = volume_sphere(radius)
print("the volume of the sphere is : {}".format(volume))
Note that you are free to define a function within another function.
def volume_sphere(r):
def cube(x):
return x**3
return math.pi * cube(r)
In this particular case I don't see a strong reason to do so. These are typically used for closures or wrappers.

Related

Beginner Python surface calculation of a hut

I'm trying to make a program to calculate the surface area of ​​a shack with a pitched roof. I've only been in this class for 2 weeks and I'm a bit overwhelmed. The program should ask the user via console for the values ​​and then calculate the values ​​using the definition.
I'm not asking for the entire code at all. But I don't understand how I can calculate inputs using a definition and then print them. this is my code so far:
import math
def floorspace(a,b):
G = 0
G = a*b
return (G)
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace, G)
You don't need to import math as basic multiplication is already included. You also don't need to initialize a variable before you assign it so I removed the
G = 0
G = a*b
lines and replaced it with a simple
return a*b
You don't need brackets around a return statement, just a print statement.
The final two issues are that you're printing incorrectly and you used the wrong function parameters. You would need to pass in the same number of parameters that are in the function declaration (so in this case, 2). Pass in a and b from the user inputs into your floorspace() function and then call print(). The code should work now!
def floorspace(a,b):
return a*b
#main program
a = int(input("enter the length of the floor!"))
b = int(input("Enter the width of the floor!"))
print(floorspace(a,b))
in your code print(floorspace,G) G is not defined you must write your it like this print(floorspace(a,b))

How to create and call on a Python Class to calculate Kelly Criterion formula for sports betting?

I am trying to create a Python Class to calculate the Kelly Criterion formula in order to determine the precise bet size for an individual sport's investment. I am not very good with using the Class function or init function and could use some help.
The Class I am trying to create uses three functions:
Function 1 asks the user to input the estimated win percentage of the bet (saved to variable 'winP').
Function 2 asks the user to input the American odds for this particular bet. I then convert the American odds to Decimal odds to use with the Kelly Criterion formula (saved to variable 'odds').
Function 3 takes 'winP' and 'odds' and implements this data into the Kelly Criterion formula.
The Kelly Criterion formula that I am using is:
Kelly Criterion (kCrit) = ((odds - 1) * (1 - winP)) / (odds - 1)
'odds' is the Decimal form of the American odds after conversion. 'winP' in the expected winning probability of this particular bet.
I was able to get the 1st and 2nd function to work perfectly (win_percentage, convert_to_decimal), however I was unable to get the 3rd function to work (implement_kc)
Here is my code below:
class KellyCriterion:
def win_percentage(percent):
winP = int(input('What is your win percentage?: '))
return winP
def convert_to_decimal(odds):
odds = int(input('What are the American odds?: '))
if odds > 0:
odds = (odds/100) + 1
return odds
elif odds < 0:
odds = -(100/odds) + 1
return odds
def implement_kc(winP, odds):
kCrit = ((odds - 1) * (1-winP)) / (odds-1)
return kCrit
winPercent = KellyCriterion()
winPercent.win_percentage()
betSize = KellyCriterion()
betSize.convert_to_decimals()
I was not sure how to call on the 3rd function properly:
kelly = KellyCriterion()
kelly.implement_kc()
I received an error: NameError: name 'winP' is not defined.
I am a beginner with using Class functions and could use some help. I also tried using an init(self) function but not exactly sure how those work.
Any suggestions would be greatly appreciated. Thanks in advance for any help that you may offer.
Just to clarify the 1st function (win_percentage) and 2nd function (convert_to_decimal) work just fine. I am having issues with the 3rd function (implement_kc).
I would like to find a way to call on the KellyCriterion Class to: 1) ask the user what is their win percentage; 2) ask the user what are the American odds; 3) implement both of their responses into the Kelly Criterion formula to find out the appropriate bet size.
Thanks again!
If you want to write a class, you need to pass self to the functions. Moreover, the way you have winPercent = KellyCriterion() and betSize = KellyCriterion() means you have two separate instances of the KellyCriterion class, which don't communicate with one another. What you want, is a single instance so you can assign both winP and odds to that instance, otherwise any call to the implement_kc() method is going to be missing values and return an error.
As an aside, here's a post that shows a class-based implementation of the Kelly Criterion and some more background on how it's done. Could be helpful for reference.
Anyway, here's some code that will work, at least if I understand what you're trying to accomplish:
class KellyCriterion:
def win_percentage(self):
winP = int(input('What is your win percentage?: '))
self.winP = winP / 100
def convert_to_decimal(self):
odds = int(input('What are the American odds?: '))
if odds > 0:
self.odds = (odds/100) + 1
elif odds < 0:
self.odds = -(100/odds) + 1
def implement_kc(self):
kCrit = ((self.odds - 1) * (1-self.winP)) / (self.odds-1)
return kCrit
If we run it:
KC = KellyCriterion()
KC.win_percentage()
KC.convert_to_decimal()
print(f"Wager: {KC.implement_kc():.2f}%")
If we enter, say 51 and -110 when prompted for input, then we get:
Wager: 0.49%
Now each of the input functions you defined assign an attribute to the class (e.g. self.winP and self.odds) that the implement_kc() method will use later when you call it.

when i run my code, why does the ellipse/circle not show up

from math import sin
from processing import *
X = 30
Y = 30
delay = 16
radius = 30
def setup():
strokeWeight(10)
frameRate(20)
size(500,500)
def sircle():
global X, Y, radius
background(100)
fill(0,121,184)
stroke(255)
fc = environment.frameCount
X += (mouse.x-X)/delay;
Y += (mouse.y-Y)/delay;
radius = radius + sin(fc / 4)
draw = sircle
run()
for some reason run() only creates the background.
does anybody know how to call the function for sircle()?
I think the OP is referring this code
where it does seem correct that draw is being assigned the function variable sircle. Besides, its not like sircle() is returning anything that can be assigned to draw
Looking at the example code in the link I shared above, you need a line like
ellipse(X,Y,radius,radius)
at the end of your sircle function
You need to run sircle() and setup() with parentheses.
These are functions not variables, they demand their parentheses. In your code draw variable stores the memory address of sircle() function.

Calculating right triangle using random points in Python

I am trying to create right triangles using random coordinates in turtle. Sometimes my code works, while other times the hypotenuse of my triangle goes in the wrong direction. I have spent hours trying to figure out what it causing the inconsistency.
There are several shapes within the code. However, only the RightTriangle class is giving me issues so I have removed the others.
If anyone is able to figure out how I can resolve the issues I am having I would be extremely grateful.
from turtle import Turtle
import random
from math import sqrt, degrees, asin, acos, atan
class Shape():
turtle = Turtle()
class RightTriangle(Shape):
def __init__(self, A, B):
self.A = A
self.B = B
def draw(self):
a = (self.B[0] - (self.A[0]))
b = (self.B[1] - (self.A[1]))
c = (sqrt((self.B[0] - self.A[0])**2 + (self.B[1] - self.A[1])**2))
angleA = degrees(atan(a/b))
angleB = degrees(atan(b/a))
Shape.turtle.penup()
Shape.turtle.setposition(self.A)
Shape.turtle.pendown()
Shape.turtle.forward(a)
Shape.turtle.right(90)
Shape.turtle.forward(b)
Shape.turtle.right(180-angleA)
Shape.turtle.forward(c)
Shape.turtle.penup()
def random_shapes(count):
def random_point():
return (random.randint(-200,200), random.randint(-200,200))
shapes = []
for i in range(1, count+1):
shapes += [RightTriangle(random_point(), random_point())]
return shapes
def main():
shapes = random_shapes(15)
for s in shapes:
s.draw()
input ('Hit <enter> key to end.')
input ('Have a nice day!')
main()
With your existing code the lengths of the edges can be negative which changes the meaning of your "forward" movements and "right" turns. Use absolute values when calculating lengths:
a = abs(self.B[0] - (self.A[0]))
b = abs(self.B[1] - (self.A[1]))
Note that c is always positive.
As a side note, you don't need the angleB variable in your code.
You are using a and b to represent dx and dy, and always starting at A. Think about whether it can be right to always do right(90) (hint, it cannot). If B is vertically above A you will go down instead of up (if you adopt the abs mentioned by Selcuk).
One really simply way to do this is to just point back towards point A in the turtle code. You can do this with
Shape.turtle.setheading(Shape.turtle.towards(self.A))
in the place of
Shape.turtle.right(180-angleA)
This is definitely the least truly mathematical way to solve this but it does work quite nicely.

Saving output of a function as a variable and using it in another function

I'm new to programming, so this question might be dumb.
I need to introduce the value of Tr1 into the Bzero1 function. When I run the module I get the result below:
.
The program is not running the Bzero1 function and I'm not sure why. Is it because I am not introducing the Tr1 value correctly or something else? I want Bzero1 to perform the operation 0.083-(0.422/Tr1**1.6), with Tr1 obtained from the result of T/Tc1.
I would appreciate your help a lot.
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
Tc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", Tc1)
def Tr1(T, Tc1):
print("Relative temperature 1: ", T/Tc1)
Tr1 = Tr1(T, Tc1)
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
Do not replace Tr1 function value, to avoid such replacement change:
Tr1_value = Tr1(T, Tc1)
Call Bzero1 function with code:
Bzero1(Tr1_value)
Modify Tr1 to return value:
def Tr1(T, Tc1):
result = T/Tc1
print("Relative temperature 1: ", result)
return result
Also, let me suggest you to take a look on python official tutorial - there you can learn a lot about python ...
Good Luck !
def is only defining a function, not calling it. E.g.
def foo(a):
print a * 2
means there is now a function foo that takes argument a. The a in foo(a) is the name of the variable inside the function.
So in your case
def Bzero1(Tr1):
print("Bzero 1: ", 0.083-(0.422/Tr1**1.6))
defines the function Bzero1 as taking argument Tr1, but doesn't call it. You need to call the function, just like you called Tr1:
Bzero1(Tr1)
You can see that this way it becomes confusing quite quickly on which is a variable outside of your function, and which are variables inside functions. Therefore it is better to use different names for variables in your outer program v.s. those inside functions.
Here are a few more best practices that you might find useful:
It is generally better to first define all functions and then execute the program's main code, as opposed to intermixing function definitions and the main program.
Another best practice is to make functions only calculate output from inputs, and handle output somewhere else. This way you get to reuse your functions in other parts of your program while always keeping control of when and what to output to the user.
Finally, you shouldn't generally reassign names, e.g. Tr1 = Tr1(...) means that Tr1 is now no longer the name of the function but the name of the result returned by Tr1. In short, use different names for different things.
Applying these tips, your code might look as follows:
# function definitions first
def Tr1(vt, vtc1):
return vt/vtc1
def Bzero1(vtr1):
return 0.083-(0.422 / vtr1 ** 1.6)
# get user input
T = float(input("Introduce system temperature in Kelvin: "))
print("System temperature is: ", T)
vTc1 = float(input("Introduce critical temperature of component 1: "))
print("Critical temperature of component 1 is: ", vTc1)
# run calculations
vTr1 = Tr1(T, vTc1)
vBz1 = Bzero1(vTr1)
# print output
print("Relative temperature 1: ", vTr1)
print("Bzero 1: ", vBz1)
Note
Since I don't know the semantic meaning of your variables I have just used small letter v as a prefix - in general it is better to use meaningful names like temperature or temp1 and temp2 etc. Programs are not math papers.

Categories