Variables And Comments In Python
Python Variables and Comments: Comprehensive Theory
Understanding how to store data and document your code is the first step toward writing clean and maintainable Python scripts.
1. Python Comments
Comments are used to explain Python code and make it more readable. They can also be used to prevent execution when testing code.
Single-Line Comments
Single-line comments start with a #. Python will ignore the rest of the line.
# This is a comment
print("Hello, World!") # This is also a comment
Multi-Line Comments
Python does not have a specific syntax for multi-line comments. You can use # on each line, or use a multi-line string (triple quotes) that is not assigned to a variable.
"""
This is a multiline comment
written in more than just one line.
"""
print("Hello, World!")
2. Python Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
x = 5
y = "John"
print(x)
print(y)
Dynamic Typing
In Python, variables do not need to be declared with any particular type, and can even change type after they have been set.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting:
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
3. Variable Naming Rules
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
- Must start with a letter or the underscore character.
- Cannot start with a number.
- Can only contain alpha-numeric characters and underscores (
A-z,0-9, and_). - Are case-sensitive (
age,Age, andAGEare three different variables). - Cannot be any of the Python keywords (like
if,while,class).
4. Outputting Variables
The Python print() function is often used to output variables.
x = "Python is "
y = "awesome"
z = x + y
print(z) # Output: Python is awesome
# You can also output multiple variables separated by a comma
a = 5
b = 10
print(a, b) # Output: 5 10
Practice Problems
- Variable Swap: Create two variables
a = 10andb = 20. Write code to swap their values so thatabecomes 20 andbbecomes 10. - Naming Check: Which of the following are valid variable names?
2myvar,my-var,_my_var,my var,MYVAR. - Basic Arithmetic: Create a variable
base = 10andheight = 20. Calculate the area of a triangle (0.5 * base * height) and print the result. - Comment Exercise: Take any code you've written and add at least three comments explaining what different parts of the code do.