Write this program in python - python

Write a program that contains ADD and AVERAGE user defined functions. On execution your program prompts for three numbers from user and call the AVERAGE function. Send the entered three numbers to AVERAGE function. The AVERAGE function call ADD function and send the three user entered numbers to it. The ADD function accepts the numbers from AVERAGE function and calculate sum. Send this sum value back to calling point (AVERAGE function). The AVERAGE function receive the sum value and calculates average for that sum of three numbers. The AVERAGE function send the average value to its calling point (outside of both functions). At the end display the average value from outside these functions.
The output should be:
a: 2
b: 3
c: 4
Average: 3.0

def add(a,b,c):
return a+b+c
def average(a,b,c):
d = add(a,b,c)
e = d/3
return e
f = average(2,3,3)
print(f)
Output:
f = 2.6666666666666665

Generic way of doing this :
def adder(num):
return sum(num)
def avg(*num):
return adder(num)/len(num)
print("Average: ",avg(1,2,3,4))
Now you can pass as much numbers as you want.

The best practice tactics will solve it, like;
n1 = int(input("Enter Number 1: " ))
n2 = int(input("Enter Number 2: " ))
n3 = int(input("Enter Number 3: " ))
def ADD(a,b,c):
return a+b+c
def AVERAGE(a,b,c):
X = ADD(a,b,c)
Y = X/3
return Y
F = AVERAGE(n1, n2, n3)
print(F)
Good luck!
Regards: Khairullah Hamsafar

Related

Using a function calculate and display the average of all numbers from 1 to the number entered by the user in python

I am gitting stuck here, please help. The code has to promt the user to enter a number, pass the number to a python function and let the function calculate the average of all the numbers from 1 to the number entered by the user.
def SumAverage(n):
sum=0
for idx in range(1,n+1):
average =sum/idx
return average
num =int(input("Enter a number"))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
The sum of the series 1 + 2 + 3 + ... + n where n is the user inputted number is:
n(n+1)/2 (see wikipedia.org/wiki/1+2+3+4+...)
We have that the average of a set S with n elements is the sum of the elements divided by n. This gives (n(n+1)/2)/n, which simplifies to (n+1)/2.
So the implementation of the average for your application is:
def sum_average(n):
return (n + 1) / 2
This has the added benefit of being O(1).
Your version is not working because the average is always set to the last calculation from the for loop. You should be adding the idx for each iteration and then doing the division after the loop has completed. However, all of that is a waste of time because there is already a function that can do this for you.
Use mean from the statistics module.
from statistics import mean
num = int(input("Enter a number"))
result = mean(list(range(1, num+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
If you are determined to do the logic yourself it would be done as below, if we stick with your intended method. #zr0gravity7 has posted a better method.
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
return round(sum / n, 2)
num = int(input("Enter a number"))
result = SumAverage(num)
print(f'The average of all numbers from 1 to {num} is {result}')
I'm not recommending this, but it might be fun to note that if we abuse a walrus (:=), you can do everything except the final print in one line.
from statistics import mean
result = mean(list(range(1, (num := int(input("Enter a number: ")))+1)))
print(f'The average of all numbers from 1 to {num} is {result}')
I went ahead and wrote a longer version than it needs to be, and used some list comprehension that would slow it down only to give some more visibility in what is going on in the logic.
def SumAverage(n):
sum=0
l = [] # initialize an empty list to fill
n = abs(n) # incase someone enters a negative
# lets fill that list
while n >= 1:
l.append(n)
print('added {} to the list'.format(n), 'list is now: ', l)
n = n - 1 # don't forget to subtract 1 or the loop will never end!
# because its enumerate, I like to use both idx and n to indicate that there is an index and a value 'n' at that index
for idx, n in enumerate(l):
sum = sum + n
# printing it so you can see what is going on here
print('length of list: ', len(l))
print('sum: ', sum)
return sum/len(l)
num =int(input("Enter a number: "))
result=SumAverage(num)
print("The average of all numbers from 1 to {} is {}".format(num,result))
Try this:
def SumAverage(n):
sum=0
for i in range(1,n+1):
sum += i
average = sum/n
return average
[its the better plz see this.
(short description):- user enter the list through functions then that list is converted into int. And the average is calculated all is done through functions thanx
]1

New to coding python , need help on why my code isnt working?

def Factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
def Fibonacci(num):
i=0
present=1
previous=0
while i<=num:
nextterm=present+previous
present=previous
previous=nextterm
i=i+1
print("The fibonacci number for", i, 'is', nextterm)
def CallFibOrFac(x):
num = 10
if x == 'Fib':
Fibonacci(num)
if x == 'Fac':
print (Factorial(n))
x = input('enter fibonacci or factorial')
num = input('enter value for fibonacci')
Fibonacci(num)
n = input('enter value for factorial'
print(Factorial(n))
I defined all my functions and wrote an if statement, but when I enter Factorial, when it asks for x=input(‘enter fibonacci or factorial’), it gives me the input to ‘enter value for fibonacci’ when I need the n=input(‘enter value for factorial’) to display when I put in "factorial".
Although you have a function to choose whether to call Fib or Fact, you never call that deciding function. Instead, what I take to be your main program utterly ignores the user's first input and proceeds to call both functions.
Back up a few steps. Learn to recognize the user's input and call -- or do not call -- a single function.

Python- Function that returns a value

Im really struggling with this question, can anyone help me write a code for this program? or at least say where am I going wrong? Ive tried a lot but can't seem to get the desired output.
This is the program description: Python 3 program that contains a function that receives three quiz scores and returns the average of these three scores to the main part of the Python program, where the average score is printed.
The code I've been trying:
def quizscores():
quiz1 = int(input("Enter quiz 1 score: "))
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
average = (quiz1 + quiz2 + quiz3) / 3
print (average)
return "average"
quizscores(quiz1,quiz2,quiz3)
One, you are returning a string, not the variable. Use return average instead of return "average". You also don't need the print() statement in the function... actually print() the function.
If you call a function the way you are doing it, you need to accept parameters and ask for input outside the function to prevent confusion. Use a loop as needed to repeatedly use the function without having to rerun it every time. So the final code would be:
def quiz_average(quiz1, quiz2, quiz3):
average = (quiz1 + quiz2 + quiz3) / 3
return average
quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))
print(quiz_average(quiz1, quiz2, quiz3)) #Yes, variables can match the parameters
You are returning a string instead of the value. Try return average instead of return "average".
There are a few problems with your code:
your function has to accept parameters
you have to return the actual variable, not the name of the variable
you should ask those parameters and print the result outside of the function
Try something like this:
def quizscores(score1, score2, score3): # added parameters
average = (score1 + score2 + score3) / 3
return average # removed "quotes"
quiz1 = int(input("Enter quiz 1 score: ")) # moved to outside of function
quiz2 = int(input("Enter quiz 2 score: "))
quiz3 = int(input("Enter quiz 3 score: "))
print(quizscores(quiz1,quiz2,quiz3)) # print the result
An alternative answer to the already posted solutions could be to have the user input all of their test scores (separated by a comma) and then gets added up and divided by three using the sum method and division sign to get the average.
def main():
quizScores()
'''Method creates a scores array with all three scores separated
by a comma and them uses the sum method to add all them up to get
the total and then divides by 3 to get the average.
The statement is printed (to see the average) and also returned
to prevent a NoneType from occurring'''
def quizScores():
scores = map(int, input("Enter your three quiz scores: ").split(","))
answer = sum(scores) / 3
print (answer)
return answer
if __name__ == "__main__":
main()

Python User Input Average

I'm trying to work on a school assignment that asks the user to input 3 integers, then I need to pass these three integers as parameters to a function named avg that will return the average of these three integers as a float value.
Here's what I've come up with so far, but I get this error:
line 13, in <module>
print (average)
NameError: name 'average' is not defined
Advice?
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
c = float(input("Enter the third number: "))
def avg(a,b,c):
average = (a + b + c)/3.0
return average
print ("The average is: ")
print (average)
avg()
average only exists as a local variable inside the function avg
def avg(a,b,c):
average = (a + b + c)/3.0
return average
answer = avg(a,b,c) # this calls the function and assigns it to answer
print ("The average is: ")
print (answer)
You should print(avg(a,b,c)) because the average variable is only stored in the function and cannot be used outside of it.
You called avg without passing variables to it.
You printed average which is only defined inside the avg function.
You called avg after your print.
Change print (average) to
average = avg(a, b, c);
print(average)

Keep getting syntax error. What do I need to do?

I am trying to get my function to take two arguments, and return their sum. Am I going about this the right way? This is what I have so far:
def my_sum(a, b):
sum = a + b
def main():
a = input(int("enter a number: ", a)
b = input(int("enter a number: ", b)
sum = a + b
return sum
print(" result: ", sum)
main()
So it looks good, but the main problem is that you aren't actually calling your function :) Once you get your two numbers, you can then make the call to your function (which you have properly set up):
def main():
# When you assign variables here, make sure you are putting the int outside
# You also don't need to reference the variable twice
a = int(input("enter a number: "))
b = int(input("enter a number: "))
# Here is where your call goes (try to avoid using variable names that
# are the same as Python keywords, such as sum)
s = my_sum(a, b)
print(" result: ", s)
Now, one other thing you'll have to do is modify your function to return a value. You're already almost there - just add a return (note that since you are just returning the sum of the two numbers, you don't have to assign it to a variable):
def my_sum(a, b):
return a + b
This now means that when you run s = my_sum(a, b), your function will return the sum of those two numbers and put them into s, which you can then print as you are doing.
One other minor thing - when you use the setup you are (with def main(), etc.), you usually want to call it like this:
if __name__ == '__main__':
main()
At this stage, don't worry too much about what it means, but it is a good habit to get into once you start getting into fun stuff like modules, etc. :)
You Have written Wrong coding Style
If you want to do some by using sum method than do this
def my_sum(a, b):
sum = a + b
return sum
def main():
a = int(raw_input("enter a number: "))
b = int(raw_input("enter a number: "))
sum = my_sum(a,b)
print" result: ", sum
main()
I hope this will work as per your requirement.
Regards,
Anil
I am not sure of the purpose of the first function you have defined there (my_sum). However, there are a few things wrong in main as well. The return function always exits the function it is in, and zooms out to a higher level scope. This is very similar to break, except that it returns a value as well. Also, your syntax when you ask for user input is incorrect. It should be:
def main():
a = int(raw_input("Enter a number: "))
b = int(raw_input("Enter a number: "))
return "Result" + (a+b)
main()
Also, if you wanted my_sum to automatically return the sum, you should use return or print:
def my_sum(a, b):
return a + b
doing a print function after return sum won't work because when returning a return value, the execution will exit the scope, the orders should be reversed.
your input function is not implemented correctly.
The correct code should be:
def main():
a = input("enter a number: ")
b = input("enter a number: ")
sum = a + b
print(" result: ", sum)
return sum

Categories

Resources