calling functions in for loop - python [closed] - python

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
i have a lab for my computer science class and i can't seem to get it right.
we're required to import everything from math and to define functions for geometric shapes
ex:
def triangleArea(b,h):
return b * h / 2
for calling it, we need to make a menu to make the user choose what they want for these geometric shapes. for example, if you chose the number 2 and it gives you the volume of a cylinder.
i just can't seem to understand how you call the function inside the while/for loops.
thank uu~!

def find_area(width, height): # define function
return width * height
for i in range(10):
area = find_area(i, 10) #calls function 'find_area()' and saves returned
#value to variable area
print(area) # prints area
count = 0
while count < 10:
area = find_area(i, 10) #calls function 'find_area()' and save returned
#value to variable area
print(area)
count += 1
Example calling function find_area() from within a for-loop and while-loop.

Related

Convert variable contents to string in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
This post was edited and submitted for review last month and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I have a variable which has an equation .I'm trying convert the equation that the varibale has into a string and compute the results
Eg
def func1(x):
y = x + 5
return y, 'x+5'
x as input can vary since I'm iterating
through multiple values
Say
h[0][1] = 5
func1(h[0][1])
Output - 10, "h[0][1]+5"
Required result
I need x+5 as string and the computed result of y as a while calling func1
Eval and exec seemed like a probable solution but they perform the inverse of what is needed
I'm not sure I understand why you'd want this but given that the variable holding the equation would be known when coding, you could just wrap the equation in a function. Eg:
def add_five(x):
return (x + 5, "x + 5")
x = 10
y = add_five(x)
print("Answer is", y[0])
print("Equation is", y[1])

Python index error when trying to make a mean [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm trying to make an average but for some reason when I try to make one it doesn't work.
I have global variables and array defined at the begining of my document :
vent_moyenne_km = []
compteur_moyenne=0
I have one of my function that is called every X time. In that one, I calculate a velocity with some value that are display on a label of my interface. that part is working, but not the mean
global compteur_moyenne
compteur_moyenne += 1
ventkmh = (vent_1[3][0]*256 + vent_1[4][0]) /100 *3.6
label_vent2_2.config(text= "%.2f" % ventkmh)
vent_moyenne_km.append("%.2f" % ventkmh)
vent_1.clear()
if compteur_moyenne == 5:
compteur_moyenne = 0
print(vent_moyenne_km)
label_vent4_2.config(text=statistics.mean(vent_moyenne_km))
vent_moyenne_km.clear()
of course in my imports I have :
import statistics
When I comment the line label_vent4_2.config(text=statistics.mean(vent_moyenne_km)), everything works and I see in the terminal my array with 5 values. I also tried numpy and even tried to make a for items in array: then add then manually, and everytime I get the error : class 'IndexError'
I'm really not sure how to fix that.
For calculating an average of a list just use numpy:
def function():
value = random.randint(0,1)
return value
list = []
for i in range(100):
list.append(function())
if i%5 == 0:
print(np.average(list))

Access the same attribute from different objects in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Suppose I have a class called Cube and I create three objects:
class Cube():
def __init__(self, volume):
self.volume = volume
a = Cube(param_a)
b = Cube(param_b)
c = Cube(param_c)
I was wondering if I can write a function, to which the user can give a format, and the function can apply the format to the objects? For example:
>>> print_all(dummy_cube.volume)
a.volume
b.volume
c.volume
So basically the function contains a loop which will replace dummy_cube to a, b, c.
I know I can use something like getattr(), but it has limits. For example, I hope that the function can print whatever format the user gives:
>>> print_all( (dummy_cube.volume)**2 + 1 )
(a.volume)**2 + 1
(b.volume)**2 + 1
(c.volume)**2 + 1
Is there any good way to do this?
Edit: As the comments pointed out, yes the function can take a list, and I intend it to return the numerical values instead of the format itself.
With a list I can do like:
cube_list = [a, b, c]
for cube in cube_list:
print( (cube.volume)**2 + 1 )
But I am still not sure how I can do it with arbitrary expressions given by the user.
The user can supply a function.
def print_all(f):
for cube in cube_list:
print(f(cube))
import operator
print_all(operator.attrgetter('volume'))
print_all(lambda c: c.volume**2 + 1)

Python Turtle - How do I stop the turtle at a specific distance or coordinate? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This is my attempt to make the turtle stop after traveling nearly 400 pixels.
def race():
while True:
alex.forward(r_alex)
a = a + r_alex
if a > 399.9:
break
And this is what I got back
UnboundLocalError: local variable 'a' referenced before assignment
The line a = a + r_alex uses a before you actually define a.
I'm guessing a is the turtle's displacement so perhaps you should try the following:
def race():
a = 0
while True:
alex.forward(r_alex)
a += r_alex
if a > 399.9:
break
Even better:
def race():
a = 0
while(a > 399.9):
alex.forward(r_alex)
a += r_alex

Variable not defined. How do i define it? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following code:
p=3.14159
#Function to circleArea
def circleArea(A):
A=r*r*p
radius=r
return radius
#Main Program
r=int(input("Enter radius: "))
print("The area of the circle is:" )
print(circleArea(A))
Why does the line beneath yield this error?
print(circleArea(A))
NameError: name 'A' is not defined
It seems you want to return r*r*p from circleArea() function and pass r as an argument. Also, you may want to use math.pi instead of hardcoding it's value:
import math
#Function to circleArea
def circleArea(r):
return r * r * math.pi
#Main Program
r=int(input("Enter radius: "))
print("The area of the circle is:" )
print(circleArea(r))
DEMO:
Enter radius: 10
The area of the circle is:
314.159265359
In your function definition, A is just a local variable inside the function. The variable that you're wanting to pass in is actually called r. So, instead, you want:
print(circleArea(r))
You also want to change your function declaration to:
def circleArea(r):

Categories