0

Why is the var type still str in Case 1?. Shouldn't it be int? In Case 2 when I'm not using the function it changes to int.

#CASE 1
num1=str()

def suma():

    num1=int(7)

suma()

print(type(num1)) # <class 'str'>

#CASE 2
num1=str()
num1=7

print(type(num1)) # <class 'int'>
  • 4
    python is dynamically typed, you don't need init a variable type like `num1=str()` or `num1=int(7)`. Instead just do `num1 = 7` or `num1 = 'some string'`. Also your function `suma()` is assigning the variable in a different scope – bherbruck Jun 02 '20 at 01:36

3 Answers3

1

You're not modifying the variable, rather creating a new num1 in the function's namespace. If you want to reference the outer variable you'd need to put global num1 inside of the suma function definition.

>>> num1 = '1'
>>> def suma():
...   num1 = 45345
... 
>>> suma()
>>> num1
'1'
>>> def suma():
...     global num1
...     num1 = 4234
... 
>>> suma()
>>> num1
4234

This answer is the best on SO I've seen around global variables: https://stackoverflow.com/a/423596/5180047

Just realized the comment also answered what I've already said above, whoops! I'll leave this here anyways. Hopefully it's helpful.

Nick Brady
  • 6,084
  • 1
  • 46
  • 71
1

num1 is showing string because it is global variable.

If you want to change the type of num1 from function suma(), then use global keyword as global num1.

# your code goes here
#CASE 1
num1=str()

def suma():
    global num1
    num1=int(7)

    print(type(num1)) #<class 'int'>
suma()

print(type(num1)) # <class 'int'>

#CASE 2
num1=str()
num1=7

print(type(num1)) # <class 'int'>
NAND
  • 663
  • 8
  • 22
Nandan Pandey
  • 148
  • 1
  • 11
0

This is about scoping. Dynamic and static scoping may result different results for the same code. Python is using static scoping. For case 1, you are declaring your variable and calling a method to change its type. Then if the line you are calling num1=str() has a static depth of 0, then the line num1=int(7) has the static depth of 1 since it is called in a subprogram. Then the change in the method suma() can't affect the num1 since it declared on the lower static depth. On your case 2, both of them have the same static depth then num1 will change its type.

NAND
  • 663
  • 8
  • 22
Arif Akkas
  • 54
  • 6