1

Why does

import sys

class k:
    x = int(sys.argv[1])
    y = int(sys.argv[2])
    z = 0

def add():
        k.z = k.x + k.y

def main():   
    add()
    print  (k.z)

if __name__ == "__main__" : main()

Give me 10 when I use the number 5 and 5 at command, and

class k:
x = 0
y = 0
z = 0
def add():
    k.z  = k.x + k.y

def main():   
    k.x = input("Enter a number")
    k.y = input("Enter another number")    
    add()
    print  (k.z)

if __name__ == "__main__" : main()

Gives me 55 when I enter 5 and 5 on the prompts.

Thanks in advance.

1
  • 1
    FWIW, in Python, it's usual practice to create an instance of a class & work with that, rather than working directly with the class and manipulating class attributes like your code does. Of course, one wouldn't normally even bother using a class for something simple like this, except as a learning exercise. For further info please see Class Objects in the official Python tutorial. Commented Aug 30, 2015 at 7:56

2 Answers 2

1

In the second example, you forgot yo typecast the input to int, since the input() returns a str object and the + operator concatenates the strings.

def main():   
    k.x = int(input("Enter a number"))
    k.y = int(input("Enter another number"))    
    add()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank your very much! So even if I declare that the values are 'int' originally I have to declare again that the value coming in is an 'int' when I go to the input step?
You don't declare variables in Python. In your code you set them to integers, but they are just names which point to values and the name can be pointed to other values regardless of their type at any time in your code without any warning.
1

Because on your second example, both x and y are strings (so '5'+'5' = '55')

To fix this:

def main():   
    value = input("Enter a number")
    k.x = int(value)

    value = input("Enter another number")
    k.y = int(value) 

    add()
    print  (k.z)

1 Comment

Thanks for your reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.