17 Antworten
+ 7
Your example was about conditional statements and variable assignment.
The fact that numbers are immutable have nothing to do with it.
x was assigned to a different value because of the condition you set.
here is an interesting discussion related to your question
https://stackoverflow.com/questions/62177372/is-integer-immutable-or-mutable
+ 3
You can update variables in python.
Even in python2 you can do this
True = False
(Because True will be treated as both variable and boolean and this can break code but just to tell that you can reassign variables)
+ 3
So basically the thing is the old value never really got erased from the memory and a new int value has been created in another memory location that holds the new value assigned use this code and you'll see:
x=5
print(x)
print(id(x))
x=12
print(x)
print(id(x))
#id prints out the memory location that holds that value
FF9900
+ 3
Python's internal workings is not something I often think about. I guess I'm just basically a simple utilitarian coder. If it gets the job done, no need to take it apart.
But here is another interesting tidbit
https://medium.com/@daniel.tooke/will-python-intern-my-string-94ea9efc18b2
+ 2
num = lambda x: 2 if x<0 else x+4
print(num(-1))
# or
print(num(1))
+ 1
Thanks 😊 i was just confused because my friend said that numbers and sequences are immutable in python .
+ 1
I've just tried this code:
x=5
print(x)
x=12
print(x)
And the value of x got updated ? Why? It's not in a conditional statement here.
+ 1
FF9900
4=5
"abcdef"[4] = "E
Yes, these are better examples of imutable.
0
Yes, the value of 'x' will get updated. As per the given condition, the 'else' part of if-else statement will get executed, so now the new value of x is 4. You can try it on any python supported IDE.
0
Yes, we can update with simple basic code by enabling the values to be of user's choice
x=int(input())
print(x)
- 1
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 20:24:02 2022
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 20:18:07 2022
"""
#print("Enter Course Code: ")
courseCode = input("Enter Course Code: ")
#print("Enter Continuous Assessment Mark: ")
markCA = float(input("Enter Continuous Assessment Mark: "))
if markCA >= 0 and markCA <= 30:
#print("Enter Examination Mark: ")
markExam = float(input("Enter Examination Mark: "))
if markExam >= 0 and markExam <= 70:
markTotal = markCA + markExam
if markTotal >= 70:
status = "Pass"
grade = "A"
if markTotal >= 60:
status = "Pass"
grade = "B"
if markTotal >= 50:
status = "Pass"
grade = "C"
if markTotal >= 40:
status = "Pass"
grade = "D"
if markTotal < 40:
status = "Trail"
grade = "F"
print("\n=============
- 2
How to detect bugs in this code