How do I call back a function in this code? - python

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)

Related

How can I get my min and max function to print my error message properly?

This is the prompt we were given to find the function needed:
A function that prompts the user for the minimum value and returns it
to the calling statement. Function to also deal with range checking to
make sure that the minimum value provided is greater than 0
Here's my code below however it doesn't print out the error message when I enter a minimum value higher than the maximum value.
def get_min():
return int(input("What's your minimum value?"))
def min_Check(get_min):
if (get_min >= 0):
return print("ERROR. Minimum should be greater than 0")
else:
return get_min
def get_max():
return int(input("What's your maximun value?"))
def max_Check(get_min):
if (get_max <= get_min):
return print(f"ERROR. Maximum value must be greater {min}")
else:
return max
min_value = get_min()
max_value = get_max()
get_check1 = min_Check(get_min)
get_check2 = max_Check(get_min)
note the difference :
1- you make a wrong condition in min_check function
2- you don't use () when you use the output of the two get function in conditions
def get_min():
return int(input("What's your minimum value?"))
def min_Check(get_min):
if (get_min() <= 0):
return print("ERROR. Minimum should be greater than 0")
else:
return get_min
def get_max():
return int(input("What's your maximun value?"))
def max_Check(get_min):
if (get_max() <= get_min()):
return print(f"ERROR. Maximum value must be greater {min}")
else:
return max
min_Check(get_min)
max_Check(get_min)
There are a couple of things in your code that need fixing:
Both max_Check and min_Check have the else statement outside the
function, I don't know if this was a copy paste error but you need
to fix that.
You never pass get_max as an argument for max_Check so it will never
do the if correctly because it is missing an argument. You should
have gotten an error for that.

Python code doesn't print anything, just gives code 0

so I'm very noobish, I got this python code that I found somewhere in my folders, because I started learning python a while ago, and I need this code for class today. Thing is, it doesn't print anything, it just indicates that there's no problem with it. Can you help me? I need to sc the code and sc the output, if you can guide me to what line of code im missing or anything really.. thanks
def square(n):
word = int(raw_input('Enter number here: '))
if len(word) > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
First of all, using Python 3, you need to replace raw_input with input. Secondly and most importantly, integer does not work with len function and you should compare your integer directly. To handle potential type mismatch, use following code (you can put it in a loop or do any other modifications)
def square():
n = input('Enter number here: ')
try:
n = int(n)
except TypeError:
print("Input is not a number")
else:
if word > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))
# Let's call the function
square()
By the way, I think calling integer variable word is not very self-descriptive.
I think this will work:
def square(n):
number = int(input('Enter number here: '))
if number > 0:
squared = n ** 2
print ("%d squared is %d" %(n,squared))

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.

Does While loop ends when the program return value?

I am a new learner for Python. I have a question about while loop.
I wrote a program below to look for square roots.
When I input anything but integers, the message "is not an integer" shows up and it repeats itself until I input correct data(integers).
My question is, why does it end loop when it return value on line 5, return(int(val))?
Thank you for your attention.
def readInt():
while True:
val = input('Enter an integer: ')
try:
return(int(val))
except ValueError:
print(val, "is not an integer")
g = readInt()
print("The square of the number you entered is", g**2)
To answer your original question, 'return' effectively exits the loop and provide the result that follows the 'return' statement, but you have to explicity print it like so:
def read_int(num1, num2):
while True:
return num1 + num2
print(read_int(12, 15))
If you simply put 'read_int(12, 14)' instead of 'print(read_int(12, 15))' in this scenario, you won't print anything but you will exit the loop.
If you allow me, here are some modifications to your original code:
def read_int(): # functions must be lowercase (Python convention)
while True:
val = input('Enter an integer: ')
try:
val = int(val) # converts the value entered to an integer
minimum_value = 0 # There is no need to evaluate a negative number as it will be positive anyway
maximum_value = 1000000 # Also, a number above 1 million would be pretty big
if minimum_value <= val <= maximum_value:
result = val ** 2
print(f'The square of the number you entered is {result}.')
# This print statement is equivalent to the following:
# print('The square of the number you entered is {}.'.format(result))
break # exits the loop: else you input an integer forever.
else:
print(f'Value must be between {minimum_value} and {maximum_value}.')
except ValueError: # If input is not an integer, print this message and go back to the beginning of the loop.
print(val, 'is not an integer.')
# There must be 2 blank lines before and after a function block
read_int()
With the final 'print' that you actually have at the end of your code, entering a string of text in the program generates an error. Now it doesn't ;). Hope this is useful in some way. Have a great day!

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