-3

This is my first day of programming. I bought a course on Udemy and this was on my day 1 practice.

As the title said, I am supposed to switch the value between variables a and b.

the following code was presented and I need to type in the code in between the codes (the area marked "#type here") to accomplish it.

a = input("a= ")
b = input("b= ")
#type here

print("a= " + a)
print("b= " + b)

I typed the following in "#type here" area.

c = a
del a
d = b
del b
a = d
del d
b = c
del c

and submitted the answer like this -

a = input("a= ")
b = input("b= ")

c = a
del a
d = b
del b
a = d
del d
b = c
del c

print("a= " + a)
print("b= " + b)

it worked, but the expected answer was -

c = a
a = b
b = c

...so much better than my code I think?

I think I don't understand how memories work in python. I learned that in python, you don't declare a variable, and a variable is created when you assign a value to it. and I learned that you can delete the variable.

I have a few questions.

q1. in my code, in the first line, instead of c = a, I initially typed a = c, because, isn't a=c and c=a the same thing? but it didn't work. the code worked only when I did c = a, not a = c so I'm curious how that's the case.

q2. after c = a, is there any value left in a? I deleted a using del a just in case there's any value left in it because I don't know if it was the case.

q3. in the expected answer,

#line 1
c = a
#line 2
a = b
#line 3
b = c

after line 1, is there any value leftover in a and is overwritten then in line 2 with the value in b, or has the value of variable a been already transferred to c and thus was empty? this is a similar question to q2. do values move from variables to variables or do they copy themselves when doing so?

I'd like answers for q1, q2, and q3. I mean it's my first day of coding. so please be gentle.

  • q1. No, the direction matters. q2. Yes, a doesn't change after `c=a`. No need to del a. q3. there is still a value in `a` until line 2 where it's over written. `=` doesn't "transfer" values, it assigns them – SuperStew May 26 '22 at 13:24
  • 2
    See [Is there a standardized method to swap two variables in Python?](https://stackoverflow.com/q/14836228/3890632)—The normal method to swap variables is `a,b = b,a` – khelwood May 26 '22 at 13:24

1 Answers1

0

instead of c = a, I initially typed a = c, because, isn't a=c and c=a the same thing?

It's not.

a=b means means if b has any value, it will be assigned to a. b=a means if a has any value, it will be assigned to b.

Q2

yes there will be because you didn't do anything to a , you just used it's value.

var =None  "clears the value"
del var removes the definition for the variable totally.
DontDownvote
  • 137
  • 7