We can create a new Python variable by assigning a value to a label, using the
= assignment operator.
In this example we assign a string with the value “Roger” to the
name = "Roger"
Here’s an example with a number:
age = 8
A variable name can be composed by characters, numbers, the
_ underscore character, and it can’t start with a number. Those are all valid variable names:
name1 AGE aGE a11111 my_name _name
Those are invalid variable names:
123 test! name%
Other than that, anything is valid unless it’s a Python keyword. There are some keywords like
import and more.
There’s no need to memorize them, as Python will alert you if you use one of those as a variable, and you will gradually recognize them as part of the Python programming language syntax.
Expressions and statements
We can expression any sort of code that returns a value. For example
1 + 1 "Roger"
A statement on the other hand is an operation on a value, for example those are 2 statements:
name = "Roger" print(name)
A program is formed by a series of statements. Each statement is put on its own line, but you can use a semicolon to have more than one statement on a single line:
name = "Roger"; print(name)
In a Python program, everything after a hash mark is ignored, and considered a comment:
#this is a commented line name = "Roger" # this is an inline comment
Indentation in Python is meaningful.
You cannot indent randomly like this:
name = "Flavio" print(name)
Some other languages do not have meaningful whitespace, but in Python indentation matters.
In this case, if you try to run this program you would get a
IndentationError: unexpected indent error, because indenting has a special meaning.
Everything indented belongs to a block, like a control statement or conditional block, or a function or class body. We’ll see more about those later on.
More python tutorials:
- Introduction to Python
- Installing Python 3 on macOS
- Running Python programs
- Python 2 vs Python 3
- The basics of working with Python
- Python Data Types
- Python Operators
- Python Strings
- Python Booleans
- Python Numbers
- Python, Accepting Input
- Python Control Statements
- Python Lists
- Python Tuples
- Python Sets
- Python Dictionaries
- Python Functions
- Python Objects
- Python Loops
- Python Modules
- Python Classes
- The Python Standard Library
- Debugging Python
- Python variables scope
- Python, accept arguments from command line
- Python Recursion
- Python Nested Functions
- Python Lambda Functions
- Python Closures
- Python Virtual Environments
- Use a GoPro as a remote webcam using Python
- Python, how to create a list from a string
- Python Decorators
- Python Docstrings
- Python Introspection
- Python Annotations
- Python, how to list files and folders in a directory
- Python, how to check if a number is odd or even
- Python, how to get the details of a file
- Python, how to check if a file or directory exists
- Python Exceptions