1.1. Variable names, Expressions and statements#

1.1.1. Variables#

In Python, variables are used to store and manage data. A variable is a symbolic name that references a value, and you can assign various data types (such as numbers, strings, lists, etc.) to variables. Here are the key points about variables in Python [Downey, 2015, Python Software Foundation, 2023]:

  1. Variable Naming Rules:

    • Variable names must start with a letter (a-z, A-Z) or an underscore (_).

    • The subsequent characters can be letters, underscores, or digits (0-9).

    • Variable names are case-sensitive (“myVar” and “myvar” are considered different).

    • Avoid using Python keywords (reserved words) as variable names.

  2. Assignment:

    • Variables are assigned using the = operator.

    • The value on the right side of the = is assigned to the variable on the left side.

    • Example: x = 5 assigns the value 5 to the variable x.

  3. Data Types:

    • Python is dynamically typed, meaning you don’t need to specify the data type when declaring a variable. The interpreter determines the type based on the assigned value.

    • Common data types include integers, floats, strings, lists, tuples, dictionaries, and more.

  4. Reassignment:

    • You can reassign a variable to a new value of a different type.

    • Example: x = 'Hello' reassigns the variable x to the string 'Hello'.

  5. Variable Usage:

    • You can use variables in expressions, print statements, function calls, and more.

    • Variables hold the value you assigned until you reassign them or the program ends.

Here’s a simple example that demonstrates variable usage:

# Variable assignment
x = 10
y = 'Hello, World!'
z = [1, 2, 3] # This is a list

# Variable usage
print(x)        # Output: 10
print(y)        # Output: Hello, World!
print(z)        # Output: [1, 2, 3]

# Variable reassignment
x = 'Python'
print(x)        # Output: Python
10
Hello, World!
[1, 2, 3]
Python

This example declares variables x, y, and z, assigns values to them, and demonstrates their use in a print statement. It also shows how x is reassigned from an integer to a string.

1.1.2. Valid and Invalid Variable Names in Python#

In Python, variable names are fundamental elements used to identify and store data values. These names play a crucial role in making your code readable and self-explanatory. It’s essential to understand the rules for creating valid variable names and to follow best practices to enhance code clarity and maintainability [Downey, 2015, Python Software Foundation, 2023].

1.1.2.1. Valid Variable Names:#

Valid variable names must adhere to a set of rules to be considered syntactically correct in Python:

  1. Start with a letter or underscore (_): A valid variable name must begin with a letter (either lowercase or uppercase) or an underscore. It cannot start with a digit or any other character. Using an underscore as the first character is a common convention for denoting “private” variables, but it has a special meaning in some contexts. For example:

valid_variable = 42
my_var = "Calgary"
  1. Subsequent characters: After the initial character, a variable name can contain letters, underscores, and digits (0-9). No spaces or special characters (except underscore) are allowed within the variable name. This rule ensures that variable names are consistent and easy to understand. For example:

count123 = 42
my_var = "Hello"
  1. Case-sensitive: Python variable names are case-sensitive, meaning that variables with different letter case are treated as distinct entities. This distinction is important when working with variables. For example:

my_var = 5
My_Var = "Hello Calgary"
  1. Avoid using Python keywords: Variable names cannot be the same as Python keywords, which are reserved words used for specific purposes in the language. Using keywords as variable names will lead to syntax errors or unexpected behavior. For example, avoid using names like if, for, while, and so on.

1.1.2.2. Invalid Variable Names:#

Invalid variable names violate one or more of the rules mentioned above:

  1. Starting with a number: A variable name that starts with a digit is invalid because it doesn’t follow the rule of starting with a letter or underscore. For example:

    123data = "Invalid variable name"
    
  2. Containing special characters: Variable names cannot contain spaces or special characters (except underscores). Using characters like hyphens, dots, or symbols within a variable name is not allowed in Python. For example:

    my-var = "Invalid variable name"
    my.var = "Invalid variable name"
    
  3. Using Python keywords: Variable names that match Python keywords are invalid. These keywords have predefined meanings in the language, and using them as variable names will lead to conflicts and errors. For example:

    if = 42  # Invalid use of a Python keyword
    

By choosing meaningful and descriptive variable names while adhering to these rules, you can enhance the readability and clarity of your Python programs.

1.1.3. Data Types#

Data types are fundamental classifications that describe the nature of values in a programming language. They specify the kind of data a variable can hold and the operations that can be performed on that data. In Python, which is a dynamically-typed language, data types are determined at runtime. Here are some common data types in Python:

  1. Numeric Types:

    • int: Represents integer values, such as -3, 0, or 42. These are whole numbers without a fractional part.

    • float: Represents floating-point numbers with a decimal point or in scientific notation, like 3.14 or 2.5e-3 (which means 2.5 * 10^-3).

  2. String Type (str):

    • Represents sequences of characters enclosed in single (’ ‘) or double (” “) quotes.

    • Example: "Hello, World!". Strings are versatile and support various operations like concatenation, slicing, and formatting.

  3. Boolean Type (bool):

    • Represents the values True or False, which are used in logical expressions and conditions.

    • Example: True or False. Boolean operations include and, or, and not.

  4. List Type (list):

    • Represents ordered collections of items, which can be of different data types.

    • Lists are mutable, allowing you to add, remove, or modify elements.

    • Example: [1, 2, "apple", True]. Access elements by index, e.g., my_list[0].

  5. Tuple Type (tuple):

    • Represents ordered collections of items like lists, but tuples are immutable (cannot be changed after creation).

    • Tuples are often used when you want to ensure the integrity of the data.

    • Example: (3, 7, "banana"). Access elements by index, similar to lists.

  6. Dictionary Type (dict):

    • Represents key-value pairs, where each value is associated with a unique key.

    • Dictionaries are useful for quick data lookups, and the keys must be immutable (e.g., strings, numbers, or tuples).

    • Example: {"name": "Alice", "age": 30, "city": "Wonderland"}. Access values using keys, e.g., my_dict["age"].

  7. Set Type (set):

    • Represents unordered collections of unique elements, useful for tasks like removing duplicates.

    • Sets do not allow duplicate values, and they support set operations like union, intersection, and difference.

    • Example: {1, 2, 3, 3, 4}. Create a set using curly braces, e.g., my_set = {1, 2, 3}.

  8. None Type (NoneType):

    • Represents the absence of a value or a null value.

    • Often used to indicate the absence of a meaningful result or to initialize variables that will be assigned a value later.

    • Example: None.

Note

In Chapter 3, we will discuss various data structures.

The applications of each of the 8 data types in Python programming tasks [Downey, 2015, Python Software Foundation, 2023]:

Data Type

Applications

Numeric Types

Arithmetic operations, calculations, storing/manipulating numerical data, handling quantities, scientific/engineering.

String Type

Working with textual data, input/output, parsing, formatting, manipulating strings, user interfaces, generating reports.

Boolean Type

Implementing conditionals, decision-making, logical expressions, comparisons, handling binary states.

List Type

Storing ordered collections, dynamic data structures, stacks/queues, managing/organizing data.

Tuple Type

Ensuring data integrity, returning multiple values from functions, representing structured data.

Dictionary Type

Efficient data retrieval/manipulation with key-value pairs, data caches, configuration management, indexing.

Set Type

Removing duplicates, membership checks, set operations, uniqueness in algorithms.

None Type

Representing absence of value, indicating lack of meaningful result, initializing variables.

1.1.3.1. Data Type Conversion Functions#

In Python, there are several data conversion functions that allow you to convert between different data types. Here’s a list of some commonly used data conversion functions [Python Software Foundation, 2023]:

  1. int(x, base=10)

    • Converts x to an integer. The base parameter specifies the base to interpret the input string (default is 10).

    • Example: int('42') returns 42.

  2. float(x)

    • Converts x to a floating-point number.

    • Example: float('3.14') returns 3.14.

  3. str(x)

    • Converts object x to a string representation.

    • Example: str(42) returns '42'.

  4. chr(i)

    • Returns a string representing a character whose Unicode code point is the integer i.

    • Example: chr(65) returns 'A'.

  5. ord(c)

    • Returns an integer representing the Unicode character.

    • Example: ord('A') returns 65.

  6. bool(x)

    • Converts x to a Boolean value (True or False).

    • Example: bool(0) returns False.

  7. list(iterable)

    • Converts an iterable (e.g., a tuple, string, or set) to a list.

    • Example: list((1, 2, 3)) returns [1, 2, 3].

  8. tuple(iterable)

    • Converts an iterable to a tuple.

    • Example: tuple([1, 2, 3]) returns (1, 2, 3).

  9. set(iterable)

    • Converts an iterable to a set.

    • Example: set([1, 2, 3, 3]) returns {1, 2, 3}.

  10. dict()

    • Creates a new dictionary.

    • Example: dict(a=1, b=2) returns {'a': 1, 'b': 2}.

  11. str.encode(encoding=‘UTF-8’, errors=‘strict’)

    • Encodes the string using the specified encoding.

    • Example: 'hello'.encode('UTF-16') returns b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'.

  12. bytes.decode(encoding=‘UTF-8’, errors=‘strict’)

    • Decodes a bytes object to a string using the specified encoding.

    • Example: b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'.decode('UTF-16') returns 'hello'.

These functions are essential for handling different data types and performing type conversions in Python.

Conversion Function

Description

Example Usage

int(x, base=10)

Converts x to an integer.

int('42') returns 42.

float(x)

Converts x to a floating-point number.

float('3.14') returns 3.14.

str(x)

Converts object x to a string representation.

str(42) returns '42'.

chr(i)

Returns a string representing a Unicode character.

chr(65) returns 'A'.

ord(c)

Returns the Unicode code point of a character.

ord('A') returns 65.

bool(x)

Converts x to a Boolean value (True or False).

bool(0) returns False.

list(iterable)

Converts an iterable to a list.

list((1, 2, 3)) returns [1, 2, 3].

tuple(iterable)

Converts an iterable to a tuple.

tuple([1, 2, 3]) returns (1, 2, 3).

set(iterable)

Converts an iterable to a set.

set([1, 2, 3, 3]) returns {1, 2, 3}.

dict()

Creates a new dictionary.

dict(a=1, b=2) returns {'a': 1, 'b': 2}.

str.encode(encoding=‘UTF-8’, errors=‘strict’)

Encodes a string using the specified encoding.

'hello'.encode('UTF-16') returns b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'.

bytes.decode(encoding=‘UTF-8’, errors=‘strict’)

Decodes a bytes object to a string using the specified encoding.

b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'.decode('UTF-16') returns 'hello'.

Remark

In Python, str.encode() and bytes.decode() are methods used to convert between string objects (str) and bytes objects (bytes) while specifying the character encoding to be used for the conversion. Encoding is the process of converting textual data (strings) into bytes, while decoding is the process of converting bytes back into textual data [Python Software Foundation, 2023].

  1. str.encode(encoding='UTF-8', errors='strict'):

    • This method is used to encode a string into bytes using the specified character encoding.

    • The encoding parameter specifies the character encoding to use. By default, it is set to 'UTF-8', which is a widely used encoding for Unicode characters.

    • The errors parameter specifies how to handle characters that cannot be encoded using the given encoding. The default is 'strict', which raises an error if such characters are encountered. Other options include 'ignore', 'replace', and more.

    • Example: encoded_bytes = my_string.encode('UTF-8', errors='ignore')

  2. bytes.decode(encoding='UTF-8', errors='strict'):

    • This method is used to decode bytes into a string using the specified character encoding.

    • The encoding parameter specifies the character encoding used during the decoding process. The default is 'UTF-8'.

    • The errors parameter, similar to str.encode(), specifies how to handle decoding errors. The default is 'strict', which raises an error. Other options include 'ignore', 'replace', etc.

    • Example: decoded_string = my_bytes.decode('UTF-8', errors='replace')

Here are a few things to keep in mind:

  • Textual data is typically stored as strings (str), and binary data (e.g., files, network communication) is often represented as bytes (bytes).

  • The choice of encoding is crucial to ensure that characters are correctly represented during the conversion between strings and bytes, especially when dealing with non-ASCII characters and different languages.

  • The encode and decode methods are bidirectional and reversible; encoding followed by decoding should ideally return the original data. However, if the encoding and decoding methods are not symmetric, data loss or unexpected behavior might occur.

# Conversion functions
# int(x, base=10)
int_from_string = int('42')
int_from_float = int(132.0)

# float(x)
float_from_string = float('3.14')
float_from_integer = float(132)

# str(x)
integer_to_string = str(42)

# chr(i)
unicode_character = chr(65)

# ord(c)
unicode_code_point = ord('A')

# bool(x)
boolean_from_integer = bool(0)

# list(iterable)
list_from_tuple = list((1, 2, 3))

# tuple(iterable)
tuple_from_list = tuple([1, 2, 3])

# set(iterable)
set_from_list = set([1, 2, 3, 3])

# dict()
new_dictionary = dict(a=1, b=2)

# str.encode(encoding='UTF-8', errors='strict')
encoded_string = 'hello'.encode('UTF-16')

# bytes.decode(encoding='UTF-8', errors='strict')
decoded_bytes = b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'.decode('UTF-16')

# Printing the results
print("int_from_string:", int_from_string)
print("int_from_float:", int_from_float)
print("float_from_string:", float_from_string)
print("float_from_integer:", float_from_integer)
print("integer_to_string:", integer_to_string)
print("unicode_character:", unicode_character)
print("unicode_code_point:", unicode_code_point)
print("boolean_from_integer:", boolean_from_integer)
print("list_from_tuple:", list_from_tuple)
print("tuple_from_list:", tuple_from_list)
print("set_from_list:", set_from_list)
print("new_dictionary:", new_dictionary)
print("encoded_string:", encoded_string)
print("decoded_bytes:", decoded_bytes)
int_from_string: 42
int_from_float: 132
float_from_string: 3.14
float_from_integer: 132.0
integer_to_string: 42
unicode_character: A
unicode_code_point: 65
boolean_from_integer: False
list_from_tuple: [1, 2, 3]
tuple_from_list: (1, 2, 3)
set_from_list: {1, 2, 3}
new_dictionary: {'a': 1, 'b': 2}
encoded_string: b'\xff\xfeh\x00e\x00l\x00l\x00o\x00'
decoded_bytes: hello

1.1.4. Expressions#

In Python, an expression is a combination of values, variables, operators, and function calls that can be evaluated to produce a result. Expressions are the building blocks of Python code, and they form the basis for performing computations, making decisions, and manipulating data. Here are some key points about expressions in Python [Downey, 2015, Python Software Foundation, 2023]:

Expressions in Python are combinations of values, variables, operators, and function calls that can be evaluated to produce a result. They are fundamental building blocks in Python that enable you to perform computations, make decisions, and manipulate data. Here are some key points about expressions:

  1. Arithmetic Expressions: These involve mathematical operations, such as addition, subtraction, multiplication, division, and more. Arithmetic expressions produce numeric results.

x = 5
y = 3
result = x + y * 2
print(result)  # Output: 11 (5 + 3 * 2)
11
  1. Comparison Expressions: These are used to compare values using comparison operators like <, >, <=, >=, ==, and !=. Comparison expressions result in boolean values (True or False).

a = 10
b = 7
is_greater = a > b
print(is_greater)  # Output: True
True
  1. Logical Expressions: These involve logical operations such as and, or, and not. They are used for making decisions and evaluating conditions. Logical expressions also result in boolean values.

x = True
y = False
result = x and not y
print(result)  # Output: True (True and (not False))
True
  1. String Expressions: These involve operations on strings, such as concatenation (joining strings) or accessing individual characters.

greeting = "Hello " + "Calgary!"
print(greeting)  # Output: Hello Calgary!
Hello Calgary!
  1. Function Call Expressions: These involve calling functions with arguments. The result of the function call is the value returned by the function.

length = len("Python")
print(length)  # Output: 6 (length of the string "Python")
6
  1. Operator Precedence: Expressions in Python follow operator precedence rules. Operators like multiplication have higher precedence than addition, and parentheses can be used to control the order of operations.

result = 3 + 4 * 2
print(result)  # Output: 11 (Multiplication is performed before addition)
11
  1. Evaluation: When an expression is evaluated, it results in a value. This value can be assigned to a variable, used in conditional statements, or printed to the console.

area = 2 * (5 + 3)
print(area)  # Output: 16 (result of the expression)
16

1.1.5. Statements#

In Python, statements are instructions that perform actions or operations. They are the fundamental building blocks of a Python program, and they define the behavior of the program. Here are some key types of statements in Python [Downey, 2015, Python Software Foundation, 2023]:

  1. Assignment Statements: Assign values to variables. The assignment operator (=) is used to assign a value to a variable.

x = 5
name = "Alice"
  1. Expression Statements: These are statements that evaluate an expression and, optionally, perform some action with the result. Most statements in Python are expression statements.

result = 3 + 4
print(result)
7
  1. Conditional Statements (if, elif, else): Control the flow of the program based on conditions.

x = 5

if x > 10:
    print("x is greater than 10")
elif x == 10:
    print("x is equal to 10")
else:
    print("x is less than 10")
x is less than 10
  1. Loop Statements (for, while): Execute a block of code repeatedly.

for i in range(5):
    print(i)
0
1
2
3
4
x = 5

while x < 10:
    print('x =',x, ", x is still less than 10")
    x += 1
x = 5 , x is still less than 10
x = 6 , x is still less than 10
x = 7 , x is still less than 10
x = 8 , x is still less than 10
x = 9 , x is still less than 10
  1. Function Definitions: Define reusable blocks of code.

def greet(name):
    print("Hello, " + name + "!")
  1. Import Statements: Import modules and functions from other files.

import math
from random import randint
  1. Exception Handling (try, except, finally): Handle errors and exceptions gracefully.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error: Division by zero")
finally:
    print("This block always executes")
Error: Division by zero
This block always executes
  1. Break and Continue Statements: Control the flow within loops.

for i in range(10):
    if i == 5:
        break  # Exit the loop when i is 5
    print(i)

for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)
0
1
2
3
4
1
3
5
7
9

Note

In the forthcoming chapters, we will comprehensively delve into the intricacies of the aforementioned concepts.