Function Help Python 3.4 - python-3.x

def areaOfRectangle (length,width):
area = length*width
sqArea = length**2
return area,sqArea
def areaOfSquare (length,):
areaOfRectangle (length,width)
return sqArea
#def radiusOfCircle (radius):
area = 3.14*(radius**2)
return area
#def volumeOfCylinder (radius,height):
volume = 3.14*(radius**2)*height
return volume
length = int(input("Input length: "))
width = int(input("Input width: "))
print()
print(areaOfRectangle (10,20))
print()
print(areaOfRectangle (24.3,6))
print()
print(areaOfRectangle (34.9,17.4))
print()
print(areaOfRectangle (length,width))
print()
print(areaOfSquare (10.3))
I need to make two functions, the first function to calculate the area of a rectangle given the length and width. The second function needs to calculate the area of a square given the length of one of its sides. The second function should call the previous function to perform the calculation. I know how to call a function within another function however I don't know how to bring a variable from the first function to the second.

I don't know how to bring a variable from the first function to the second
Typically, this is done through the use of parameters. Let's say you have a value x:
x = 0
You can pass the value to a function by inserting it into the call itself:
f(x)
Lastly, the function needs to be able to handle the parameter you give it:
def f(y): pass
A working example of what you describe:
def f2(y):
return y + 1
def f1():
x = 2
print(f2(x))
f1()
3 is printed.

Related

myNames gets the list but when trying to get the average, an error saying object is not iterable in the for loop when trying to get the average

def myNames():
b = []
while True:
a = input("whats the name: ")
if a != "done":
b.append(a)
elif a == "done":
break
return b
x = myNames()
print (x)
def getAverageLength(myNames):
total = 0
for i in myNames: #This line of code gives me an error and I cant figure it out
total = total + len(i)
average = float(total) / float(len(myNames))
return average
getAverageLength(myNames)
It takes my first function (myNames) as an argument. Ive been trying to figure this error out but have no idea what to do here
Your last line: getAverageLength(myNames), like you said in your description, is using myNames as a parameter which is only present as a function in the current scope.
This means when you reach your for loop, you end up trying to iterate over a function, since that is what was passed into getAverageLength
Maybe you meant getAverageLength(x)?
Or perhaps getAverageLength(myNames()) since myNames() passes the result of the function as opposed to the function itself.
To correctly calculate the average length of the strings, you could use the following:
averageLength = sum(map(len, x)) / len(x)

Need help writing a function which returns a dictionary with the keys as recursive digit sums

So I have written a function which calculates the sum of the digits when a number is input to the function. Now I am trying to write another function which would return a dictionary with the values from my digitsum function as the keys and the values would be how many times the count of that specific digitsum has occurred. Any ideas on how to go about writing the second function?
def digitsum(x):
if x < 10:
return x
else:
return (x%10) + digitsum(x//10)
def digitsumdictionary(lnum=0, hnum=100):
L =[digitsum(num) for num in range(100)]
counter = Counter(L).items()
return counter
Digitsum function is called depending on the length of the number.
You can simply find it by using len(list(str(num))). But if you want to count as the function calls itself, Then try this,
def digitsum(x, count=1):
if x < 10:
return { x : count }
else:
return {(x%10) + int(list(digitsum(x//10 , count+1).keys())[0]) : int(list(digitsum(x//10 , count+1).values())[0])}
Setting the count to 1 or 0 initially, includes or excludes the first call respectively.
The below code returns a list of dictionaries of the desired output.
[digitsum(i) for i in range(10)]

Function does not give desired result

I am trying to define a function for Fibonacci series but the code is not working. I can't resolve the issues and need help to fix the problem. Whenever I am trying to call this function, last value of the series comes always greater than n, which I don't want
def fib(n):
Series = [0,1]
if n>1:
while Series[-1]<=n:
c=Series[-2]+Series[-1]
Series.append(c)
if Series[-1]>n:
break
return Series
Your code is really good, just the indentation of the return is wrong. Just align it properly.
def fib(n):
Series = [0,1]
if n>1:
while Series[-1]<=n:
c=Series[-2]+Series[-1]
Series.append(c)
return Series
do you need something like this:
def fibo(n):
l = [0,1]
for i in range(2,n+1):
l += [l[i-1] + l[i-2]]
return l
If you want to get the Fibonacci sequence up to n:
def fib(n):
series = [0,1]
if n > 1:
c = 1
while c <= n:
series.append(c)
c = series[-2] + series[-1]
return series

how to print the median of a list in python

I've written code to find the median of a list but I'm unsure how to display it when I run the code.
I've tried the print function but I'm not sure what to print.
My code is:
wages = [1,2,3]
def median(wages):
sorted_list = sorted(wages)
length = len(sorted_list)
center = length // 2
if length == 1:
return sorted_list[0]
elif length % 2 == 0:
return sum(sorted_list[center - 1: center + 1]) / 2.0
else:
return sorted_list[center]
Any help would be appreciated.
You can just call your function in the print statement:
print(median(wages))
or
print(median([1,2,3])
You might be confused because you labelled wages as the array and put it in the definition of your function, but there is no connection between the two wages in your code. The line
wages = [1,2,3]
creates a variables called wages but it doesn't impact the wages in the line:
def median(wages):
or inside your function definition. To read more have a look into variable scopes in python.
For example, you could call your function on any array such as,
test_array = [1,2,3,4]
print(median(test_array))
You can just print the return value of your median method.
def median():
your code here
print(median())
PS : There are some indentation errors in your code.

Problem with calling a variable from one function into another

I am trying to call a variable from one function into another by using the command return, without success. This is the example code I have:
def G():
x = 2
y = 3
g = x*y
return g
def H():
r = 2*G(g)
print(r)
return r
H()
When I run the code i receive the following error NameError: name 'g' is not defined
Thanks in advance!
Your function def G(): returns a variable. Therefore, when you call it, you assign a new variable for the returned variable.
Therefore you could use the following code:
def H():
G = G()
r = 2*G
print (r)
You don't need to give this statement:
return r
While you've accepted the answer above, I'd like to take the time to help you learn and clean up your code.
NameError: name 'g' is not defined
You're getting this error because g is a local variable of the function G()
Clean Version:
def multiple_two_numbers():
"""
Multiplies two numbers
Args:
none
Returns:
product : the result of multiplying two numbers
"""
x = 2
y = 3
product = x*y
return product
def main():
result = multiple_two_numbers()
answer = 2 * result
print(answer)
if __name__ == "__main__":
# execute only if run as a script
main()
Problems with your code:
Have clear variable and method names. g and G can be quiet confusing to the reader.
Your not using the if __name__ == "__main__":
Your return in H() unnecessary as well as the H() function.
Use docstrings to help make your code more readable.
Questions from the comments:
I have one question what if I had two or more variables in the first
function but I only want to call one of them
Your function can have as many variables as you want. If you want to return more than one variable you can use a dictionary(key,value) List, or Tuple. It all depends on your requirements.
Is it necessary to give different names, a and b, to the new
variables or can I use the same x and g?
Absolutely! Declaring another variable called x or y will cause the previous declaration to be overwritten. This could make it hard to debug and you and readers of your code will be frustrated.

Resources