Python Foundations · Day 2

Strings, Operators & User Input

What you will cover

String manipulation, f-strings, arithmetic operators, comparisons, logical operators, type conversion and user input via input().

How to use this day

Plan about 1h45. Type every example yourself and complete the exercises in your editor.

2.1 String Manipulation

Strings are everywhere in data work - names, addresses, categories, labels, file paths. Python gives you a rich set of tools to work with them.

String concatenation

You can join two strings together using +:

first_name = "Jordan"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name)  # Jordan Smith

Notice the space in the middle - concatenation does not add spaces automatically.

f-Strings (formatted string literals)

f-strings are the modern, clean way to embed variables directly inside a string. Prefix your string with f and place variable names inside {}:

name = "Jordan"
age = 28
print(f"My name is {name} and I am {age} years old.")
# My name is Jordan and I am 28 years old.

You can even perform calculations inside the braces:

price = 49.99
quantity = 3
print(f"Total: £{price * quantity:.2f}")
# Total: £149.97

The :.2f is a format specifier - it rounds the result to 2 decimal places. You will use this constantly in data reporting.

Useful string methods

String methods are functions that belong to strings. You call them with a dot: string.method().

text = "  Hello, Data World!  "

print(text.upper())                     # "  HELLO, DATA WORLD!  "
print(text.lower())                     # "  hello, data world!  "
print(text.strip())                     # "Hello, Data World!"  - removes whitespace
print(text.strip().replace("Data", "Python"))  # "Hello, Python World!"
print(text.strip().split(", "))         # ['Hello', 'Data World!']
MethodWhat it does
.upper()Converts to uppercase
.lower()Converts to lowercase
.strip()Removes leading/trailing whitespace
.replace(old, new)Replaces a substring
.split(separator)Splits into a list of strings
.startswith(value)Returns True if string starts with value
.endswith(value)Returns True if string ends with value
.count(value)Counts occurrences of value
.find(value)Returns index of first occurrence, or -1

String indexing and slicing

Each character in a string has a position, called an index, starting at 0:

city = "London"
#        0 1 2 3 4 5

print(city[0])    # L
print(city[3])    # d
print(city[-1])   # n  (negative index counts from the end)

Slicing extracts a portion of a string using [start:end] - the start is inclusive, the end is exclusive:

country = "United Kingdom"
print(country[0:6])    # United
print(country[7:])     # Kingdom  (to the end)
print(country[:6])     # United   (from the start)
print(country[::2])    # Uite igm (every 2nd character)

2.2 Arithmetic Operators

Python handles all standard mathematical operations:

a = 17
b = 5

print(a + b)   # 22  - addition
print(a - b)   # 12  - subtraction
print(a * b)   # 85  - multiplication
print(a / b)   # 3.4 - division (always returns float)
print(a // b)  # 3   - floor division (integer result, rounds down)
print(a % b)   # 2   - modulo (remainder after division)
print(a ** b)  # 1419857 - exponentiation (a to the power of b)

Operator precedence

Python follows standard mathematical order: ** first, then *, /, //, %, then + and -. Use parentheses to be explicit:

print(2 + 3 * 4)    # 14 - multiplication first
print((2 + 3) * 4)  # 20 - parentheses first

Augmented assignment operators

These are shortcuts for updating a variable:

score = 100
score += 10   # score = score + 10 → 110
score -= 5    # score = score - 5  → 105
score *= 2    # score = score * 2  → 210
score //= 3   # score = score // 3 → 70

2.3 Comparison Operators

Comparison operators evaluate a condition and return a Boolean (True or False):

x = 10
y = 20

print(x == y)   # False - equal to
print(x != y)   # True  - not equal to
print(x < y)    # True  - less than
print(x > y)    # False - greater than
print(x <= 10)  # True  - less than or equal to
print(y >= 20)  # True  - greater than or equal to

Warning: a very common mistake is confusing = (assignment) with == (comparison). Writing if x = 5 will cause a SyntaxError. Always use == when asking “is x equal to 5?”.

2.4 Logical Operators

Logical operators combine multiple Boolean expressions:

age = 25
has_degree = True

# and - True only if BOTH conditions are True
print(age > 18 and has_degree)   # True

# or - True if AT LEAST ONE condition is True
print(age < 18 or has_degree)    # True

# not - inverts the Boolean
print(not has_degree)            # False

A practical example:

salary = 45000
experience_years = 3

is_eligible = salary > 30000 and experience_years >= 2
print(f"Eligible for promotion: {is_eligible}")  # True

2.5 Type Conversion

Often in data work you receive values in the wrong type and need to convert them:

# String to integer
age_str = "28"
age_int = int(age_str)
print(age_int + 1)   # 29

# String to float
price_str = "19.99"
price_float = float(price_str)
print(price_float * 2)   # 39.98

# Number to string (useful for building messages)
score = 95
message = "Your score is " + str(score)
print(message)   # Your score is 95

# Float to integer (truncates, does NOT round)
print(int(3.9))   # 3
print(int(-3.9))  # -3

Not every conversion is possible. int("hello") will raise a ValueError. You will learn how to handle errors gracefully on Day 6.

2.6 Getting Input from the User

input() pauses your programme and waits for the user to type something. It always returns a string:

name = input("What is your name? ")
print(f"Hello, {name}!")

Because input() returns a string, you must convert it if you need a number:

age = int(input("How old are you? "))
print(f"In 10 years you will be {age + 10} years old.")

✏️ Day 2 Exercises

Exercise 2.1 - String Surgery

Create ex2_1.py. Given the following string, use string methods only (no manual editing of the string) to produce and print the three outputs:

raw_data = "   product_name: Widget Pro   "

Target output:

PRODUCT_NAME: WIDGET PRO
product_name: widget pro
product_name: widget pro

Hint: you can chain methods: raw_data.strip().upper().

Exercise 2.2 - The Calculator

Create ex2_2.py. Ask the user to enter two numbers. Perform and print all seven arithmetic operations (+, -, *, /, //, %, **) with a descriptive label for each.

Hint: remember that input() returns a string. Use float() so your calculator handles decimals.

Exercise 2.3 - Greeting Card Generator

Create ex2_3.py. Ask the user for their first name, last name and age. Then print a formatted greeting like:

=============================
  Welcome, Jordan Smith!
  Age: 28
  In 5 years: 33
=============================

Hint: use f-strings and the * operator on strings - "=" * 29 produces a line of 29 equals signs.

Exercise 2.4 - Challenge: Slicing Practice

Given the string "Data Analytics Programme", use slicing only (no string methods) to extract and print:

  • "Data"
  • "Analytics"
  • "Programme"
  • "emmargorP" (Programme reversed)

Hint: for reversing a slice, use [start:end:-1], or simply [::-1] on the relevant portion.

📌 Day 2 Summary

ConceptWhat you learned
f-stringsEmbed variables directly in strings with f"...}
String methods.upper(), .lower(), .strip(), .replace(), .split()
Indexing & slicingAccess characters and substrings with []
Arithmetic operators+, -, *, /, //, %, **
Comparison operators==, !=, <, >, <=, >=
Logical operatorsand, or, not
Type conversionint(), float(), str()
input()Reads user input as a string

Tomorrow you will give your programmes the ability to make decisions and repeat actions - the core logic of any data pipeline or analytical script.