2-5. Expressions

In Python, the key to working with data in programs is through expressions. Expressions are snippets of code that generate or calculate new data values. They can be as simple as a literal value or more complex by combining multiple elements. Let's break down the basics:

Literals

Literals are the simplest form of expressions. They directly represent specific values in the code. There are two main types of literals:

  • Numeric Literals: These are numbers written directly in the code.
4.5, 1, 9, 32
  • String Literals: These are sequences of characters enclosed in quotation marks.
"Hello", "Enter a number between 0 and 1: "

 

Evaluation of Expressions

When you input an expression into the Python interpreter, it evaluates the expression and returns its value. For instance:

>>> 7
7
>>> "Hello"
'Hello'

Here, the number 7 is evaluated to 7, and the string "Hello" is evaluated to 'Hello'.

Variables can also be used in expressions. If a variable has been assigned a value, Python evaluates it to that value. If not, it raises a NameError.

>>> x = 10
>>> x
10
>>> print(x)
10
>>> print(y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

 

Combining Expressions with Operators

Expressions can be made more complex by combining them with operators. Python supports various operators for different operations:

  • Addition (+): Adds two numbers.
  • Subtraction (-): Subtracts one number from another.
  • Multiplication (*): Multiplies two numbers.
  • Division (/): Divides one number by another.
  • Exponentiation ()**: Raises one number to the power of another.

The order in which operations are performed follows the rules of precedence and associativity, which can be controlled using parentheses.

>>> x = 10
>>> y = 20
>>> z1 = 3 * x + y
>>> z2 = 3 * (x + y)
>>> print(z1)
50
>>> print(z2)
90

 

String Operations

Python also allows for operations on strings, such as concatenation, which combines strings together.

>>> "Hello" + " " + "World"
'Hello World'

This example shows how strings can be joined to form a new string.

Expressions are a fundamental part of Python programming, allowing you to manipulate and create new data values. We'll explore more operations and data manipulations in later chapters.