Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Basics

Python Data Types, Variables and Strings: Indexing, Slicing and f-strings

What a data type is (a shop receipt has four), variables as labels, numbers and float surprises, string methods, indexing and slicing on "Hello, World", f-strings and type conversion, all with real output.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Basics

What you will learn

  • Name Python's simple types (int, float, str, bool) and check them with type()
  • Explain a variable as a name that points to a value, and swap two values in one line
  • Index and slice a string, including negative indexes and steps
  • Build text with f-strings and convert between types with int, float and str

Before you start

  • Your First Python Program
  • Run a Python File and Read the Error

Every Python program is made of values and the names you give them. AI tools can write a lot of this code for you, and that's fine. But you can't check code you can't read, and you can't prompt well for something you don't understand. So these small pieces are worth learning properly.

What a data type is

Think about a shop receipt. The item says bread, which is text. The quantity is 2, a whole number. The price is 1.50, a number with a decimal point. Paid is yes or no, only two possible answers.

That's four kinds of value, and you treat them differently. You can multiply a price by a quantity, but you'd never multiply the word bread. A data type tells Python what kind of value it has and what it can do with it. The built-in type() function tells you the type of any value:

print(type(42))
print(type(3.14))
print(type("hello"))
print(type(True))
print(type([1, 2, 3]))
print(type((1, 2, 3)))
print(type({"name": "Alice"}))
print(type({1, 2, 3}))
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>

Read <class 'int'> as "this is an int". The first four are the simple types:

  • int, an integer: a whole number, positive, negative or zero.
  • float, a number with a decimal point.
  • str, a string: text in quotes.
  • bool, a boolean: only ever True or False, with a capital first letter.

The last four hold several values. Square brackets make a list (ordered, you can change it), round brackets a tuple (you can't change it), curly brackets with keys and values a dict, and curly brackets with only values a set (each value once). They get their own article: Python lists, tuples, sets and dicts.

Numbers

print(10 + 3)
print(10 - 3)
print(10 * 3)
print(10 / 3)
print(10 // 3)
print(10 % 3)
print(2 ** 10)
print(type(10 / 2))
13
7
30
3.3333333333333335
3
1
1024
<class 'float'>

A single slash is division. A double slash is floor division: share 10 items across 3 groups and each group gets 3. The percent sign is modulo, what's left over: 1 item. 2 ** 10 is 2 to the power of 10. And remember the last line: a single slash always gives a float, even when 10 divides by 2 exactly.

When decimals surprise you

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))
print(0.1 + 0.2 == 0.3)
print(round(0.1 + 0.2, 2) == 0.3)
0.30000000000000004
0.3
False
True

It isn't a bug. Computers store decimals in binary, and most decimals can't be stored exactly, so a tiny gap shows up. == asks whether two values are the same, and the raw sum isn't. When you compare decimals, round them first.

Variables are labels

Think of a sticky label. You write a name on it, stick it on a value, and from then on you can ask for the value by name.

name = "Alice"
age = 30
is_active = True

print(name)
print(age)
print(is_active)
Alice
30
True

Python reads the right side first and makes the value, then the left side gives it a name. So this = doesn't ask a question; it means "give this name to this value". Notice you never said which type. Python works it out from the value.

Naming rules and style

Normal variables use snake case: small letters with underscores, like user_name. A name like is_active tells you it holds True or False. MAX_RETRIES in capitals is a constant, a value you don't plan to change; that's only a convention. One real rule: a name can't start with a digit.

2nd_place = "Bob"
print(2nd_place)
  File "S01L02_Essentials\bad_name.py", line 1
    2nd_place = "Bob"
    ^
SyntaxError: invalid decimal literal

Dynamic typing and multiple assignment

x = 10
print(x, type(x))

x = "hello"
print(x, type(x))
10 <class 'int'>
hello <class 'str'>

The same label moves from 10 to "hello". The type belongs to the value, so a name can point to anything. That's flexible, but a name that changes type halfway through makes a program harder to read.

a, b, c = 1, 2, 3
print(a, b, c)

a, b = b, a
print(a, b, c)

x = y = 0
print(x, y)
1 2 3
2 1 3
0 0

a, b = b, a is the useful one. Python takes both values on the right first, then hands them out, so they swap without an extra variable.

String basics

s1 = 'hello'
s2 = "world"

print(s1 + " " + s2)
print("-" * 20)
print(len(s1))
print(s1.upper())
print("  hi  ".strip())
print("hello world".title())
print("hello".replace("l", "L"))
hello world
--------------------
5
HELLO
hi
Hello World
heLLo

Single or double quotes both work. + joins, * repeats, len gives the length. Methods are functions you call on a value with a dot: upper, strip (spaces off both ends), title and replace.

Every character has an index

The string Hello, World has 12 characters with indexes 0 to 11 and negative indexes -12 to -1; the slice s[0:5] covers indexes 0 to 4 and stops before index 5, the comma index from end H0-12 e1 l2 l3 o4 ,5 space6 W7-5 o8 r9 l10 d11-1 s[0:5] gives "Hello" stop index 5 is not included
Indexes start at 0. A slice runs from its start up to, but not including, its stop.
s = "Hello, World"

print(len(s))
print(s[0])
print(s[4])
print(s[-1])
print(s[11])
print(s[12])
12
H
o
d
d
Traceback (most recent call last):
  File "S01L02_Essentials\indexing.py", line 8, in <module>
    print(s[12])
          ~^^^^
IndexError: string index out of range

The comma and the space count, so there are 12 characters. Indexes start at 0, and -1 counts from the end. Twelve characters means indexes 0 to 11, so s[12] doesn't exist. The last index is always the length minus one.

Strings can't be changed

word = "hello"
print(word.upper())
print(word)

word = word.upper()
print(word)

word[0] = "J"
HELLO
hello
HELLO
Traceback (most recent call last):
  File "S01L02_Essentials\immutable.py", line 8, in <module>
    word[0] = "J"
    ~~~~^^^
TypeError: 'str' object does not support item assignment

Strings are immutable. upper() made a new string and left the original alone. To keep the new one, assign it: the label moves to the new string. Changing one letter in place isn't allowed.

Slicing

s = "Hello, World"

print(s[0:5])
print(s[7:])
print(s[:5])
print(s[-5:])
print(s[3:3])
print(s[0:100])
Hello
World
Hello
World

Hello, World

Read s[0:5] as "from index 0, up to but not including index 5". Five is a position, not a count. Leave out the stop and you go to the end; leave out the start and you begin at 0. s[3:3] starts and stops at the same place, so you get an empty string, the blank line. And s[0:100] goes far past the end with no error. An index past the end is an error; a slice past the end just gives you what's there.

Slicing with a step

s = "Hello, World"

print(s[::2])
print(s[0:5:2])
print(s[::-1])
print(s[-5:])
Hlo ol
Hlo
dlroW ,olleH
World

The third value is the step. s[::2] takes indexes 0, 2, 4 and so on (the space is a character too). A step of -1 walks backwards, so s[::-1] reverses the string. You'll see that one often.

f-strings

name = "Alice"
age = 30
price = 9.5

print(f"Hello {name}, you are {age}")
print(f"Next year: {age + 1}")
print(f"{name.upper()} pays {price:.2f}")
print("Hello {}, you are {}".format(name, age))
print("Hello %s, you are %d" % (name, age))
Hello Alice, you are 30
Next year: 31
ALICE pays 9.50
Hello Alice, you are 30
Hello Alice, you are 30

Put an f before the quote and your values in curly brackets. The brackets can hold an expression or a method call, and :.2f shows two decimals. The last two lines are older ways, .format and %, which you'll see in older code. In your own code, use an f-string; it's the easiest to read.

Type conversion

print(int("42") + 8)
print(float("3.5") + 1)
print(str(42) + "!")
print(int(3.9))
print(float(5))
print(int(float("3.9")))
50
4.5
42!
3
5.0
3

int(3.9) gives 3. It doesn't round; it cuts the decimal part off. You can chain conversions, and the inside runs first. Without conversion, things go wrong in two different ways:

age = "30"
print(age + 1)
Traceback (most recent call last):
  File "S01L02_Essentials\bad_convert.py", line 2, in <module>
    print(age + 1)
          ~~~~^~~
TypeError: can only concatenate str (not "int") to str
print(int("hello"))
Traceback (most recent call last):
  File "S01L02_Essentials\bad_int.py", line 1, in <module>
    print(int("hello"))
          ~~~^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'hello'

A TypeError means the types don't fit together. A ValueError means the type was fine, but this value can't be converted.

True and False from any value

print(bool(0))
print(bool(1))
print(bool(""))
print(bool("hi"))
print(bool(0.0))
print(bool([]))
False
True
False
True
False
False

Zero and empty things are False. That becomes handy once you write conditions and loops.

Quick recap

IdeaRemember
Typesint, float, str, bool; check with type()
Variablesa name that points to a value; snake_case
Division/ always gives a float; round floats before comparing
Stringsimmutable; methods return a new string
Indexingstarts at 0; last index is len - 1
Slicing[start:stop:step], stop not included
Conversionint(), float(), str(), bool()

Try it yourself

Put your full name in a variable. Print your first name with a slice, print your name reversed, then put it in a sentence with an f-string.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 6 of 48

Previous
Run a Python File and Read the Error: Tracebacks in Three Steps
Next post
Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Python for AI: The Five Tools You Actually Need

The small part of Python that carries most AI code: dicts and JSON, typed functions with a dataclass, comprehensions and f-strings, environment variables for keys, and try/except for replies that are not JSON. Three standard-library scripts on four support tickets.

Thinking Like a Python Architect in an AI-First World

Coding is laying bricks; architecting is deciding how the pieces fit. A two-line average function shows why someone still has to understand the code an AI tool writes.

Your First Python Program: print, Comments, sep and end

Five tiny files: print and quotes, top-to-bottom order, # comments, several values with sep and end, and the SyntaxError one missing quote causes. Every output is from a real run.

Set Up PyCharm for Python: Install, First Project and First Run

Install PyCharm, create a Pure Python project, and understand the two words that confuse beginners: the interpreter (the cook) and .venv (the project's own shelf). Then run a file and read the exit code.

On this page

  • What a data type is
  • Numbers
  • When decimals surprise you
  • Variables are labels
  • Naming rules and style
  • Dynamic typing and multiple assignment
  • String basics
  • Every character has an index
  • Strings can't be changed
  • Slicing
  • Slicing with a step
  • f-strings
  • Type conversion
  • True and False from any value
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.