Chapter 2: Python Basics Exercises

Hands-on exercises to practice Python syntax, variables, and data types

Chapter 2 Concepts

This chapter covers the fundamental building blocks of Python programming:

Variables Data Types Type Conversion User Input Basic Operations String Manipulation
Exercise 1

Variable Swap

Create a program that swaps the values of two variables.

# Start with these variables
a = 10
b = 20

# Your code to swap values
# Print both variables after swapping
  • Initialize two variables with different values
  • Swap their values without using a temporary variable
  • Print the values before and after swapping
  • Hint

    You can use tuple unpacking: a, b = b, a

    Exercise 2

    Data Type Exploration

    Create variables of different data types and examine their properties.

    # Create variables of different types
    integer_var = 10
    float_var = 3.14
    string_var = "Hello"
    bool_var = True

    # Print their types and values
    # Use the type() function
  • Create variables of int, float, string, and bool types
  • Print the type of each variable using type()
  • Try converting between types using int(), float(), str()
  • Exercise 3

    User Input Processing

    Create a program that takes user input and processes it.

    # Ask user for their name and age
    name = input("What is your name? ")
    age = input("How old are you? ")

    # Calculate year of birth
    # Print a personalized message
  • Use input() to get user's name and age
  • Convert age to integer
  • Calculate approximate year of birth
  • Print a message like "Hello [name], you were born in [year]"
  • Exercise 4

    String Manipulation

    Practice various string operations and methods.

    # Start with this string
    text = " Python Programming is Fun! "

    # Perform these operations:
    # 1. Remove whitespace from both ends
    # 2. Convert to lowercase
    # 3. Replace "Fun" with "Awesome"
    # 4. Split into words
  • Use strip() to remove whitespace
  • Use lower() to convert to lowercase
  • Use replace() to change words
  • Use split() to create a list of words
  • Print each result
  • Exercise 5

    Type Conversion Challenge

    Practice converting between different data types.

    # Start with these values
    num_str = "123"
    pi_str = "3.14"
    number = 100

    # Convert between types
    # 1. Convert num_str to integer
    # 2. Convert pi_str to float
    # 3. Convert number to string
    # 4. Try converting "hello" to integer (handle the error)
  • Convert string to integer
  • Convert string to float
  • Convert integer to string
  • Try invalid conversion and handle ValueError
  • Exercise 6

    Simple Calculator

    Create a basic calculator that takes two numbers and an operator.

    # Get two numbers and an operator from user
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))

    # Perform calculation based on operator
    # Print the result
  • Get two numbers from user (convert to float)
  • Get an operator (+, -, *, /)
  • Use if/elif to perform the correct operation
  • Print the equation and result: "5.0 * 3.0 = 15.0"
  • Exercise 7

    String Formatting Practice

    Practice different ways to format strings in Python.

    # Create variables
    item = "book"
    price = 15.99
    quantity = 3

    # Format strings using:
    # 1. f-strings
    # 2. .format() method
    # 3. % formatting
    # Print all three versions
  • Use f-string: f"You bought {quantity} {item}s for ${price*quantity:.2f}"
  • Use format: "You bought {} {}s for ${:.2f}".format(quantity, item, price*quantity)
  • Use % formatting: "You bought %d %ss for $%.2f" % (quantity, item, price*quantity)
  • Compare the results
  • Exercise 8

    Boolean Expressions

    Practice using boolean expressions and comparisons.

    # Get user input
    age = int(input("Enter your age: "))
    temperature = float(input("Enter temperature: "))

    # Check these conditions:
    # 1. Is age greater than or equal to 18?
    # 2. Is temperature between 20 and 30 degrees?
    # 3. Is age not equal to 30?
    # Print the results
  • Get age and temperature from user
  • Check if age is >= 18
  • Check if temperature is between 20 and 30 (inclusive)
  • Check if age is not equal to 30
  • Print the results of each check
  • Exercise 9

    Dynamic Typing Demonstration

    Demonstrate Python's dynamic typing feature.

    # Create a variable and change its type
    variable = 10
    print(type(variable))

    # Change to string
    variable = "Hello"
    print(type(variable))

    # Change to float
    variable = 3.14
    print(type(variable))

    # Change to boolean
    variable = True
    print(type(variable))
  • Create a variable and assign it an integer value
  • Print its type
  • Reassign to a string and print type
  • Reassign to a float and print type
  • Reassign to a boolean and print type
  • Hint

    Python is dynamically typed, meaning variable types are determined at runtime and can change.