Python Programming

Variables and Basic Data Types

5 sections AI-powered notes
GET THE FULL EXPERIENCE

This is the chapter notes. Students get the interactive version.

  • Ask Aarav Sir anything — instant voice + chat doubts
  • Interactive lessons with audio narration + visual diagrams
  • Study Lab — paste any photo, PDF, or YouTube link to get it explained

What are Variables?

What are Variables? The Building Blocks of Your Code

Imagine you're baking a cake. You need sugar, flour, eggs, and milk. Instead of remembering the exact amount of each ingredient every time you use it (e.g., "700 grams of white crystalline substance," "500 grams of finely ground grain"), you label containers: one for "sugar," one for "flour," and so on. When the recipe says "add sugar," you grab the container labeled "sugar." If you run out, you refill the "sugar" container, and it still holds sugar, just a different amount.

In programming, variables serve a very similar purpose. They are named storage locations that hold data in a computer's memory. Instead of remembering the exact memory address where a piece of information resides (which would be incredibly complex and error-prone!), you give that storage location a human-readable name – a variable name.

Why Do We Need Variables?

Variables are absolutely fundamental for several reasons:

  1. Storing Information: They allow your program to remember pieces of data, like a user's name, a calculated score, the current temperature, or the number of items in a shopping cart. Without variables, your program would be like a person with no short-term memory!
  2. Reusability: Once you store a value in a variable, you can refer to it multiple times throughout your code without having to type the value out repeatedly. This makes your code cleaner, shorter, and less prone to errors.
  3. Flexibility: The value stored in a variable can change as your program runs. This is crucial for dynamic applications that respond to user input or changing conditions. For instance, a variable score can start at 0 and increase as a player earns points, or current_time can update every second.
  4. Readability: Giving meaningful names to your variables makes your code much easier for you (and others) to understand. Imagine trying to debug code where x holds a customer's name, y holds their age, and z holds their order total. customer_name, customer_age, and order_total are far clearer!

{{VISUAL: diagram: an analogy showing a variable as a labeled container (e.g., "age") holding a specific data value (e.g., "30").}}

Declaring and Assigning Variables in Python

Python makes working with variables incredibly straightforward. Unlike some other programming languages, you don't need to explicitly "declare" the type of data a variable will hold before using it. You simply assign a value to a name using the equals sign (=), which is called the assignment operator. Python is smart enough to figure out the data type on its own.

Let's look at an example:

# Assigning an integer (whole number) value
age = 30

# Assigning a string (text) value
user_name = "Alice"

# Assigning a floating-point (decimal number) value
price = 19.99

# Assigning a boolean (True/False) value
is_active = True

In the examples above:

  • age, user_name, price, and is_active are our variable names. These are the labels.
  • 30, "Alice", 19.99, and True are the values being stored. These are the contents.
  • The = symbol assigns the value on the right to the variable name on the left.

Once a variable has been assigned a value, you can use its name to access that value anywhere in your code:

print(age)           # Output: 30
print(user_name)     # Output: Alice

# You can even use variables in calculations!
total_cost = price * 2
print(total_cost)    # Output: 39.98 (19.99 * 2)

What's happening "under the hood"?

When you write age = 30, Python doesn't just put the number 30 into a box named age. Instead, Python creates an "object" representing the number 30 somewhere in your computer's memory. Then, the variable age acts like a label or a reference that points to that object.

If you then do age = 31, Python creates a new object for the number 31 and makes the variable age point to that new object. The old 30 object might still exist in memory for a short while, but age no longer refers to it. Python's memory management (called "garbage collection") eventually cleans up objects that are no longer referenced by any variable, freeing up memory.

{{VISUAL: diagram: a sequence showing a variable 'x' initially pointing to value '10' in memory, and then after reassignment 'x' pointing to a different value '20' in memory, illustrating how references change.}}

Variable Naming Rules and Best Practices

Choosing good, descriptive names for your variables is a hallmark of good programming. It makes your code much easier to read, understand, and maintain, especially as your programs grow in complexity. Python has specific rules you must follow and widely accepted conventions you should follow for naming variables.

Rules (Must Follow):

  1. Start with a Letter or Underscore: Variable names must begin with a letter (a-z, A-Z) or an underscore (_). They cannot start with a number.
    • valid_name = 10
    • _private_var = "secret"
    • 1st_number = 5 (Invalid! This will cause a SyntaxError.)
  2. Alphanumeric Characters and Underscores: The rest of the variable name can consist of letters, numbers (0-9), and underscores. Spaces are not allowed.
    • my_variable_name = "hello"
    • item_count_2 = 100
    • my variable = "nope" (Invalid! This will cause a SyntaxError.)
  3. Case-Sensitive: Python variable names are case-sensitive. age, Age, and AGE are considered three different variables.
    • my_variable = 5
    • My_Variable = 10 # This is a different variable!
    • MY_VARIABLE = 15 # Yet another different variable!
  4. Reserved Keywords: You cannot use Python's reserved keywords (like if, for, while, class, def, True, False, None) as variable names. These words have special meanings in Python, and trying to redefine them would confuse the interpreter. (Don't worry, you'll learn about these later!)

Best Practices (Should Follow):

  1. Descriptive Names: Choose names that clearly indicate the purpose or content of the variable. This is the most important best practice!
    • customer_name is far better than cn or x.
    • temperature_celsius is better than temp.
  2. Lowercase with Underscores (Snake Case): The widely accepted convention in Python (as per the PEP 8 style guide) is to use lowercase letters with words separated by underscores for readability. This is called "snake_case".
    • user_input_string
    • total_items_in_cart
    • Avoid camelCase (e.g., userInputString) which is common in JavaScript or Java, but not idiomatic Python for variables.
  3. Avoid Single Letters (Mostly): While x, y, i, j are sometimes acceptable as temporary loop counters or mathematical variables, avoid using them for important data that needs to be understood outside a very small context.
  4. Be Consistent: Once you choose a naming style (like snake_case), stick with it throughout your project. Consistency makes your code predictable and easier to follow.

{{VISUAL: diagram: a comparison table showing examples of good (snake_case, descriptive) vs. bad (camelCase, vague, starting with numbers, using keywords) variable names in Python.}}

Key Takeaways

  • Variables are named containers for data. They allow your program to store, reference, and manipulate information efficiently.
  • You assign values to variables using the = operator in Python.
  • Python variables are dynamically typed, meaning you don't explicitly state their data type; Python infers it from the value you assign.
  • Follow naming rules (starts with letter/underscore, alphanumeric) and best practices (snake_case, descriptive) for clean, readable code that others (and your future self!) will appreciate.

Understanding variables is the very first step toward writing useful and dynamic Python programs. They are the fundamental building blocks upon which all more complex operations are built. In the next pages, we'll explore the different types of data you can store in these variables!


Numbers: Int & Float

Numbers: Int & Float

Welcome back, future Pythonista! In our previous page, we dipped our toes into the world of variables. Now, it's time to dive into the most fundamental building blocks of almost any program: numbers. Python provides two primary numeric types for handling numerical data: integers (int) and floating-point numbers (float). Understanding these is crucial for everything from simple calculations to complex data analysis.

Let's break them down.

Integers (int): The Whole Story

Imagine counting apples, tracking a score in a game, or numbering pages in a book. For these scenarios, you're dealing with whole numbers – no fractions, no decimals. In Python, these are represented by the int data type.

What they are: Integers are positive or negative whole numbers (including zero) without any decimal component. Python's integers have arbitrary precision, meaning they can be as large as your computer's memory allows, unlike some other programming languages that limit integer size.

Declaring Integers: Assigning an integer value to a variable is straightforward:

# Positive integer
score = 100

# Negative integer
temperature = -5

# Zero
count = 0

# A really large integer (Python handles it effortlessly!)
population = 7800000000

To verify the type of a variable, Python offers the built-in type() function:

print(type(score))
print(type(temperature))

This will output:

<class 'int'>
<class 'int'>

{{VISUAL: diagram: A comparison table illustrating key characteristics and typical use cases for Python's int and float data types.}}

Basic Arithmetic with Integers

Python supports all the standard arithmetic operations you'd expect. Let's see them in action:

OperatorOperationExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication6 * 212
/Division15 / 35.0
//Integer Division15 // 43
%Modulo (Remainder)15 % 43
**Exponentiation2 ** 38

Let's test some of these in code:

x = 20
y = 7

# Addition
result_add = x + y
print(f"Addition: {result_add}") # Output: Addition: 27

# Subtraction
result_sub = x - y
print(f"Subtraction: {result_sub}") # Output: Subtraction: 13

# Multiplication
result_mul = x * y
print(f"Multiplication: {result_mul}") # Output: Multiplication: 140

# Standard Division (results in a float!)
result_div = x / y
print(f"Standard Division: {result_div}") # Output: Standard Division: 2.8571428571428577
print(f"Type of Standard Division: {type(result_div)}") # Output: Type of Standard Division: <class 'float'>

# Integer Division (discards the fractional part)
result_int_div = x // y
print(f"Integer Division: {result_int_div}") # Output: Integer Division: 2

# Modulo (remainder)
result_mod = x % y
print(f"Modulo: {result_mod}") # Output: Modulo: 6

# Exponentiation
result_exp = 2 ** 5
print(f"Exponentiation: {result_exp}") # Output: Exponentiation: 32

Notice a critical point: standard division (/) always returns a float, even if the result is a whole number (e.g., 10 / 2 gives 5.0). If you specifically need an integer result from division, use integer division (//).

Floating-Point Numbers (float): The Decimal World

When precision beyond whole numbers is required – think prices, measurements, or scientific calculations – you'll turn to floating-point numbers.

What they are: Floating-point numbers, or "floats," are numbers that have a decimal point. They can represent fractions and real numbers. Python stores these using a double-precision 64-bit format, which provides a good balance of range and precision for most applications.

Declaring Floats: You can declare a float simply by including a decimal point in the number:

# Positive float
price = 19.99

# Negative float
wind_speed = -12.5

# Float representing a whole number (still a float!)
distance = 100.0

# Using scientific notation (e for exponent)
# 3.0 x 10^8 (speed of light approximation)
speed_of_light = 3.0e8

Let's confirm their type:

print(type(price))
print(type(speed_of_light))

This will output:

<class 'float'>
<class 'float'>

{{VISUAL: diagram: A flowchart demonstrating the process of a Python arithmetic operation involving an integer and a float, highlighting the automatic type promotion to float.}}

Basic Arithmetic with Floats

Arithmetic operations on floats behave very similarly to integers, but the results will always be floats.

a = 15.5
b = 2.0

# Addition
print(f"Addition: {a + b}") # Output: Addition: 17.5

# Subtraction
print(f"Subtraction: {a - b}") # Output: Subtraction: 13.5

# Multiplication
print(f"Multiplication: {a * b}") # Output: Multiplication: 31.0

# Division
print(f"Division: {a / b}") # Output: Division: 7.75

# Exponentiation
print(f"Exponentiation: {a ** b}") # Output: Exponentiation: 240.25

One thing to be aware of with floats is precision issues. Due to how computers store floating-point numbers internally (binary representation), some decimal numbers cannot be represented exactly, leading to tiny inaccuracies. For most everyday tasks, this isn't a concern, but it's vital for high-precision scientific or financial calculations.

print(0.1 + 0.2) # Output: 0.30000000000000004 (not exactly 0.3)

Mixed-Type Operations: The Dominance of Floats

What happens if you combine an int and a float in an arithmetic operation? Python is smart enough to handle this gracefully. It will promote the integer to a float before performing the operation, and the result will always be a float.

integer_value = 10
float_value = 3.5

# Addition
mixed_add = integer_value + float_value
print(f"Mixed Addition: {mixed_add}") # Output: Mixed Addition: 13.5
print(f"Type of Mixed Addition: {type(mixed_add)}") # Output: Type of Mixed Addition: <class 'float'>

# Multiplication
mixed_mul = integer_value * float_value
print(f"Mixed Multiplication: {mixed_mul}") # Output: Mixed Multiplication: 35.0
print(f"Type of Mixed Multiplication: {type(mixed_mul)}") # Output: Type of Mixed Multiplication: <class 'float'>

This automatic type promotion ensures that you don't lose any precision when performing operations involving both integers and floats.

{{VISUAL: photo: A calculator displaying various numbers, some integers and some with decimal points, visually representing the concepts of int and float in everyday context.}}

Summary

  • Integers (int) are whole numbers, ideal for counts, indices, and discrete values. They have arbitrary precision.
  • Floating-point numbers (float) are numbers with decimal points, used for measurements, prices, and values requiring fractional precision.
  • Python supports standard arithmetic operations: +, -, *, /, //, %, **.
  • Standard division (/) always returns a float. Use integer division (//) for whole number results.
  • When an int and a float are combined in an operation, the int is promoted to a float, and the result is a float.

You've now got a solid grasp on how to work with numbers in Python. These fundamental data types will be constants in your programming journey. Next up, we'll explore another incredibly common and versatile data type: strings!


Text: String Data

Text: String Data

Imagine a world without text. No names, no messages, no instructions, no web pages. Pretty boring, right? In Python, just like in the real world, text is everywhere, and it's incredibly important. We use text to represent user input, display information, store names, communicate messages, and much more.

In programming, a sequence of characters, such as letters, numbers, and symbols, is called a string. Python has robust and flexible ways to handle these textual data types, making them a fundamental building block for almost any application.


What are Strings?

A string is an ordered sequence of characters. Each character in a string occupies a specific position, allowing you to access and manipulate them individually or in groups. Python treats strings as objects, which means they come with a set of built-in capabilities (methods) that we'll explore in more advanced chapters. For now, let's focus on the basics.

Creating Strings

You can create a string in Python by enclosing characters within single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """).

Single and Double Quotes

Most commonly, you'll use single or double quotes. Python doesn't have a preference; they are functionally identical. The main reason to choose one over the other is convenience when your string itself contains quotes.

# Using single quotes
my_string_1 = 'Hello, Python!'
print(my_string_1)

# Using double quotes
my_string_2 = "Welcome to the course."
print(my_string_2)

# Handling quotes within strings
message_1 = "He said, 'Python is fun!'"
print(message_1)

message_2 = 'It\'s a beautiful day.' # Using an escape character for single quote
print(message_2)

message_3 = "The book is titled \"Python for Beginners\"." # Using an escape character for double quote
print(message_3)

Notice how message_1 uses double quotes to enclose the string, allowing the single quote inside to be part of the text without issue. Conversely, message_2 uses an escape character (\) before the apostrophe to tell Python to treat it as a literal single quote, not the end of the string. We'll touch more on escape characters later.

Triple Quotes

Triple quotes are especially useful for multi-line strings or for docstrings (documentation strings) which describe functions, classes, and modules.

multi_line_string = '''
This is a string
that spans
multiple lines.
'''
print(multi_line_string)

another_multi_line = """
You can also use
triple double quotes
for the same purpose.
"""
print(another_multi_line)

Python preserves the line breaks and indentation exactly as they appear within the triple quotes.


Basic String Operations

Now that we know how to create strings, let's explore some fundamental operations you can perform on them.

1. Concatenation: Joining Strings

You can combine two or more strings together using the + operator. This process is called concatenation.

first_name = "Alice"
last_name = "Wonderland"

full_name = first_name + " " + last_name # Add a space in between
print(full_name) # Output: Alice Wonderland

greeting = "Hello"
name = "Bob"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, Bob!

{{VISUAL: diagram: illustrating string concatenation with two string blocks merging into one longer string block.}}

Remember, you can only concatenate strings with other strings. Trying to concatenate a string with a number (e.g., "Age: " + 30) will result in a TypeError. If you need to include numbers, convert them to strings first using str().

2. Indexing: Accessing Individual Characters

Strings are sequences, which means each character has an associated position, or index. Python uses zero-based indexing, meaning the first character is at index 0, the second at 1, and so on.

You can access individual characters using square brackets [] with the index number.

my_word = "Python"

# Positive indexing
print(my_word[0]) # Output: P (the first character)
print(my_word[1]) # Output: y
print(my_word[5]) # Output: n (the last character)

# Negative indexing
# You can also access characters from the end of the string using negative indices.
# -1 refers to the last character, -2 to the second to last, and so on.
print(my_word[-1]) # Output: n
print(my_word[-2]) # Output: o
print(my_word[-6]) # Output: P (the first character)

If you try to access an index that is out of range (e.g., my_word[6] or my_word[-7]), Python will raise an IndexError.

3. Slicing: Extracting Substrings

While indexing lets you grab a single character, slicing allows you to extract a portion (a "slice") of a string. The syntax for slicing is [start:end:step].

  • start: The index where the slice begins (inclusive). If omitted, defaults to 0.
  • end: The index where the slice ends (exclusive). If omitted, defaults to the end of the string.
  • step: How many characters to jump after retrieving one (defaults to 1).
full_phrase = "Python Programming"
Stuck on something here?
Aarav Sir explains any part — voice or chat — 24/7.

Basic slicing

print(full_phrase[0:6]) # Output: Python (characters from index 0 up to, but not including, 6) print(full_phrase[7:18]) # Output: Programming

Omitting start or end

print(full_phrase[:6]) # Output: Python (from beginning to index 6) print(full_phrase[7:]) # Output: Programming (from index 7 to the end) print(full_phrase[:]) # Output: Python Programming (the entire string)

Using negative indices in slicing

print(full_phrase[-11:-7]) # Output: Prog (from 'P' of Programming to 'g') print(full_phrase[-11:]) # Output: Programming (from 'P' of Programming to the end)

Slicing with a step

print(full_phrase[0:6:2]) # Output: Pto (every second character from index 0 to 6) print(full_phrase[::-1]) # Output: gnimmargorP nohtyP (reverses the string!)


{{VISUAL: diagram: showing a string with positive and negative indices labelled above and below each character, demonstrating how slicing selects a sub-segment.}}

#### 4. The `len()` Function: Getting String Length

The built-in `len()` function is used to get the number of characters (the length) in a string.

```python
my_sentence = "This is a sample sentence."
length = len(my_sentence)
print(f"The length of the string is: {length}") # Output: The length of the string is: 26

empty_string = ""
print(len(empty_string)) # Output: 0

Immutability of Strings

A critical concept to understand about Python strings is that they are immutable. This means that once a string is created, its content cannot be changed. You cannot modify individual characters within an existing string.

If you perform an operation that seems to "change" a string, what actually happens is that a new string is created with the desired modifications, and the original string remains untouched.

my_data = "immutable"
# Let's try to change the first character from 'i' to 'I'
# my_data[0] = 'I' # This would cause an error!

# Instead, you create a new string:
new_data = 'I' + my_data[1:]
print(new_data) # Output: Immutable
print(my_data)  # Output: immutable (original string is unchanged)

The original my_data still refers to "immutable", while new_data refers to a brand new string "Immutable".

{{VISUAL: diagram: comparing a mutable object (e.g., a list) where an element can be directly changed, versus an immutable object (e.g., a string) where modification always creates a new object.}}


Escape Characters Revisited

We briefly encountered escape characters (\) when discussing quotes. They allow you to include special characters in strings that would otherwise be difficult or impossible to type directly.

Here are a few common escape characters:

  • \n: Newline (moves cursor to the next line)
  • \t: Tab (inserts a horizontal tab)
  • \\: Backslash (inserts a literal backslash)
  • \': Single quote (inserts a literal single quote)
  • \": Double quote (inserts a literal double quote)
print("Hello\nWorld!")
# Output:
# Hello
# World!

print("Name:\tAlice") # Output: Name:   Alice

path = "C:\\Users\\Guest\\file.txt"
print(path) # Output: C:\Users\Guest\file.txt

If you have a string with many backslashes (like file paths or regular expressions) and don't want them to be interpreted as escape characters, you can use a raw string by prefixing the string literal with r or R:

raw_path = r"C:\Users\Guest\file.txt"
print(raw_path) # Output: C:\Users\Guest\file.txt (backslashes are treated literally)

You now have a solid understanding of how to create, access, and perform basic manipulations on string data. This is a fundamental skill, as strings are integral to interacting with users, displaying information, and processing textual data in Python. In later chapters, we'll dive into more advanced string methods for searching, replacing, formatting, and more!


Logic: Boolean Type

Logic: The Boolean Type

Welcome to the world of decision-making in programming! So far, we've explored how to store different kinds of data: numbers for calculations, and strings for text. But what about representing truth itself? What if your program needs to know if something is True or False?

Enter the Boolean data type, arguably the simplest yet most foundational data type for any programming language. Booleans are the bedrock of logic, allowing your programs to make decisions, control flow, and respond dynamically to different conditions.


What are Booleans?

At its core, the boolean data type represents one of two possible values: True or False. Think of it as a simple on/off switch, a yes/no answer, or a condition being met or not met.

In Python, True and False are keywords and are case-sensitive. They must start with a capital letter.

# Declaring boolean variables
is_logged_in = True
has_permission = False
is_admin = True

Let's check their type:

print(type(is_logged_in))
print(type(has_permission))

Output:

<class 'bool'>
<class 'bool'>

As you can see, Python recognizes these as bool types. Simple, right? But their power truly unfolds when we start using them in expressions.

Generating Booleans: Comparison Operators

While you can assign True or False directly, booleans are most often the result of an evaluation. The most common way to generate a boolean is by comparing values using comparison operators. These operators compare two values and return either True or False based on whether the comparison holds.

Here are the primary comparison operators in Python:

  • == (Equal to): Checks if two values are equal.
  • != (Not equal to): Checks if two values are not equal.
  • > (Greater than): Checks if the left value is greater than the right.
  • < (Less than): Checks if the left value is less than the right.
  • >= (Greater than or equal to): Checks if the left value is greater than or equal to the right.
  • <= (Less than or equal to): Checks if the left value is less than or equal to the right.

Let's see them in action:

# Equality and inequality
print(10 == 10)      # True
print(5 == 10)       # False
print("hello" == "Hello") # False (case-sensitive)
print("python" != "java") # True

# Greater than and less than
print(20 > 15)       # True
print(10 < 5)        # False
print(7.5 >= 7.5)    # True
print(8 <= 10)       # True

# Comparing different types (be cautious!)
print(10 == 10.0)    # True (Python handles numeric type comparison intelligently)
# print(10 == "10")  # False (different types, different values)

{{VISUAL: diagram: table showing common comparison operators, their symbols, and examples of how they evaluate to True or False}}

Notice how each of these expressions evaluates to a boolean value, which you can then store in a variable or use directly in a logical statement.

Combining Logic: Boolean Operators (and, or, not)

Sometimes, you need to combine multiple conditions to make a more complex decision. This is where logical operators (also known as boolean operators) come into play: and, or, and not.

  1. and Operator: The and operator returns True only if both operands (the values on either side of and) are True. If even one operand is False, the result is False.

    age = 25
    has_ticket = True
    
    can_enter_club = (age >= 18) and has_ticket
    print(f"Can enter club: {can_enter_club}") # True (25 >= 18 is True, True is True)
    
    age = 16
    can_enter_club = (age >= 18) and has_ticket
    print(f"Can enter club (age 16): {can_enter_club}") # False (16 >= 18 is False)
    
  2. or Operator: The or operator returns True if at least one of the operands is True. It only returns False if both operands are False.

    is_weekend = False
    has_day_off = True
    
    can_relax = is_weekend or has_day_off
    print(f"Can relax: {can_relax}") # True (has_day_off is True)
    
    is_weekend = False
    has_day_off = False
    can_relax = is_weekend or has_day_off
    print(f"Can relax (no day off): {can_relax}") # False (both are False)
    
  3. not Operator: The not operator is a unary operator, meaning it operates on a single operand. It simply negates the truth value of its operand. If an operand is True, not makes it False, and vice-versa.

    is_raining = True
    print(f"Is not raining: {not is_raining}") # False
    
    is_hungry = False
    print(f"Is not hungry: {not is_hungry}") # True
    

{{VISUAL: diagram: truth table for AND, OR, and NOT operators showing inputs and corresponding outputs}}

You can combine these operators for very complex logical conditions, often using parentheses to control the order of evaluation (just like in mathematics).

Booleans in Action: The Foundation of Control Flow

You might be wondering, "Why do I need True and False so much?" The answer lies in how programs make decisions. Booleans are fundamental to control flow statements, which dictate the order in which your program's code executes.

The most basic control flow statement is the if statement:

temperature = 28
is_hot = temperature > 25

if is_hot:
    print("It's a hot day! Stay hydrated.")
else:
    print("The weather is pleasant.")

Here, the if statement checks the value of is_hot. If is_hot is True, the code inside the if block executes. Otherwise, the code inside the else block executes. We'll delve much deeper into if statements later, but this gives you a glimpse into the indispensable role booleans play.

"Falsy" and "Truthy" Values (Advanced Concept)

An important concept in Python (and many other languages) is that certain values, when evaluated in a boolean context (like an if statement), are implicitly treated as True or False, even if they aren't explicitly bool types.

  • Falsy values are those that evaluate to False in a boolean context:

    • None
    • 0 (integer)
    • 0.0 (float)
    • Empty sequences: "" (empty string), [] (empty list), () (empty tuple), {} (empty dictionary), set() (empty set)
  • Truthy values are almost everything else. Any non-zero number, non-empty string, non-empty list, etc., will evaluate to True.

You can explicitly convert any value to a boolean using the bool() function:

print(bool(0))           # False
print(bool(10))          # True
print(bool(""))          # False
print(bool("Hello"))     # True
print(bool([]))          # False
print(bool([1, 2, 3]))   # True
print(bool(None))        # False

{{VISUAL: diagram: flowchart illustrating how Python evaluates different data types (numbers, strings, lists) to their "truthy" or "falsy" boolean equivalents}}

Understanding "falsy" and "truthy" values can lead to more concise code, but it's crucial to be aware of which values fall into which category to avoid unexpected behavior.


Booleans are simple in their definition but profound in their impact. They are the logical backbone of your programs, enabling them to navigate complex conditions and behave intelligently. As you progress, you'll find yourself using boolean logic in virtually every piece of code you write!


Data Types Exercises

Data Types Exercises: Putting It All Together

Welcome to the final page of our "Variables and Basic Data Types" chapter! Throughout this lesson, you've learned how to declare variables, understand Python's core data types—integers, floats, strings, and booleans—and perform fundamental operations on them.

Now, it's time to solidify that knowledge with some hands-on practice. The best way to learn programming is by doing, by writing code, making mistakes, and figuring out solutions. Think of these exercises not as tests, but as opportunities to explore and experiment in a safe environment.

How to Approach These Exercises

For each exercise, you'll find:

  1. The Problem: A clear description of what you need to achieve.
  2. Hints (Optional): Gentle nudges if you get stuck, pointing you towards relevant concepts.
  3. Expected Output/Key Learnings: What your code should ideally produce, or key points to consider in your solution.

We strongly encourage you to try solving each problem yourself first before peeking at any potential solutions or hints. Use a Python interpreter (like an interactive shell or a script you run) to write and test your code. Don't be afraid to make mistakes—they are incredibly valuable learning opportunities!


Exercise 1: Personal Profile & Simple Arithmetic

Problem:

Imagine you're creating a simple personal profile application.

  1. Declare a variable name and assign it your first name (as a string).
  2. Declare a variable age and assign it your current age (as an integer).
  3. Declare a variable height_cm and assign it your height in centimeters (as a float).
  4. Calculate your age in five years and store it in a new variable age_in_five_years.
  5. Calculate your height in inches (1 inch = 2.54 cm) and store it in height_inches.
  6. Print a summary using an f-string that looks something like this: "Hello, [Name]! You are [Age] years old and [Height_cm] cm tall. In five years, you will be [Age_in_five_years] years old. Your height in inches is approximately [Height_inches] inches."

Hints:

  • Remember how to declare variables for different types.
  • Use + for addition and / for division.
  • F-strings (f"...") are your friend for formatting output.

{{VISUAL: diagram: flow of Python code execution for variable declaration and simple arithmetic, showing assignment and operation steps.}}

Expected Output/Key Learnings:

Your output should display your personalized details. Pay attention to the data types you're working with. age and age_in_five_years should be integers, height_cm and height_inches should be floats. Ensure your f-string correctly embeds all variables.


Exercise 2: Type Conversion & Basic Validation

Problem:

You're building a simple program that takes a user's favorite number as input and performs a calculation.

  1. Simulate getting user input for their favorite number by assigning a string like "42" to a variable called fav_num_str.
  2. Try to multiply fav_num_str by 2. What happens? (Don't just guess; write the code and observe the error!)
  3. Now, convert fav_num_str to an integer and store it in a new variable fav_num_int.
  4. Multiply fav_num_int by 2 and store the result in doubled_fav_num.
  5. Print both fav_num_str and doubled_fav_num along with descriptive labels.
  6. Bonus: What if the user entered "hello" instead of "42"? Try converting "hello" to an integer. What kind of error do you get? This is important for understanding robust user input!

Hints:

  • Use int() for converting to an integer.
  • Remember that multiplying a string by an integer repeats the string.
  • Python's error messages are often very descriptive. Read them carefully!

Expected Output/Key Learnings:

You should observe a TypeError when trying to multiply fav_num_str by 2 directly (it will instead repeat the string). After conversion, the multiplication should work as expected. The bonus part will introduce you to ValueError, a common error when type conversions fail because the string content isn't suitable for the target type. This exercise highlights the crucial role of type conversion when dealing with input that Python initially treats as strings.


Exercise 3: String Power & Boolean Logic

Problem:

Let's work with some text and logical conditions.

  1. Declare a variable product_name and assign it the string "Python Programming Course".
  2. Declare a variable price and assign it 49.99 (float).
  3. Declare a variable is_available and set it to True.
  4. Use an f-string to print an advertisement message: "🚀 Special Offer: Get the [Product Name] for only $[Price]! Status: [Available/Not Available]" (Hint: You'll need an if/else statement or a conditional expression to display "Available" or "Not Available" based on is_available.)
  5. Check if the product_name contains the word "Python". Store the result in a boolean variable contains_python.
  6. Check if the product_name starts with "Java". Store the result in a boolean variable starts_with_java.
  7. Print the values of contains_python and starts_with_java with clear labels.
  8. Combine is_available and contains_python using the and operator. Print the result: "Is it a Python course AND available? [Result]"

{{VISUAL: diagram: truth table for basic boolean operations like AND, OR, and NOT, showing input and output combinations.}}

Hints:

  • String methods like .find() or the in operator can check for substrings.
  • String methods like .startswith() are useful.
  • Remember and, or, not for boolean operations.
  • A concise way to convert True/False to "Available"/"Not Available" in an f-string is: { "Available" if is_available else "Not Available" }.

Expected Output/Key Learnings:

You'll see a dynamically generated advertisement. contains_python should be True, and starts_with_java should be False. The combined boolean expression should show True if is_available and contains_python are both True. This exercise reinforces string manipulation, conditional logic, and the practical application of boolean data types.


Exercise 4: The Order Calculator (Challenge!)

Problem:

You're building a mini-calculator for a simple online order.

  1. Declare a variable item_quantity and set it to 3 (integer).
  2. Declare a variable item_price and set it to 25.50 (float).
  3. Declare a variable has_discount_code and set it to True (boolean).
  4. Calculate the subtotal (quantity * price).
  5. If has_discount_code is True, apply a 10% discount to the subtotal. Store the final price in total_price. Otherwise, total_price is just the subtotal.
  6. Declare a variable customer_name and set it to "Alice".
  7. Print a formatted receipt using an f-string that includes:
    • Customer Name
    • Item Quantity
    • Item Price (formatted to two decimal places)
    • Subtotal (formatted to two decimal places)
    • Whether a discount was applied (True or False, or "Yes"/"No")
    • Total Price (formatted to two decimal places)

Hints:

  • Use an if/else statement for applying the discount.
  • To format a float to two decimal places in an f-string, use :{.2f}. E.g., f"Price: ${price:.2f}".
  • A 10% discount means multiplying by 0.90 (or 1 - 0.10).

{{VISUAL: photo: a programmer's desk with a laptop displaying Python code, a cup of coffee, and a notebook, symbolizing a focused coding session.}}

Expected Output/Key Learnings:

Your receipt should clearly show all calculated values, correctly formatted. This exercise combines all the basic data types (integers, floats, booleans, strings) and fundamental operations (arithmetic, conditional logic, string formatting). It's a great demonstration of how these basic building blocks come together to create useful mini-applications.


Reflect and Debug

If your code didn't work as expected, that's perfectly normal! Here's how to learn from it:

  1. Read the Error Message: Python's error messages tell you what went wrong and where.
  2. Check Your Types: Are you trying to perform an operation on incompatible types (e.g., adding a string and an integer without conversion)?
  3. Inspect Variable Values: Use print() statements to check the value of variables at different points in your code. This helps you trace the flow.
  4. Simplify: If a complex piece of code isn't working, break it down into smaller, simpler parts and test each part individually.

Congratulations on completing the exercises for this chapter! You've taken significant steps in understanding the core components of Python programming. Keep practicing, keep exploring, and keep building!

In this chapter

  • 1.What are Variables?
  • 2.Numbers: Int & Float
  • 3.Text: String Data
  • 4.Logic: Boolean Type
  • 5.Data Types Exercises

Frequently asked questions

What are Variables?

Imagine you're baking a cake. You need sugar, flour, eggs, and milk. Instead of remembering the exact amount of each ingredient every time you use it (e.g., "700 grams of white crystalline substance," "500 grams of finely ground grain"), you label containers: one for "sugar," one for "flour," and so on. When the recipe

What is Numbers: Int & Float?

Welcome back, future Pythonista! In our previous page, we dipped our toes into the world of variables. Now, it's time to dive into the most fundamental building blocks of almost any program: numbers. Python provides two primary numeric types for handling numerical data: **integers** (`int`) and **floating-point numbers

What is Text: String Data?

Imagine a world without text. No names, no messages, no instructions, no web pages. Pretty boring, right? In Python, just like in the real world, text is everywhere, and it's incredibly important. We use text to represent user input, display information, store names, communicate messages, and much more.

What is Logic: Boolean Type?

Welcome to the world of decision-making in programming! So far, we've explored how to store different kinds of data: numbers for calculations, and strings for text. But what about representing truth itself? What if your program needs to know if something is `True` or `False`?

What is Data Types Exercises?

Welcome to the final page of our "Variables and Basic Data Types" chapter! Throughout this lesson, you've learned how to declare variables, understand Python's core data types—integers, floats, strings, and booleans—and perform fundamental operations on them.

More chapters in Python Programming

Want the full Python Programming experience?

Every chapter. Interactive lessons. AI teacher on tap. Study Lab for any photo or PDF. 3-day free trial — no credit card.

1000s of students
100% NCERT-aligned
Powered by AI

Install Learn Skill

Add to home screen for the best experience