Introduction to Python and Basic Data Types

SA
StudyAI Editorial
Reviewed by StudyAI tutors
· Published Updated

From the https://youtu. curriculum

Introduction to Python and Basic Data Types

TL;DR

Python is a popular, easy-to-read programming language that lets you tell computers what to do. At its core, Python handles different types of information, like numbers and text, which are called data types. Understanding these data types is essential for writing effective and error-free code.

1. The Mental Model

Think of Python as a set of instructions you're giving to a very obedient, but unintelligent, assistant. This assistant needs you to be very specific about what kind of information you're giving it and what you want it to do with that information.

2. The Core Material

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. This means you don't need to put semicolons at the end of every line, and the way you indent your code actually matters.

Getting Started with Python

Young professional woman working on a laptop in an office setting, concentrating on her task.
Photo by cottonbro studio on Pexels

You don't need a huge setup to start. You can use an online interpreter or install Python on your computer. When you run Python, you're interacting with its "interpreter," which executes your code line by line.

Let's look at the "Hello, World!" program, which is the traditional first step in learning any new language:

print("Hello, World!")

When you run this, Python simply displays Hello, World! on your screen. The print() part is a built-in function that outputs data.

Variables: Naming Your Data

Close-up of colorful JavaScript code displayed on a computer monitor, ideal for tech-themed projects.
Photo by Rashed Paykary on Pexels

A variable is like a named container for a piece of information. You give it a name, and then you can store different kinds of data in it.

message = "Welcome to Python!" # 'message' is the variable name
print(message)

In this example, message holds the text "Welcome to Python!". You can change what's inside a variable at any time.

age = 30
print(age)

age = 31 # Now 'age' holds a different value
print(age)

Basic Data Types in Python

Vibrant and engaging code displayed on a computer screen, showcasing programming concepts.
Photo by Seraphfim Gallery on Pexels

Python automatically figures out what kind of data you're storing. Here are the most common basic types:

Numbers

There are two main types of numbers you'll use:

  • Integers (int): Whole numbers, positive or negative, without decimals.
    python my_integer = 10 another_integer = -5
  • Floating-point numbers (float): Numbers that have a decimal point.
    python my_float = 3.14 another_float = 0.5

You can perform standard math operations:

a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333... (always a float)
print(a // b) # Floor division: 3 (gets the whole part)
print(a % b) # Modulo: 1 (gets the remainder)

Strings

Strings (str) are sequences of characters, like letters, numbers, or symbols. You define them using single quotes (') or double quotes (").

greeting = "Hello"
name = 'Alice'
multiline_string = """This is a string
that spans multiple lines."""

print(greeting + ", " + name + "!") # You can combine (concatenate) strings

Booleans

Booleans (bool) represent truth values: True or False. They're fundamental for making decisions in your code.

is_sunny = True
is_raining = False

print(is_sunny)
print(is_raining)

You'll use these in conditional statements (which we'll cover later) to control the flow of your program.

Checking Data Types

Close-up of a person using a laptop and reviewing documents with a smartphone on a wooden table.
Photo by Kampus Production on Pexels

You can always check the type of a variable using the type() function.

x = 10
y = 3.14
z = "Python"
is_active = True

print(type(x))
print(type(y))
print(type(z))
print(type(is_active))

This will output p```mermaid graph TD A["Start: Writing Python Code"] --> B{"Need to store information?"} B -- "Yes" --> C["Choose a Variable Name"] C --> D["Assign Value to Variable"] D --> E{{"What kind of information?"}} E -- "Whole Number" --> F["int(e.g.,age = 30)"] E -- "Decimal Number" --> G["float(e.g.,price = 19.99)"] E -- "Text/Characters" --> H["str(e.g.,name = 'Bob')"] E -- "True/False Value" --> I["bool(e.g.,is_valid = True)"] F --> J["Use Variable in Program"] G --> J H --> J I --> J B -- "No" --> K["Work directly with values (e.g.,print(5 + 3)`)"]
K --> L["Continue Coding"]
J --> L
L --> M["End: Program Logic"]


## 3. Worked Example
Let's build a small snippet that calculates a simple bill and uses different data types.

```python
# Cafe billing system

# --- Inputs (using different data types) ---
coffee_price = 3.50        # float
sandwich_price = 7.99      # float
customer_name = "Jamie"    # string
has_discount = True        # boolean
discount_percentage = 0.10 # float (10%)

# --- Calculations ---
num_coffees = 2            # int
num_sandwiches = 1         # int

subtotal_coffee = coffee_price * num_coffees
subtotal_sandwich = sandwich_price * num_sandwiches

total_bill = subtotal_coffee + subtotal_sandwich

# Apply discount if applicable
if has_discount:
    total_bill = total_bill * (1 - discount_percentage)
    print(f"Applying {discount_percentage*100}% discount for {customer_name}.")
else:
    print(f"No discount applied for {customer_name}.")

# --- Output ---
print(f"Hello, {customer_name}!")
print(f"Your coffee subtotal: ${subtotal_coffee:.2f}")
print(f"Your sandwich subtotal: ${subtotal_sandwich:.2f}")
print(f"Your final bill is: ${total_bill:.2f}")

This code first sets up prices and customer info. It then calculates subtotals based on int quantities, sums them for total_bill (a float), and conditionally applies a float discount if has_discount (a boolean) is True. Finally, it prints a user-friendly summary using str values.

4. Key Takeaways

  • Python is a user-friendly language that's easy to read and write.
  • Variables are named containers used to store different kinds of data.
  • Basic data types include integers (int), floating-point numbers (float), strings (str), and Booleans (bool).
  • int is for whole numbers, float is for numbers with decimal points.
  • str is for any text, enclosed in single or double quotes.
  • bool is for True or False values, used for making decisions.
  • You can check a variable's data type with the type() function.

Common Mistakes to Avoid:
- Forgetting quotes around strings (e.g., name = John instead of name = "John").
- Mixing data types unexpectedly, like trying to add a number and a string directly without converting one (e.g., print(5 + "apples")).
- Using variable names that aren't descriptive (e.g., x = 5 when age = 5 is clearer).
- Confusing integer division (//) with regular division (/) when you need a specific type of result.

5. Now Try It

Create a short Python script that:
1. Stores your favorite movie title in a string variable.
2. Stores its release year (an integer) in another variable.
3. Stores its average rating (a float, e.g., 8.5) in a third variable.
4. Stores whether you recommend it (True or False) in a boolean variable.
5. Prints out each piece of information, clearly labeled, using f-strings (like print(f"Title: {movie_title}")).

Success looks like: Seeing your movie details printed clearly on the screen, each value correctly corresponding to its assigned variable and data type.

Frequently asked about Introduction to Python and Basic Data Types

Python is a popular, easy-to-read programming language that lets you tell computers what to do. At its core, Python handles different types of information, like numbers and text, which are called data types. Read the full notes above for the details.

Introduction to Python and Basic Data Types is a core topic in https://youtu.. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes. Every note in the StudyAI Campus Hub is free to read. Create a free account if you want to clone the full plan, generate your own notes from your textbook, or get AI-powered practice quizzes and flashcards.

Get the full https://youtu. curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Create Free Account