+ 2

Beginner Python Question

Spam = "7" Spam = Spam + "0" Eggs = int(Spam) + 3 print (float(eggs)) Answer 73.0 I got the answer right in the quiz but I did think the second line would have made a new variable for Spam no? As in - by using the variable as part of the definition it would forget what the variable would be... Does that make sense? Or does it just remember what the last variable of Spam is and then overwrite it once the calculation is done?

7th Jan 2020, 10:12 PM
Andrew Chadwick
Andrew Chadwick - avatar
4 odpowiedzi
+ 8
spam="7" #line -1 spam is a reference variable which is pointing to str type of object "7" spam →7 => spam = spam + "7" # line 2 as we know str is an immutable data type and if we try to change content then compulsary a new object will be created so spam → "70" now spam is pointing to a new object "70" and the previously created object "7" is eligible for garbage collection =>Eggs =int(spam) + 3 Eggs →73 at this line the reference variable Eggs pointing to 73 ( object) =>print(float(Eggs)) =>here again a new object is created that is 73.0 but we only print that object so no reference pointing to this object and in last this object is also eligible for garbage collection
9th Jan 2020, 6:26 PM
Saroj Patel
Saroj Patel - avatar
+ 4
First, the calculation on the right side is done ('7'+'0'), then the result is assigned to the name, which will overwrite the old association.
7th Jan 2020, 10:29 PM
HonFu
HonFu - avatar
0
It stores the last value of variable then execute next operation and got the new value for the variable.
9th Jan 2020, 9:24 AM
Kriti Parashar
- 2
wahh
9th Jan 2020, 5:16 AM
iamghifari
iamghifari - avatar