Lowest price ever! Learn Generative AI for 48% less!
Get my discount0
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)
8 Answers
+ 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()))
+ 2
~ swim ~ That's what I was looking for, Thanks
+ 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
+ 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!
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
0
Evan Martine can you please give the whole code
0
Im using python 2.7 @- swim -
- 1
Use num1=int(input())
Same for num2