Assignment statements are a core concept in Python, allowing you to assign values to variables. The essence of an assignment is quite simple: it calculates the value of an expression on the right and assigns it to the variable on the left. This operation forms the basis of most programming tasks in Python.
The basic syntax is:
variable = expression |
This assigns the value of the expression on the right to the variable on the left. Examples:
area = 3.14 * radius ** 2 temperature = (fahrenheit - 32) * 5/9 counter = 10 |
In addition, you can reassign variables as many times as needed:
# Initial assignment # Reassignment # Update based on current value |
Variables as References
In Python, variables act as references to values, not containers. When you reassign a variable, it points to a new value, and the old value is eventually discarded if not referenced elsewhere.
Gathering User Input with input()
The input() function is used to get input from the user, and it always returns the input as a string.
Syntax:
variable = input(prompt) |
For example:
favorite_color = input("Please enter your favorite color: ") print(favorite_color) |
For numerical input, you need to convert the string to a number:
age = int(input("Enter your age: ")) temperature = float(input("Enter the current temperature: ")) |
Using eval(input()) can be risky, so it's safer to use type-specific conversion functions such as int() or float().
Multiple Assignment
Multiple assignment allows you to assign values to multiple variables in a single statement.
Syntax:
var1, var2, ..., varN = expr1, expr2, ..., exprN |
Example:
total, difference = a + b, a - b |
This is very useful when swapping values:
a, b = b, a |
And for capturing multiple user inputs:
print("Enter two exam scores separated by a comma: ") score1, score2 = map(int, input().split(',')) average = (score1 + score2) / 2 print("The average score is:", average) |
This technique enhances code efficiency and compactness.