0

How to handle input() within functions in Python

I have the following code snippet: while True: print("Enter 'a' to add two numbers") ... user_input = raw_input('Users Choice: ') #I'm using py2 so raw_input works here def getNumbers(): print('Enter first number') num1 = input() print('Enter second number') num2 = input() ... if user_input == 'a': getNumbers() num3 = str(num1 + num2) print('The answer is: ' + num3 + '\n\n') The function is meant to take in an input from the user then the following code is meant to combine num1 and num2 into a solution. Anybody know what I did wrong? (Also if your looking for the rest of the code, it's just a simple calculator. I'm worried about functions that can handle input and if that's even possible)

12th Jun 2019, 12:37 PM
Evan Martine
14 Antworten
+ 2
I was trying to make the function do too much, I changed the code to: print('Enter first number and press \'enter\' key') print('Enter second number and press \'enter\' key') def getNumbers(num1, num2): print(str(num1 + num2)) getNumbers(int(input()),int(input()))
12th Jun 2019, 1:27 PM
Evan Martine
+ 2
~ swim ~ That's what I was looking for, Thanks
12th Jun 2019, 1:46 PM
Evan Martine
+ 1
- swim -, I realized that the function was trying to do too many different things, If I wanted this to work as intended I would have to use the print statements outside of the function. Even then I would get something like: Enter your first number: Enter your second number: 3 4 Answer: 7 #The calculation happens outside of the function and im looking for something like: Enter your first number: 3 Enter your second number: 4 Answer: 7
12th Jun 2019, 1:15 PM
Evan Martine
+ 1
~ swim ~ Mostly, I dont think its possible to get what I described above without excessive code. Im trying to nail down what I can and cant do with functions and I didnt see any documentation on input being handled the way I described. Thanks for the support!
12th Jun 2019, 1:34 PM
Evan Martine
0
@Pulkit Kamboj - While that would prevent the use of other datatypes other than int, That wasnt the solution. @- swim - - Ive updated the title and the code so that you have access to the basics
12th Jun 2019, 12:52 PM
Evan Martine
0
Evan Martine can you please give the whole code
12th Jun 2019, 12:54 PM
Pulkit Kamboj
Pulkit Kamboj - avatar
0
Im using python 2.7 @- swim -
12th Jun 2019, 12:57 PM
Evan Martine
- 1
Use num1=int(input()) Same for num2
12th Jun 2019, 12:43 PM
Pulkit Kamboj
Pulkit Kamboj - avatar