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.
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 everTrueorFalse, 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
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
| Idea | Remember |
|---|---|
| Types | int, float, str, bool; check with type() |
| Variables | a name that points to a value; snake_case |
| Division | / always gives a float; round floats before comparing |
| Strings | immutable; methods return a new string |
| Indexing | starts at 0; last index is len - 1 |
| Slicing | [start:stop:step], stop not included |
| Conversion | int(), 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.
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.
