Computer Science
The id( ) can be used to get the memory address of a variable. Consider the adjacent code and tell if the id( ) functions will return the same value or not(as the value to be printed via print() ) ? Why ?
[There are four print() function statements that are printing id of variable num in the code shown on the right.
num = 13
print( id(num) )
num = num + 3
print( id(num) )
num = num - 3
print( id(num) )
num = "Hello"
print( id(num) )
Python Funda
26 Likes
Answer
num = 13
print( id(num) ) # print 1
num = num + 3
print( id(num) ) # print 2
num = num - 3
print( id(num) ) # print 3
num = "Hello"
print( id(num) ) # print 4
For the print statements commented as print 1 and print 3 above, the id() function will return the same value. For print 2 and print 4, the value returned by id() function will be different.
The reason is that for both print 1 and print 3 statements the value of num is the same which is 13. So id(num) gives the address of the memory location which contains 13 in the front-loaded dataspace.
Answered By
15 Likes
Related Questions
Carefully look at the following code and its execution on Python shell. Why is the last assignment giving error ?
>>> a = 0o12 >>> print(a) 10 >>> b = 0o13 >>> c = 0o78 File "<python-input-41-27fbe2fd265f>", line 1 c = 0o78 ^ SyntaxError : invalid syntax
Predict the output
a, b, c = 2, 3, 4 a, b, c = a*a, a*b, a*c print(a, b, c)
Consider below given two sets of codes, which are nearly identical, along with their execution in Python shell. Notice that first code-fragment after taking input gives error, while second code-fragment does not produce error. Can you tell why ?
(a)
>>> print(num = float(input("value1:")) ) value1:67 TypeError: 'num' is an invalid keyword argument for this function
(b)
>>> print(float(input("valuel:")) ) value1:67 67.0
Predict the output of the following code :
days = int (input ("Input days : ")) * 3600 * 24 hours = int(input("Input hours: ")) * 3600 minutes = int(input("Input minutes: ")) * 60 seconds = int(input("Input seconds: ")) time = days + hours + minutes + seconds print("Total number of seconds", time)
If the input given is in this order : 1, 2, 3, 4