In this tutorial, you'll learn about variables and constants in Python. Understanding how to declare and use variables is fundamental to programming with Python. Variables allow you to store data that can be manipulated and used throughout your program. Constants, on the other hand, are values that remain unchanged once set.
Variables in Python are dynamically typed, meaning you don't need to explicitly declare their type when you create them. This flexibility makes Python easy to use for beginners but also requires careful attention to ensure your code behaves as expected.
In Python, you can create a variable by simply assigning a value to it using the = operator. Here's a basic example:
1x = 102print(x)
When you run this code, the output will be:
In this example, the values 1, 2, and 3 are assigned to the variables a, b, and c, respectively.
You can also use multiple assignment to swap the values of two variables without needing a temporary variable:
1x = 52y = 1034# Swap values using multiple assignment5x, y = y, x67print(x)8print(y)
The output will be:
10 5
This is a common technique in Python to swap the values of two variables.
Constants in Python are not a built-in feature like in some other programming languages. However, by convention, constants are represented using uppercase letters with underscores separating words (similar to snake_case). This convention helps indicate that the value should not be changed once it's set. For example:
1PI = 3.141592GRAVITY = 9.81
While Python does not enforce immutability for constants, following this convention is a good practice to prevent accidental modification of these values.
Let's create a simple program that calculates the area and circumference of a circle using variables and constants:
1# Constants2PI = 3.1415934# Variables5radius = float(input("Enter the radius of the circle: "))67# Calculations8area = PI * radius ** 29circumference = 2 * PI * radius1011# Output results12print(f"The area of the circle is {area:.2f}")13print(f"The circumference of the circle is {circumference:.2f}")
When you run this program, it will prompt you to enter the radius of a circle and then calculate and display the area and circumference.
= operator.snake_case for variable names to improve readability.In the next tutorial, you'll learn about basic input and output operations in Python. Understanding how to interact with users is essential for creating functional programs. Make sure to practice what you've learned about variables and constants by experimenting with different values and calculations.