returning two integers using functions in python - python

Still new to python and this problem is driving me crazy I know I'm missing something really obvious but I just can't figure it out :/ Here is the problem:
Write a function called main that prompts/asks the user to enter two integer values.
Write a value returning function named max that accepts two integer values as arguments and returns the value that is the greater of the two. For example, if 30 and 25 are passed as arguments to the function, the function should return 30.
Call the max function in the main function
The main function should display the value that is the greater of the two.
This is my code, unsure of where I went wrong
def main():
num1 = int(input('Enter the first number'))
num2 = int(input('Enter the second number'))
return num1, num2
max(n1, n2)
print(max)
def max(n1, n2):
return max
main()

When you call a the max function you need to read the returned value. What you're printing at the end of main is the max function itself. The issue would be clearer if you renamed the max function "getMax".
A second issue is that no code is executed after return in a function. So the main function stops on the fourth line when it returns num1 and num2.

You've got a lot of it there. Here's how to pull it all together:
def get_max(n1, n2):
return n1 if n1 > n2 else n2
def main():
num1 = int(input('Enter the first number> '))
num2 = int(input('Enter the second number> '))
print(f"The maximum of {num1} and {num2} is {get_max(num1, num2)}")
main()
Result:
Enter the first number> 345
Enter the second number> 333
The maximum of 345 and 333 is 345
I know the instructions say to create a function named max, but that's the name of a very commonly used function in the standard Python library. It's best that you avoid redefining built in functions by reusing their names.

Here's what you want:
def main():
num1 = int(input('Enter the first number: '))
num2 = int(input('Enter the second number: '))
result = max(num1, num2)
print(result)
def max(n1, n2):
if n1 > n2:
return n1
else:
return n2
main()
If you want to use the built-in max() function under the function you created, rename your function to something different to avoid a recursion error.

Related

How do I access the value of a variable in one function without calling the entire function in Python [duplicate]

This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed last month.
The issue I'm having is that in one of my functions ( function range_and_number() ), I'm asking the user for input, and I'm saving this input in a variable called max number. Next I checked to make sure that this value only has numbers in it, and if it does I break the loop.
def range_and_number():
while True:
max_number = input("Max Number Possible (No Decimals): ")
if max_number.isnumeric() == True:
print("Your Good")
max_number = int(max_number)
break
else:
print("Please Re-Type Your Maximum Number: ")
return max_number
def get_length():
lives = len(range_and_number)
return lives
def main():
s = get_length()
print(f"================= {s} =================")
Issue: I want to access the value of max number in another function ( function get_length() ) because in this function, I want to measure the length of characters in the variable 'max number'.
The error I'm getting is:
lives = len(range_and_number)
TypeError: object of type 'function' has no len()
I understand why I'm getting the error, but how do I get around it. How do I access the value stored in max_number without calling the function itself.
P.S. If you have the time, please post as many possible solutions please. Thanks in advance
(What I tried)
I tried using a Global Variable and created it at the top of my function
I named the Global Variable TE
Then, I did TE = max_number
After, I tried accessing TE in the second function, but it didn't work
You need to put () after a function name to call it.
You can't get the length of an integer, so you need to convert it to a string in order to call len().
def get_length():
lives = len(str(range_and_number()))
return lives
Issue: I want to access the value of max number in another function ( function get_length() ) because in this function, I want to measure the length of characters in the variable 'max number'.
I tried using a Global Variable and created it at the top of my function
Don't use a global variable. Use a variable in function main.
def range_and_number():
while True:
max_number_as_string = input("Max Number Possible (No Decimals): ")
try:
max_number = int(max_number_as_string)
print("You're good.")
return max_number
except ValueError:
print("Please Re-Type Your Maximum Number.")
def get_length(n):
return len(str(n))
def main():
max_number = range_and_number()
lives = get_length(max_number)
print('Lives: {}'.format(lives))
print('Max number: {}'.format(max_number))
if __name__ == '__main__':
main()
Output:
Max Number Possible (No Decimals): hello
Please Re-Type Your Maximum Number.
Max Number Possible (No Decimals): 127.5
Please Re-Type Your Maximum Number.
Max Number Possible (No Decimals): 127
You're good.
Lives: 3
Max number: 127
You have to call the function and convert it to string:
s = range_and_number().__str__().__len__()
or print the len(max_number) before converting it to int
or you could use logarithm to calculate the length after converting it to intdough it would be unnecessary and inefficient when you already have the length of string.
Fancy way of doing it:
Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))
range_and_number = lambda f: lambda s: (s.__len__() if (s:=input(s)) and s.isnumeric() else f("Please Re-Type Your Maximum Number: \n"))
print("================= %d ================="%Y(range_and_number)('Max Number Possible (No Decimals): \n'))
The function get_length should call the function range_and_number. Your code should be something like this.
def range_and_number():
while True:
max_number = input("Max Number Possible (No Decimals): ")
if max_number.isnumeric() == True:
print("Your Good")
max_number = int(max_number)
break
else:
print("Please Re-Type Your Maximum Number: ")
return max_number
def get_length():
lives = len(str(range_and_number()))
return lives
def main():
s = get_length()
print(f"================= {s} =================")

Passing a Value through a function

I am upskilling a bit with my Python and have a passing values question (Got the task off an online python task website).
Call 'UserInput' twice and assign it to two different variables.
Pass the results of this to the Adder function.
Output the result of the Adder function as part of a sentence.
I am unsure about running the same function twice and setting them as separate variables, and running it in main.
This is mine so far:
def Adder(n1,n2):
ans = n1+n2
#print(ans)
print(n1)
def userinput():
try:
n1 = int(input("Please enter an integer!: "))
except:
print("that is not an integer try again!")
else:
print("thank you for this integer")
print(n1)
return(n1)
def main():
userinput()
Adder(n1,n2)
main();
Expecting two numbers in the main and then pass them to "Adder"

Python Basic Input Confusion

So I am trying to teach myself python and I am having some problems accomplishing this task. I am trying to read in two integers from the keyboard, but the problem is that they can either be read in on the same line or on two different lines.
Example Inputs:
23 45
or
23
45
Each number should go to its own variable.
Im pretty sure I should make use of the strip/split functions, but what else am I missing? I just really dont know how to go about this... Thanks.
Here is what Im working with, but obviously this version takes the numbers one on each line.
def main():
num1 = int(input())
num2 = int(input())
numSum = num1 + num2
numProduct = num1 * num2
print("sum = ",numSum)
print("product = ",numProduct)
main()
the input terminates on new line (more percisely, the sys.stdin flushes on new line), so you get the entire line. To split it use:
inputs = input("Enter something").split() # read input and split it
print inputs
applying to your code, it would look like this:
# helper function to keep the code DRY
def get_numbers(message):
try:
# this is called list comprehension
return [int(x) for x in input(message).split()]
except:
# input can produce errors such as casting non-ints
print("Error while reading numbers")
return []
def main():
# 1: create the list - wait for at least two numbers
nums = []
while len(nums) < 2:
nums.extend(get_numbers("Enter numbers please: "))
# only keep two first numbers, this is called slicing
nums = nums[:2]
# summarize using the built-in standard 'sum' function
numSum = sum(nums)
numProduct = nums[0] * nums[1]
print("sum = ",numSum)
print("product = ",numProduct)
main()
Notes on what's used here:
You can use list comprehension to construct lists from iterable objects.
You can use sum from the standard library functions to summarize lists.
You can slice lists if you only want a part of the list.
Here I have modified your code.
def main():
num1 = int(input("Enter first number : "))
num2 = int(input("\nEnter second number : "))
if(num1<=0 or num2<=0):
print("Enter valid number")
else:
numSum = num1 + num2
numProduct = num1 * num2
print("sum of the given numbers is = ",numSum)
print("product of the given numbers is = ",numProduct)
main()
If you enter invalid number it prints message Enter valid number.

How to add a set of numbers that the user inputted in Python?

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])

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