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
Related
def calculation(numbers):
for i in range(1,11):
maths = i * numbers
result = print(f"{numbers} x {i} = {maths}")
return result
user_input = int(input('enter a number: '))
x = calculation(user_input)
print(x)
So this is a multiplication program using for loop.
when am returning "result" its doing the calculations but after that its returning NONE
why is it doing that? and what is the fix for it?
I tried returning "maths" but its only returning the last iteration I don't want that,
I want to see all the iterations.
The print() should be removed.
I have a task for my Python Course. I have to write a function that calculates the absolute value and returns the absolute value of a number. I was able to get it to work, but it only works when I add the last line, which isn't supposed to be there. I'm not sure how to call the function without that last bit. Any tips?
def absolute(a):
a = float(input('Enter a positive or negative number: '))
if a >= 0:
print ('The absolute value of', a, 'is:', a)
if a < 0:
print('The absolute value of', a, 'is:', a*(-1))
print ( 'The absolute value of 1 is', absolute(1) )
The last line of your code is what's actually calling the function. Without it, you've defined a function but aren't using it anywhere. The last line is what's actually using the function.
EDIT: if you are meant to be returning the value, you should include a return statement at the end of the function. Right now you're just printing a statement, which isn't returning anything.
Here is an updated version of your code:
def absolute():
a = float(input('Enter a positive or negative number: '))
if a >= 0:
return ('The absolute value of', a, 'is:', a)
if a < 0:
return('The absolute value of', a, 'is:', a*(-1))
Output:
Your function is doing unnecessary work by asking for input as well as checking whether it is a positive or negative.
My approach:
def absolute(num):
if num >= 0:
return num
else:
return num * -1
Define another function that will process number provided by the user:
def process_num():
a = int(input('Please enter a number: '))
print(f'The absolute value of {a} is {absolute(a)}')
Then, just call the process_num() to run the function.
Pic:
Your function just prints the value. Return and print are two different things.
And this is how you print the value on both types.
def AbsoluteValue(a):
return abs(a)
def Abs(a):
print(abs(a))
n = float(input())
print(AbsoluteValue(n))
Abs(n)
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
#This part of the code will only get numbers from user
while True:
#Using while True will allow me to loop and renter if user input is wrong. While True will go above Try Catch
try:
# Using try: and except: will allow to end the program without crash however then need to be indented
# Try goes before the def name
def getNumbers():
num1=int(input("Enter 1st number: "))
num2=int(input("Enter 2nd number: "))
getNumbers()
break# the while will stop when both values are numbers
except:
print("Incorrect input detected, try again")
#This part of the code will add the 2 numbers
def addNums():
What do I put here so that I can use num1+num2
addNums()
def subNums():
What do I put here so that I can use num1-num2
addNums()
I wrote a Calculator program but over there I declared those num1 and num2 as global variables in side getNumbers def. Someone mentioned that is not a good/ideal way which is why I wanted to try this approach.
Thanks in advance.
In order to use global variables inside of a function, use the global keyword:
x = 1
y = 2
def add() :
global x, y
return x + y
EDIT
Actually, your "question" is really unclear. You say you are not willing to use global-variables in your code, but you wrote:
def addNums():
What do I put here so that I can use num1+num2
addNums()
The problem is that num1 and num2 don't exist at this place. If you want to use them, then they are global variables.
As far as I understand, what you want is just a function:
def addNums(x, y):
return x+y
addNums(num1, num2)
I don't know what's your doubt, it's not clear in your post.
Why can't you do in this way (just for e.g, you can make it better):--
Blockquote
def subNums(a, b):
return (a - b)
def addNums(a, b):
return (a + b)
def getNumbers():
while True:
try:
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
return (num1, num2)
except:
print("Incorrect input detected, try again")
a, b = getNumbers()
print ("sum of %d and %d : %d" % (a, b, addNums(a, b)))
print ("difference of %d and %d : %d" % (a, b, subNums(a, b)))
Hope this will help.
How do I add numbers in between two numbers the user inputted in Python 2.7. So a person would input 75 and 80 and I want my program to add the numbers in between those two numbers. I am very new to programming and python so any help would be awesome!
This example excludes 75 and 80. If you need to include them replace with print sum(range(n1,n2+1))
n1=input('Enter first number ')
n2=input('Enter second number ')
print sum(range(min(n1,n2)+1,max(n1,n2)))
#DSM is right!
n1=input('Enter first number ')
n2=input('Enter second number ')
print (n2-n1+1)*(n2+n1)/2
to capture user input use number1 = raw_input('Input number'). From there I'm not exactly sure what you mean from adding numbers between the two? If you want 76+77+78+79 in that example
number1 = raw_input('Input number')
number2 = raw_input('Second number')
result = 0
for n in range(int(number1)+1, int(number2)):
result+=n
print result
Here's a quick sample that should handle a few different situations. Didn't go that in-depth since I don't know the scope of the situation. Realistically you should do some form of type-checking and loop until valid input is entered. However this should get you started:
def sumNums(a, b):
total = 0
if a < b:
total = sum(range(a+1, b))
elif b < a:
total = sum(range(b+1, a))
return total
num1 = int(raw_input("First Number: "))
num2 = int(raw_input("Second Number: "))
print sumNums(num1, num2)
However I'm sure there's a more comprehensive way using lists and sum() but it seems like you only need a basic working example.
easy you just go
def add(x,y):
if True:
return add(x, y)
else:
return None
add([1,2,3,4][0], [1,2,3,4][2])