I keep getting "Unresolved Reference" error when, I'm trying to call function
here is code for area of circle
#area of circle
def arc(a,r):
a=3.14 * (radius**2)
return arc
radius=int(input("Enter Radius: "))
area_of_circle=arc(a,r)
print("Area of circle: {}".format(arc))
There are a few errors in here, I'll step through each and explain what's happening.
The first two issues occur in your arc() function. I'll write comments above each offending line:
def arc(a,r):
# What is `radius`? That's not defined in this function!
a=3.14 * (radius**2)
# You're returning a reference to the arc() function from the arc() function?
return arc
The next two issues are in the main area of your program. Again, I'll write comments above the offending lines:
radius=int(input("Enter Radius: "))
# What is `a`? What is `r`? You haven't defined those names!
area_of_circle=arc(a,r)
# `arc` is a function, so what do you expect to happen here?
print("Area of circle: {}".format(arc))
To clean this up, you need to make sure every name references a valid variable, and that you're using functions and variables correctly. In your particular program, functions should be defined and called, not returned from functions or passed around like variables in .format() statements. Variables should be defined and given a valid value.
There are a few other errors that may arise once you clean those issues up, but I'm hoping you'll be able to solve those once you have most of the issues fixed!
Fixed up the variables/names/labels in your code:
# area of circle
def area_of_circle(radius):
area = 3.14 * (radius ** 2)
return area
radius = int(input("Enter Radius: "))
area_of_circle = area_of_circle(radius)
print("Area of circle: {}".format(area_of_circle))
Related
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.
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.
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.
I'm not understanding where I have to use a function and where I don't, for example, I tried to write this for the area of a rectangle and after hours of trying to figure out why I couldn't get it to execute properly I could just get rid of the very first line of code and it worked fine.
def area_rectangle(width,height):
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print area
Thought I had to start it out like I did but it just wasn't working until I deleted the first line.
Functions are a way of compartmentalizing code such that it makes it both easier to read and easier to manage. In this case, there are a few concepts you must understand before implementing functions to solve your problem.
Functions follow the format:
def functionName(): #this defines the function
print("This is inside the function.") #this is code inside the function
functionName() #this calls the function
A few things to note:
code that belongs to the function is indented
in order for the function to execute, it first has to be invoked (i.e. called)
So your function aims to calculate the area of a rectangle using width and height variables. In order for your function to work you would first need to invoke the function itself and then remove the unneeded parameters as you are asking for them as input anyway. This would give you:
def area_rectangle():
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print (area)
area_rectangle()
Another way to go about this would be to make use of parameters. Parameters are values passed to a function by the line of code that invokes them, and they are given within the parentheses:
def functionName (my_param):
print (my_param)
fucntionName (my_param)
Using parameters to solve your problem would look something like this:
def area_rectangle(width, height):
area=width*height
print (area)
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area_rectangle(width, height)
Another side note is on return values. Rather than printing the result of a function within the function itself, you can return it to the line that invoked it and then make use of it outside the function:
def area_rectangle(width, height):
area=width*height
return area
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area = area_rectangle(width, height)
print ("The area is {}".format(area))
Functions are an essential part of Python, and I suggest reading some tutorials on them, as there is many more things you can do with them. Some good ones...
learnpython.org - Functions
tutorialspoint.com - Python Functions
First,
You should indent your code
Second,
Now to get your code working you should call the function area_rectangle()
Corrected Code
def area_rectangle():
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print area
area_rectangle()
Indentation is the key for Python (there are no {} just indentation)
Refer python documentation
You cant executing your function because
You are not invoking (calling) it at the bottom.
def area_rectangle(width,height):
width=int(input("Enter the width of rectangle: "))
height=int(input("Enter the height of rectangle: "))
area=width*height
print area
area_rectangle()
You are passing the required argument "width and height" to the function
"area_rectangle" which is meaningless because you are accepting them from the user
within the function. just call the function to work.
Functions are a group of statements which gives you the answer for your problem statement. In your case if you are writing it as a function then you can resuse this value "area_rectangle" anywhere you want. you don't need to write those lines again.
This is surely a beginner's question, I'm just having trouble searching for it.
What I want to do is calculate points on a circle for thousands of circles which I will later render. Because I will be rendering many thousands of circles a second, I thought I'd try to avoid unncessary overhead. To do this, I've created a function that calculates a number of points (which I want to be variable, a larger circle will need more points calculated) on a unit circle, and another function which can take these points, translate them and then scale by the radius.
My original code ended up something like this:
class Circle():
...
def CalcCircle(segments):
does some stuff to calculate generic coordinates
def CreateCircle(x, y, r, segments):
does some stuff to create a circle using CalcCircle(segments)
Obviously the problem was that even though I might only want to create circles with 20 segments, I was calling the CalcCircle function (and repeating the same calculations) every time I called CreateCircle.
The only way I could figure out how to fix this was:
class Circle():
...
def CalcCircle(segments):
does some stuff to calculate generic coordinates
CreateCircle_has_not_been_run = True
def CreateCircle(x, y, r, segments):
if Circle.TransCircle_has_not_been_run:
generic_circle = Circle.CalcCircle(segments)
Circle.CreateCircle_has_not_been_run = False
does some stuff to create a circle using generic_circle
I've never formally learnt programming so I'm not sure if this is considered good design. Surely it would become messy if every time I wanted to "initialize" data or call a function only on the first run through I had to make a random class variable. The reason I ask is I'm constantly running into this problem, so I assume there must be a standard way of doing it.
Edit: An example of how the call will be made.
#window.event
def on_draw():
window.clear()
width = window.get_size()[0]
height = window.get_size()[1]
radius = int(width/50)
segments = int(radius*1.5)
for i in range(N):
pyglet.gl.glColor3f(0.05,0.2,0.9)
DrawCircle(positions[i][0],positions[i][1],width,segments)
DrawCage(width,height)
DrawLabel(width,height)
etc.
I'm aware that there's problems here but I'm just trying to illustrate the example (positions comes from the update function if anyone is wondering). As I've said earlier, this is a problem I run into all the time.
I could call Circle.CalcCircle() from the on_resize() function as per Achim's suggestion. I have a hard time believing however that standard practice is to stick two random functions into a class (as it stands neither of them necessarily need to even be in the Circle class), one of which is implicitly dependent on the other and both of which are called in different parts of the code.
I would do something like this:
class Circle:
def __init__(self):
self.unit_circle_points = None
def CalcCircle(self, segments):
# Do some stuff to calculate segments,
# assign calculated values to class attribute
self.unit_circle_points = calculated_points
def CreateCircle(self, X, y, r, segments):
# If circle points have not yet been calculated then calculate
# and store, else just load stored points
if self.unit_circle_points is None:
self.CalcCircle(segments)
unit_circle_points = self.unit_circle_points
# Now use unit_circle_points to do some calculations
Every time you instantiate a circle object it will come with an attribute named unit_circle_points that is initialized to None. When you call the CreateCircle method on that object for the first time it will see that the unit_circle_points attribute is None and perform the necessary computations by calling CalcCircle, storing the results. On subsequent calls to the CreateCircle method of this Circle object the unit_circle_points attribute will no longer be None, and the method will simply use the values stored in the attribute.
Edit:
If this requires to much "implicit" behavior for your taste, you can shift things around so that CalcCircle must be called explicitly by the user to generate the pre-calculated data.
class Circle:
def __init__(self):
self.unit_circle_points = None
def CalcCircle(self, segments):
# Do some stuff to calculate segments,
# assign calculated values to class attribute
self.unit_circle_points = calculated_points
return self
def CreateCircle(self, X, y, r):
# If circle points have not yet been calculated then raise an error,
# else load previously calculated points
if self.unit_circle_points is None:
raise Exception("You'd better explicitly call CalcCircle first.")
unit_circle_points = self.unit_circle_points
# Now use unit_circle_points to do some calculations