skip to Main Content

My Python program is supposed to wait for input from the user, but instead, it proceeds to take input from the next line of code automatically
my code is

num1 = input()
num2 = input()
print(num1 + num2)

In terminal

num1 = input()
num2 = input()
>>> print(num1 + num2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'num2' is not defined. Did you mean: 'num1'?'

enter image description here

how to resolve this issue.

2

Answers


  1. As you learn to develop Python programs, you will realize that the language relies heavily on structure and formatting of the lines of code, which in doing a quick cursive review seems to indicate it would probably be very beneficial for you to search out and review some fundamental Python tutorials to see some of the formatting standards, such as when and where to place lines of code on separate lines.

    In testing out your initial code as such:

    num1 = input() num2 = input()
    
    print(num1 + num2)
    

    resulted in a syntax error at the terminal.

    craig@Vera:~/Python_Programs/Gimme$ python3 Gimme.py 
      File "/home/craig/Python_Programs/Gimme/Gimme.py", line 1
        num1 = input() num2 = input()
                       ^^^^
    SyntaxError: invalid syntax
    

    That is, the language was complaining that it did not know how to handle the two prompts on the same line.

    Doing a really simple bit of refactoring by placing the input prompts on separate lines did provide for the entry of two values.

    num1 = input() 
    num2 = input()
    
    print(num1 + num2)
    
    craig@Vera:~/Python_Programs/Gimme$ python3 Gimme.py 
    33
    145
    33145
    

    So to reiterate, the main takeaway would be to hunt out and review Python tutorial literature, either in a manual and/or online.

    Login or Signup to reply.
  2. Use int for number.

    Snippet"

    num1 = input()
    num2 = input()
    print(int(num1) + int(num2))
    

    Output:

    5
    6
    11
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search