Python Syntax and Variables

Understanding Python syntax and how variables work is essential for writing clean, readable, and effective code. In this chapter, we will explore the foundational rules that govern Python’s structure, the role of variables in storing data, naming conventions, and how Python handles types dynamically.

1. Introduction to Python Syntax

Python emphasizes readability and simplicity. Its syntax rules eliminate many of the common syntactical requirements seen in other programming languages, such as braces {} and semicolons ;. Instead, Python uses indentation and newline characters to define the structure of code blocks.

1.1 Key Characteristics of Python Syntax

  • Whitespace Matters: Indentation is used to denote blocks of code.
  • No Semicolons Needed: Python does not require semicolons to end statements.
  • Case Sensitivity: Python is case-sensitive; Variable and variable are different.
  • Comments: Start with a hash symbol #. Multiline comments use triple quotes.
# This is a single-line comment
'''
This is a multiline comment
or documentation string
'''
  • Code Blocks: Defined by indentation (default is 4 spaces).
if True:
    print("This is true")

1.2 Example: Python vs C++

Python:

for i in range(5):
    print(i)

C++:

for (int i = 0; i < 5; i++) {
    cout << i << endl;
}

Python requires fewer lines and is more readable.

2. What are Variables?

Variables are containers for storing data values. In Python, you do not need to declare a variable type explicitly. You simply assign a value, and Python interprets the type dynamically.

2.1 Variable Declaration

In Python, declaring a variable is simple and requires no explicit type definition. Just assign a value to a name, and Python handles the rest dynamically.

x = 5        # Integer
name = "Ram" # String
pi = 3.14    # Float

Python figures out the type on its own.

2.2 Dynamic Typing

Dynamic typing means that the type of a variable is interpreted at runtime, and you can reassign variables to different data types without any type declaration.

x = 10       # x is an integer
x = "hello"  # now x is a string

Variables can be reassigned to different types without error.

3. Variable Naming Rules and Conventions

  • Must start with a letter (a-z, A-Z) or underscore _
  • Can contain letters, numbers, and underscores
  • Cannot use Python reserved keywords like if, class, True, etc.

3.2 Naming Styles

  • snake_case for variables and functions: user_name
  • CamelCase for classes: StudentRecord
  • Constants (by convention): PI = 3.14

3.3 Best Practices

  • Choose meaningful names: age, user_name, product_price
  • Avoid single-letter names unless used as iterators (i, j)
  • Use underscores to improve readability

4. Multiple Assignments

Python allows assigning values to multiple variables in a single line, making code more concise and readable. This feature is particularly useful for swapping values or initializing multiple variables simultaneously.

Python supports multiple assignment in a single line:

a, b, c = 1, 2, 3

Assign same value to multiple variables:

x = y = z = 100

Swap values easily:

a, b = b, a

5. Variable Scope

Variable scope in Python defines the region of the code where a variable is recognized. Understanding local and global scopes is crucial to avoid unintended side effects and bugs.

5.1 Local vs Global Variables

Local variables exist only within the function or block where they are defined, whereas global variables are accessible throughout the program.

  • Global: Defined outside functions, accessible everywhere
  • Local: Defined within a function, accessible only inside

Example:

x = 5  # global

def func():
    x = 10  # local
    print(x)

func()
print(x)

5.2 The global Keyword

The global keyword allows you to modify a variable declared in the global scope from within a function. Without using global, assignments inside a function create a new local variable.

Used when you want to modify a global variable inside a function.

x = 10

def change():
    global x
    x = 20

change()
print(x)  # Output: 20

6. Constants in Python

Constants in Python are variables whose values should not be changed once assigned. Though Python doesn’t enforce immutability, naming them in uppercase signals to other developers that these values are fixed.

Python doesn’t have built-in constant types, but by convention, constants are written in uppercase:

PI = 3.14159
GRAVITY = 9.8

There’s no enforcement, but developers follow this practice.

7. Type Conversion (Type Casting)

Type conversion, also known as type casting, is the process of converting the value of one data type to another. Python provides built-in functions to perform type casting easily and explicitly.

Python allows explicit type conversion:

int("10")    # Converts string to int
float(5)     # Converts int to float
str(100)     # Converts int to string

Use functions like int(), float(), str(), list(), etc.

8. Using type() and id() Functions

type() and id() are built-in Python functions used to inspect variables. While type() reveals the data type of a variable, id() returns its unique memory address.

type()

Returns the type of a variable:

x = 10
print(type(x))  # Output: <class 'int'>

id()

Returns the unique memory address of the object:

print(id(x))

Useful in debugging or identity comparison.

9. Reserved Keywords

Keywords are reserved words in Python that have special meaning and cannot be used as variable names or identifiers. They form the syntax and structure of Python code.

These cannot be used as variable names:

False, None, True, and, as, assert, break, class, continue,
def, del, elif, else, except, finally, for, from, global,
if, import, in, is, lambda, nonlocal, not, or, pass, raise,
return, try, while, with, yield

Check list using:

import keyword
print(keyword.kwlist)

10. String Formatting with Variables

String formatting allows you to insert variable values directly into strings, making output more readable and dynamic. Python provides multiple ways to format strings, including f-strings, the format() method, and the older % operator.

name = "Alice"
age = 25
print(f"Hello, my name is {name} and I am {age} years old.")

Other methods:

print("Name: {} Age: {}".format(name, age))

11. Practical Examples and Exercises

  1. Create a variable for each of these data types: integer, float, string, list, tuple.
  2. Create a function that modifies a global variable.
  3. Create a script that takes user input and prints out the type.
  4. Swap two variables without using a third variable.

12. Summary

In this chapter, we covered the syntax essentials and variable mechanics of Python. You now understand how Python manages whitespace, how to declare and manage variables, naming conventions, variable scope, constants, and type casting. These foundational skills are essential for everything you will build in Python.

Next Chapter: Data Types in Python – Learn the built-in types Python offers and how to use them effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top