Skip to content
beginner

Working with Numbers and Strings

Every value in Python carries a type, and every type has rules about what you can do with it. Numbers compute. Strings reshape. The moment you learn to…

Published 2026-05-11Updated 2026-09-158 min read
Elegant library with people studying, surrounded by wooden shelves and classical architecture.
Elegant library with people studying, surrounded by wooden shelves and classical architecture. Photo by Genaro Servín on Pexels.

Every value in Python carries a type, and every type has rules about what you can do with it. Numbers compute. Strings reshape. The moment you learn to check what you're holding, use an operation that fits it, and convert deliberately at the boundary, you stop fighting the language and start building with it.

By the end of this tutorial, you'll do basic math, reshape text, convert between numbers and strings, and combine them without tripping over Python's type rules. Let's start with the smallest useful pieces.

What Are Numbers and Strings in Python?

Before we use them, let's name what we're holding.

Numbers are values you can count or measure. Python has two main numeric types:

  • Integers: whole numbers like 5, -3, or 100.
  • Floats: numbers with a decimal point, like 3.14, -0.5, or 2.0.

Strings are pieces of text. A string is a sequence of characters wrapped in quotes:

"Hello, world!"
"42"
"Python is fun!"

Notice that 42 and "42" are different things. One is a number you can do math on; the other is text that happens to look like a number. That distinction drives most of the surprises in this tutorial.

Almost every program needs both. Scores, prices, and ages are numbers. Names, messages, and instructions are strings. If you've already covered Python Variables and Data Types, this is where those types start doing real work.

Using Numbers: Basic Math in Python

Python does arithmetic like a calculator, with a few operators you should know:

  • Addition: +
  • Subtraction: -
  • Multiplication: *
  • Division: /
print(2 + 3)      # 5
print(10 - 4)     # 6
print(6 * 7)      # 42
print(8 / 2)      # 4.0
5
6
42
4.0

Notice the last line: 8 / 2 prints 4.0, not 4. In Python, division always returns a float, even when the result looks like a whole number. That's not a bug—it's a deliberate rule that keeps division predictable.

More Math Operations

Python adds three operators that a plain calculator often hides:

  • Exponentiation: ** for powers
  • Integer division: // for the whole-number part
  • Modulo: % for the remainder
print(2 ** 3)   # 8 (2 to the power of 3)
print(7 // 2)   # 3 (integer division)
print(7 % 2)    # 1 (remainder)
8
3
1

These three are workhorses. Integer division splits things into even groups, and modulo tells you what's left over—which is exactly how you check whether a number is even or odd.

Knowledge check

Check your understanding

Answer this question before you continue.

What does this code print?
Output Prediction

Focus: Use modulo to predict the remainder of integer division.

print(7 % 2)

Integers vs. Floats

Integers and floats can participate in arithmetic together. When you mix them, the result is a float:

print(5 + 2.5)    # 7.5
7.5

That compatibility rule stops at numbers. It does not extend to strings. An integer and a float are both numeric, so Python promotes the result to a float. A string is a different kind of value entirely, and Python will not silently guess how to combine it with a number—you'll see that wall in a moment.

Everyday uses are everywhere: current_year - birth_year for an age, coffee_price + muffin_price for a total, (score1 + score2 + score3) / 3 for an average.

Knowledge check

Check your understanding

Answer this question before you continue.

What does this code print?
Output Prediction

Focus: Predict the result and type-like display of division in Python.

print(8 / 2)

Working with Strings: Handling Text

Strings are how Python stores text. You create one by wrapping characters in quotes:

greeting = "Hello, world!"
print(greeting)
Hello, world!

You can use single quotes ('Hello') or double quotes ("Hello"). Pick one and stay consistent. The only rule that matters: the opening and closing quotes must match.

Simple Python String Operations

Here are the string operations you'll reach for constantly.

Joining (concatenation) with +:

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)
Ada Lovelace

Repeating with * and a number:

laugh = "ha"
print(laugh * 3)
hahaha

Getting the length with len():

message = "Python"
print(len(message))
6

Changing case with .upper() and .lower():

word = "Python"
print(word.upper())
print(word.lower())
PYTHON
python

Checking for a substring with the in keyword:

sentence = "Python is fun!"
print("fun" in sentence)
True

Knowledge check

Check your understanding

Answer this question before you continue.

Which expression produces the string `hahaha`?
Single Choice

Focus: Select the string operation that repeats text a specified number of times.

Reshaping Text: Strip and Split

Manipulating a string usually means cleaning it up or breaking it into pieces. Two methods handle most of that work.

.strip() removes extra spaces from the start and end. .split() breaks a string into a list of pieces wherever a separator appears:

raw = "  Ada, Grace, Alan  "
cleaned = raw.strip()
names = cleaned.split(", ")
print(cleaned)
print(names)
Ada, Grace, Alan
['Ada', 'Grace', 'Alan']

This is the shape of real text handling: trim the noise, then split the signal into usable pieces. You'll reach for this pattern constantly once your programs read names, lists, or any input typed by a person.

Knowledge check

Check your understanding

Answer this question before you continue.

What is the value of `parts` after this code runs?
Output Prediction

Focus: Predict how stripping and splitting reshape a string into cleaned text and a list.

raw = "  Ada, Grace, Alan  "
cleaned = raw.strip()
parts = cleaned.split(", ")

Combining Numbers and Strings

Here's where beginners usually hit their first real wall. Numbers and strings are different types, and Python refuses to mix them silently.

age = 25
print("I am " + age + " years old.")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

Read that error closely. Python isn't confused—it's telling you exactly what happened: you tried to add a string and an integer, and it won't guess what you meant. That's a feature, not a bug. Silent guessing would hide real mistakes.

The fix is to make both sides the same type. Convert the number to a string with str():

age = 25
print("I am " + str(age) + " years old.")
I am 25 years old.

Or use an f-string, which does the conversion for you:

age = 25
print(f"I am {age} years old.")
I am 25 years old.

Converting Between Numbers and Strings

Conversion goes both ways:

  • Number to string: str(42) → "42"
  • String to integer: int("42") → 42
  • String to float: float("3.14") → 3.14
print(str(42))
print(int("42") + 8)
print(float("3.14") + 1.0)
42
50
4.14

This matters the moment you take user input, because input() always returns a string. Converting that string into a number is the standard first step before doing math on it.

Common mistake

Common mistake: Trying to add a string and a number with +. Python raises a TypeError instead of guessing. Convert with str(), int(), or float() first, or use an f-string and let Python handle the conversion.

The Boundary in Action: Reading Input

A flowchart shows two inputs, 4 and 5, entering as strings; the unconverted path produces 45 through text concatenation, while int conversion produces 4 and 5 as integers and the result 9 through addition.
Convert numeric input at the boundary so Python performs addition instead of joining text.

The 42 versus "42" distinction stops being abstract the first time your program asks a person for a number. Watch what happens when you read two values and try to add them:

first = input("First number: ")
second = input("Second number: ")
print(first + second)
First number: 4
Second number: 5
45

You asked for numbers, typed numbers, and got 45. That is not a bug. input() always returns a string, so + concatenated the text "4" and "5" instead of adding the values. Python did exactly what you told it—you just told it to join text.

The fix is to convert at the boundary, the moment you know the input's meaning is numeric:

first = int(input("First number: "))
second = int(input("Second number: "))
print(first + second)
First number: 4
Second number: 5
9

Same input, different result, because now both values are integers before the + runs. That is the decision rule this whole tutorial has been building toward: check what you're holding, use an operation that fits it, and convert deliberately at the boundary when the meaning is numeric.

Practice: Try It Yourself

The fastest way to make this stick is to run code and watch the output. Open a Python file and work through these:

  1. Add two numbers and print the result.
  2. Create a string with your name and print a greeting.
  3. Join a first and last name into one string.
  4. Repeat a string three times and print it.
  5. Convert the string "100" to an integer, add 50, and print the result.
  6. Take the string " Ada, Grace, Alan ", strip it, split it, and print the list.
  7. Read two numbers with input(), convert them with int(), and print their sum.

For task 5, expect to use int(). If you try to add "100" + 50 directly, you'll get the same TypeError from earlier—and now you'll know exactly why. For task 7, you're applying the boundary rule from the previous section: without int(), two numeric-looking inputs will concatenate instead of adding.

Checking your work:

  • If you see an error, read the message. It names the line and usually the type mismatch.
  • Change the numbers or strings and rerun. Small edits are how you build intuition.
  • When output surprises you, that's evidence about how the language works—not a reason to give up.

What's Next?

You now have the two core building blocks: numbers you can compute with and strings you can reshape. More importantly, you have the rule that keeps them from colliding: convert deliberately at the boundary between text and computation.

The next step is putting that rule to work with real user input, so your programs stop being fixed scripts and start responding to the person running them. Practice reading input, converting it at the boundary, and using the converted value in a calculation.

Knowledge check

Final check

Finish the article by checking the ideas you just learned.

A program reads `4` and `5` with `input()` and prints `first + second`, producing `45`. Which explanation matches the article?
Question 1 of 2Misconception Check

Focus: Explain why numeric-looking input values concatenate until they are converted.

Which replacement fixes the error while preserving the intended message?
Question 2 of 2Debugging

Focus: Fix a string-and-number concatenation error by converting the number or using an f-string.

age = 25
print("I am " + age + " years old.")

References

  1. 3.1.2 Stringsdocs.python.org
  2. Working With Strings and Numbers - Real Pythonrealpython.com
Practical resource

Want a more structured Python path?

Use the Python Starter Pack to turn scattered tutorials into a focused practice path.

View the bundle
Coming soon

Python Starter Pack

A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.

$9
PDF BundleTopic PackPythonBeginner
  • 5 curated chapters
  • Enhanced PDF edition with bundle-only learning guidance
  • Offline-friendly format for focused review
  • Source article links for future online updates

Coming soon

Free Python bundle

Get the LearnPyFast Python for Artificial Intelligence Starter Bundle

Build a Python foundation you can actually use. The Python for Artificial Intelligence Starter Pack brings together a guided path through setup, core programming concepts, data structures, files, JSON, APIs, debugging, and practical projects—so you can move quickly from running your first program to understanding and building useful software.

You’ll receive the bundle by email. You can unsubscribe anytime.

No spam. You can unsubscribe anytime. See our Privacy policy.

Related sites

Continue beyond Python

Explore related Worldmonger sites when you want to move from Python basics into JavaScript or LLM application building.

JavaScript tutorialstutorial

LearnJSFast

Beginner-friendly JavaScript tutorials for practical web development and self-taught developers.

JavaScriptFrontendWeb development
Visit LearnJSFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related tutorials

Continue with nearby Python topics and beginner-friendly explanations.

Close-up view of HTML and CSS code displayed on a computer screen, ideal for programming and technology themes.
beginner
11 min read

Basic Math in Python

Python does not make you memorize a calculator manual. It hands you a small set of operators and lets you run the calculation and read the answer…

Read tutorial
Close-up of a large pot filled with black dye used in traditional incense stick production indoors.
beginner
9 min read

Python Comments and Code Style

Comments are not for Python. They are for the next human who reads your code—and that human is often you, six weeks later. The interpreter skips every line…

Read tutorial