Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 months ago.
The community is reviewing whether to reopen this question as of 5 months ago.
Improve this question
I just want to use input, in a function in python.
this is my code:
print("I can tell you the maximum of 3 numbers")
def max_num(num1, num2, num3, false=None):
num1 = input("enter first number")
num2 = input("enter second number")
num3 = input("enter third number")
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
elif num1.isdigit(False) and num2.isdigit(False) and num3.isdigit(False):
print("no number available")
else:
return num3
return max_num()
but when I run this code, Just first line (print), runs succesfully.
what is wrong?
I would be thankful.
When defining a function with parameters, make sure that these parameters don't come inside the definition of the function.
The code also has some indentation and logical mistakes.
This is a corrected version.
print("I can tell you the maximum of 3 numbers")
num1 = input("Enter the first number:")
num2 = input("Enter the second number:")
num3 = input("Enter the third number:")
def max_num(num1, num2, num3):
if not num1.isdigit() or not num2.isdigit() or not num3.isdigit():
return "Wrong Input"
else:
num1,num2,num3=int(num1),int(num2),int(num3)
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print(max_num(num1,num2,num3))
You need to call that function like print(max_num(num1, num2, num3)), you are still create the function but not calling it.
What does return max_num() even mean? You should return a number, and a number is already returned in all possible branches.
If you want to call this function, try something like print(max_num(1, 2, 3)) at the end of the script.
Also, it is a bit confusing: are you planning to pass in the three numbers by functions arguments or user input? Because you are attempting to do both right now.
Ok, there are lots of issues with this code, but to answer your original question "Why does input never get called?", the answer is simple:
You have defined the function max_num, but you have never called it. Only once a function is called does the code inside run.
So in your script, you simply need to remove all the input parameters in your function definition (as they are never used), and add the line:
max_num()
Then you'll need to fix all the other quirks :)
Happy coding
Related
I am trying to run a function where I can have a user enter three integers run them through a function that will tell which number is largest. I know there is a way to do it through the command line, but I want it to be done through the user I've tried:
num1 = (int(input("Enter 3 numbers and I'll tell you the largest!: ")))
num2 = (int(input("Enter another number: ")))
num3 = (int(input("And one more: ")))
def max_num(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3
print (max_num())
When I run the command I enter three numbers. But I get
< function max_num at 0x00E4D7C0 >
as a result, but I want it to say what the largest number is.
You need to use this line to call the function, with its arguments:
print (max_num(num1, num2, num3))
you printed function as object not called it.
function # as object
function() # as function call
In python everything is an object. So what you have done basically is defined a function def max_num(num1, num2, num3): which takes 3 int arguments.
Now that is just defining a function, When you need to call that function you need to pass exactly 3 int arguments.
What you have done is print(max_num) which will refer to the function object created inside memory and not actually calling a function.
Try to call it with print (max_num(num1, num2, num3)) and It will work.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping on some input concerning the use of 'user inputted' arguments as variable value amounts to be used in a calculation within a function... this will no doubt be a very simple issue but I am new to python and so far my attempts at fixing it have been flawed.
The function is a simple calculation of adding two numbers together solely for the purpose of introducing new students to functions.
I have no issues with the function working as intended when I feed hard coded values as integers into the parameters (which are included in this example code)
but when I try to pass 'user input' argument values in when actually running the program the function simply concatenates the two values rather than adding them, this is (I presume) because the input values are in the format of a 'string'.
I have tried introducing 'int' statements after the 'input' statements within the argument variable code but this results in an error 'invalid literal for int()' I have also tried this at different points of the function code itself with no luck..... so how would I go about making sure the values are recognised as integers before or during calculation? Thanks
def getSum(num1, num2):
calc = num1 + num2
return calc
num1 = input("Type in your first number to add: ")
num2 = input("Type in your second number to add: ")
result1 = getSum(num1, num2)
answer = getSum(10, 5)
answer2 = getSum(155, 56668)
print(answer)
print(answer2)
print(result1)
int() should work correctly if the user only enters integer values - otherwise you have to wrap it with a try and catch block
try:
num1 = int(input("Type in your first number to add: "))
num2 = int(input("Type in your second number to add: "))
catch Exception as ex:
pass //do nothing
Just introduce int() for num1 and num2 in line2.
So the new code will be:
def getSum(num1, num2):
calc = int(num1) + int(num2)
return calc
num1 = input("Type in your first number to add: ")
num2 = input("Type in your second number to add: ")
result1 = getSum(num1, num2)
answer = getSum(10, 5)
answer2 = getSum(155, 56668)
print(answer)
print(answer2)
print(result1)
This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 5 years ago.
I'm practicing Python so I decided to recreate the max() function for 2 numbers. The code doesn't have an error, it just doesn't return anything. Please help! `
def newMax(num1, num2):
if num1 > num2:
return num1
elif num2 > num1:
return num2
elif num1 == num2:
return "They're both equal!"
else:
return "We've run into some sort of error. Make sure you entered 2 numbers."
print("This program will return the largest of 2 numbers you enter.")
number1 = input("Please enter your first number.")
number2 = input("Please enter your second number.")
newMax(number1, number2)
`
Can you not call a function with variables as the parameters, and if not then how would I write this program? FIGURED OUT, I had a print statement error, sorry.
new_max = newMax(number1, number2)
print(new_max)
Try assigning it to a variable and printing that variable.
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 6 years ago.
Ok so I am new to python and trying to learn how to code. I ran into an issue today that I don't understand. So this code executes as expected and prints the largest of the three numbers no matter what position the largest number is.
if num1 >= num2 and num3:
print(num1, 'Is the greatest number!')
elif num2 >= num3 and num1:
print(num2, 'Is the greatest number!')
else:
print(num3, 'Is the greatest number')
But if i change the elif statement to this:
elif num2 >= num1 and num3:
print(num2, 'Is the greatest number!')
Even if num3 is the largest the else statement will not execute and it will display the larger number of num1 or num2.
Your first version works purely by coincidence. You need to do
if num1 >= num2 and num1 >= num3:
print(num1, 'Is the greatest number!')
elif num2 >= num3 and num2 >= num1:
print(num2, 'Is the greatest number!')
else:
print(num3, 'Is the greatest number')
Although, this will still print wrong info if any of the numbers are equal
The problem here is a misunderstanding in the way the keyword and works.
In python, and is used to separate two complete logical statements: cond1 and cond2. It first checks cond1. If cond1 is True, it moves on to check cond2. If cond2 is also True, then the whole statement evaluates to True.
When you do if num1 >= num2 and num3, you are actually asking python if the following is True:
num1 >= num2
num3 exists and is not 0 (since it's a number)
It is not checking if num1 >= num2 and num1 >= num3.
So if num1 = 2, num2 = 1, num3 = 3, your conditional will still return True for if num1 >= num2 and num3.
The same concept applies to your problem conditional.
Okay, so this is a bit confusing to explain.
Basically, I would like 'num1' to generate a random number every time it is called, however when inside the function, I would like the variable to stay the same, in order to give the correct answer.
#finding random numbers to be used in questions
import random
num1 = int(random.randrange(0,101,1))
num2 = int(random.randrange(0,101,1))
#defining a function that asks an addition question, using random numbers
def addition_question(num1,num2):
answer1 = num1 + num2
print("What is",num1,"+",num2,"?")
given1=input()
if given1==answer1:
print("Correct!")
else:
print("Sorry, wrong answer!")
print("Question 1:")
addition_question(num1,num2)
I think at the moment what it is doing is assigning a different value for num1 and num2 each time they are called.
Is there any way to solidify the values of the variables within the functions, while still kepping the value of them outside the function random?
A class would be the best bet here.
class NumberQuestion(object):
def __init__(self):
self.num1 = random.randrange(0,101,1)
self.num2 = random.randrange(0,101,1)
def addition_question(self):
answer1 = self.num1 + self.num2
print("What is %s + %s?" % (self.num1, self.num2))
given1 = input()
if int(given1) == answer1:
print("Correct!")
else:
print("Sorry, wrong answer!")
print("Question 1:")
question = NumberQuestion()
question.addition_question()
You are more than likely comparing an int to a string with if given1 == answer1 so cast the input as an integer, you can also use a while loop to keep asking the user for more guesses until they enter the correct answer.
def addition_question(num1,num2):
answer1 = num1 + num2
print("What is",num1, "+",num2,"?")
while True:
given1 = int(input())
if given1 == answer1:
print("Correct!")
break
else:
print("Sorry, wrong answer, guess again!")
This could be a good chance to use your newly acquired closure skills
def question_generator():
'''returns a function which does the addition stuff'''
num1 = random.randrange(0,101,1)
num2 = random.randrange(0,101,1)
def addition_question():
answer1 = num1 + num2
print("What is",num1,"+",num2,"?")
given1=int(input())
if given1==answer1:
print("Correct!")
else:
print("Sorry, wrong answer!")
return addition_question
new_question = question_generator()
print("Question 1:")
new_question()
Note: every time you call question_generator(), a new function is created, which has new num1 and num2. If you call new_question again, it will contain the same num1 and num2
addition_question here is a closure. it "remembers" the scope in which it was created.
every time we call question_generator, the scope for the returned function contains two freshly created random numbers. The returned function remembers the value of num1 and num2.
You could call question_generator()() to produce a new addition question if you need not save the returned function.