Python Basics & Syntax

This foundational topic covers the essential Python syntax, core data types, control flow mechanisms, and functions. Mastering these elements is crucial for professionals in data science and machine learning to write clear, efficient, and maintainable Python code.

7 free lessons available

Start here

Variables & Data Types

In any programming language, you need a way to store and manipulate information. Python provides variables as named containers for data, allowing you to refer to values by a meaningful name rather than their raw form. This abstraction makes your code more readable, maintainable, and flexible, as you can change the underlying value without altering every place it's used.

What are Variables?

Think of a variable as a label or a tag that you attach to a piece of data in your computer's memory. Instead of directly interacting with memory addresses, you use these descriptive labels. When you assign a value to a variable, Python creates an object in memory to hold that value and then makes the variable name point to that object. This allows you to retrieve or modify the data simply by using the variable's name.

pythonAssigning Values to Variables
✨ Variable Naming Conventions

Python variables typically follow snake_case (all lowercase, words separated by underscores), like user_name or total_sales. Variable names must start with a letter or an underscore, and can contain letters, numbers, or underscores. They are also case-sensitive (myVar is different from myvar). Choose descriptive names that clearly indicate the variable's purpose.

Python's Core Data Types

While variables hold data, the data type defines the kind of data a variable can store and the operations that can be performed on it. Python is a dynamically typed language, meaning you don't explicitly declare a variable's type; Python infers it at runtime. Understanding these fundamental types is crucial for writing correct and efficient code, as different types behave in distinct ways.

Integers (int)

Integers represent whole numbers, positive or negative, without any decimal point. They are used for counting, indexing, and any scenario where fractional values are not applicable. Python's integers have arbitrary precision, meaning they can be as large as your system's memory allows, unlike some other languages with fixed-size integer types. This makes them incredibly versatile for handling very large numbers without overflow issues.

pythonWorking with Integer Data

Floating-Point Numbers (float)

Floating-point numbers, or floats, represent real numbers with a decimal point. They are essential for calculations involving fractions, measurements, scientific data, and financial values. Python uses the standard IEEE 754 double-precision format for floats, which offers a good balance of range and precision. While powerful, it's important to be aware of potential precision limitations inherent in floating-point arithmetic.

pythonHandling Decimal Values with Floats
💡 Floating-Point Precision

Due to how computers store floating-point numbers in binary, some decimal numbers cannot be represented exactly. This can lead to tiny, unexpected differences in calculations, such as 0.1 + 0.2 not being exactly 0.3. For financial calculations where exact decimal precision is critical, consider using Python's decimal module instead of standard floats.

Check Your Understanding
What will be the data type of result after executing x = 10; y = 3.0; result = x / y?

Strings (str)

Strings are sequences of characters used to represent text. They are enclosed in single quotes ('...'), double quotes ("..."), or triple quotes ('''...''' or """...""") for multi-line strings. Strings are immutable, meaning once created, their content cannot be changed. Any operation that appears to modify a string, such as concatenation, actually creates a new string object in memory. This immutability ensures that string values remain consistent throughout their lifecycle.

pythonManipulating Text with Strings

Booleans (bool)

Booleans represent truth values: either True or False. They are crucial for control flow, allowing your programs to make decisions based on conditions. Boolean values are the result of comparison operations (e.g., x > y) and are used extensively in if statements, while loops, and logical operations. Python's True and False are capitalized keywords, distinct from string representations like 'True' or 'False'.

pythonUsing Boolean Logic for Decision Making
Check Your Understanding
Which of the following expressions will evaluate to True?

Dynamic Typing: Python's Flexibility

Python is a dynamically typed language, which means you do not explicitly declare the data type of a variable when you create it. Instead, Python automatically determines the type of a variable at runtime based on the value assigned to it. This offers great flexibility, as a single variable can hold different types of data at different points in your program's execution. However, this flexibility also requires careful programming to avoid unexpected type-related errors.

pythonReassigning Variables with Different Types

Checking Data Types with type()

Given Python's dynamic typing, it's often useful to explicitly check the data type of a variable at runtime. The built-in type() function allows you to do exactly this, returning the class type of the object a variable refers to. This is particularly helpful for debugging, validating inputs, or ensuring that a variable holds the expected type before performing type-specific operations. Knowing the type helps prevent TypeError exceptions.

pythonInspecting Variable Types

Type Conversion (Casting)

Sometimes, you need to change a variable from one data type to another, a process known as type conversion or casting. Python provides built-in functions for this purpose, such as int(), float(), str(), and bool(). These functions attempt to convert the input value into the specified type. Type conversion is common when processing user input, which is often received as a string but needs to be treated as a number for calculations, or when formatting output.

pythonConverting Between Data Types
⚠️ Potential Type Conversion Errors

Be cautious when converting types. For example, int('hello') or float('abc') will raise a ValueError because the string cannot be meaningfully converted to a number. Similarly, int(3.9) will truncate the decimal part, resulting in 3, not 4 (it does not round). Always ensure the data is compatible with the target type before attempting conversion.

Variables and Memory: A Conceptual Model

In Python, variables do not directly store values; instead, they store references (memory addresses) to objects that contain the actual values. When you assign x = 10, x becomes a label pointing to an integer object 10. If you then do y = x, y also points to the same integer object 10. This object-oriented model means that multiple variables can refer to the same data in memory, which is a key concept for understanding how Python manages data, especially with mutable types like lists and dictionaries.

Conceptual Model: Variables Referencing Objects in Memory
Loading diagram...
This diagram illustrates how variables in Python act as labels that point to distinct data objects stored in memory. The variable name is separate from the actual value it holds.
Key Takeaways
  • Variables are named references to data objects in memory, making code readable and manageable.

  • Python automatically infers a variable's data type (e.g., int, float, str, bool) based on the assigned value, a concept known as dynamic typing.

  • Integers (int) handle whole numbers, floats (float) handle decimal numbers (with precision considerations), strings (str) manage text, and booleans (bool) represent True/False logic.

  • Use the built-in type() function to inspect the data type of any variable at runtime, which is crucial for debugging and type-safe operations.

  • Type conversion (casting) functions like int(), float(), str(), and bool() allow you to explicitly change a value's data type, but be mindful of potential ValueError if the conversion is invalid.

  • Variables store references to objects, not the objects themselves. Multiple variables can point to the same object, which is fundamental to Python's memory model.

Open this lesson on its own page →

Ready to keep this from fading?

Bitelrn turns lessons like this into a full course — quizzes, a knowledge map, and spaced review.

Get started free