← Back to Python series
🌱
Basic
int · float · str · bool · type() · Arithmetic · Comparison · Logical · f-strings · input()

Weeks 2–3 — Variables & Data Types · Operators & I/O

Explore Python's four core data types, learn how to assign variables, use type() to inspect values, and perform basic type conversions. Master Python's arithmetic, comparison, and logical operators, format output with f-strings, and build interactive programs with input().

variablesintfloatstrbooltype conversionoperatorsf-stringinputformat
Duration
⏱ 2 hours + 2 hours
Level
📊 Beginner
Prerequisite
🎯 Week 1
OUTCOME
Declare variables of all basic types and convert between them / Build a simple calculator that reads two numbers and prints results

What you'll learn

  • 1Declare and reassign variables
  • 2Distinguish int, float, str, and bool
  • 3Use type() to inspect a value's type
  • 4Convert between types with int(), float(), str()
  • 5Understand dynamic typing in Python
  • 6Use all arithmetic operators including // and %
  • 7Compare values with ==, !=, <, >, <=, >=
  • 8Combine conditions with and, or, not
  • 9Format output with f-strings
  • 10Chain augmented assignment operators (+=, -=, *=)

Week 2 — Variables & Data Types

Explore Python's four core data types, learn how to assign variables, use type() to inspect values, and perform basic type conversions.

1. Variables

A variable is a named container for a value. Python uses dynamic typing — you don't declare the type, Python infers it.

python
x = 10
name = "Alice"
is_student = True
print(type(x))     # <class 'int'>
💡

Variable names are case-sensitive. Use snake_case by convention (my_variable, not myVariable).

2. Core Data Types

TypeExampleDescription
int42, -7Whole numbers
float3.14, -0.5Decimal numbers
str"hello"Text (immutable)
boolTrue, FalseBoolean logic
python
age = 25            # int
price = 9.99        # float
greeting = "Hi!"    # str
active = True       # bool
print(type(age))    # <class 'int'>

3. Type Conversion

Convert between types using built-in functions: int(), float(), str(), bool().

python
num_str = "42"
num = int(num_str)       # "42" → 42
pi = float("3.14")       # "3.14" → 3.14
text = str(100)          # 100 → "100"
print(bool(0), bool(1))  # False True
⚠️

int("3.7") raises ValueError — convert to float first: int(float("3.7"))

4. User Input

input() always returns a string. Remember to convert when you need a number.

python
name = input("Enter your name: ")
age  = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")

5. Common Mistakes

  1. Adding a number to a string without conversion — TypeError: can only concatenate str to str. Use str(num) + "text".
  2. int("3.7") → ValueError. Use int(float("3.7")) instead.
  3. Forgetting that input() returns str — age > 18 fails if age is a string.

Week 3 — Operators & I/O

Master Python's arithmetic, comparison, and logical operators, format output with f-strings, and build interactive programs with input().

1. Arithmetic Operators

OperatorNameExampleResult
+Add5 + 38
-Subtract5 - 32
*Multiply5 * 315
/Divide7 / 23.5
//Floor divide7 // 23
%Modulo7 % 21
**Exponent2 ** 101024
💡

// always returns int (floors toward negative infinity). % returns the remainder — handy for even/odd checks: n % 2 == 0.

2. Comparison & Logical Operators

python
print(5 > 3)        # True
print(5 == 5)       # True
print(5 != 3)       # True
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

3. f-strings

f-strings (f"...") are the modern way to embed expressions inside string literals.

python
name = "Alice"
age = 20
pi = 3.14159
print(f"Hello, {name}!")
print(f"Age: {age}")
print(f"Pi ≈ {pi:.2f}")   # 2 decimal places

4. Augmented Assignment

python
x = 10
x += 5   # x = x + 5 = 15
x -= 3   # x = 12
x *= 2   # x = 24
print(x) # 24

5. Common Mistakes

  1. = vs ==: = assigns, == compares. if x = 5 is a SyntaxError.
  2. 7 / 2 → 3.5 (float), not 3. Use 7 // 2 for integer division.
  3. "5" + 5 → TypeError. Convert first: int("5") + 5.

💻 Examples

Run these examples and check the output yourself.

01_variables.py— Basic variable assignment and type()
CODE
x = 42
pi = 3.14
name = "Alice"
flag = True
print(x, type(x))
print(pi, type(pi))
print(name, type(name))
print(flag, type(flag))
▶ Output
42 <class 'int'>
3.14 <class 'float'>
Alice <class 'str'>
True <class 'bool'>
02_conversion.py— Type conversion examples
CODE
print(int("100"))      # 100
print(float("3.14"))   # 3.14
print(str(42))         # "42"
print(bool(0))         # False
print(bool("hi"))      # True
▶ Output
100
3.14
42
False
True
03_input.py— Reading user input and converting types
CODE
name = input("Name: ")
year = int(input("Birth year: "))
age = 2024 - year
print(f"{name} is about {age} years old.")
▶ Output
Name: Alice
Birth year: 2000
Alice is about 24 years old.
01_arithmetic.py— All arithmetic operators
CODE
a, b = 17, 5
print(f"{a} + {b} = {a+b}")
print(f"{a} - {b} = {a-b}")
print(f"{a} * {b} = {a*b}")
print(f"{a} / {b} = {a/b:.2f}")
print(f"{a} // {b} = {a//b}")
print(f"{a} % {b} = {a%b}")
print(f"{a} ** {b} = {a**b}")
▶ Output
17 + 5 = 22
17 - 5 = 12
17 * 5 = 85
17 / 5 = 3.40
17 // 5 = 3
17 % 5 = 2
17 ** 5 = 1419857
02_fstring.py— f-string formatting
CODE
name = "Alice"
score = 92.567
print(f"Student: {name}")
print(f"Score:   {score:.1f}")
print(f"Passed:  {score >= 60}")
▶ Output
Student: Alice
Score:   92.6
Passed:  True
03_calculator.py— Simple two-number calculator
CODE
a = float(input("First number: "))
b = float(input("Second number: "))
print(f"{a} + {b} = {a+b}")
print(f"{a} - {b} = {a-b}")
print(f"{a} * {b} = {a*b}")
if b != 0:
    print(f"{a} / {b} = {a/b:.4f}")
else:
    print("Division by zero!")

📝 Exercises

Try them yourself first, then open the solution to compare.

Exercise 1

Type Inspector

Goal: Print the type and value of at least 5 different variables.

Requirements
  • Assign 5+ variables of different types
  • Print both type() and value for each
▶Toggle solution
SOLUTION
a = 10
b = 3.14
c = "hello"
d = True
e = None
for v in [a, b, c, d, e]:
    print(type(v).__name__, "→", v)
▶ Output
int → 10
float → 3.14
str → hello
bool → True
NoneType → None
Exercise 2

Personal Info Calculator

Goal: Read name and birth year from input, calculate age, and print a greeting.

Requirements
  • Use input() for name and birth year
  • Convert birth year to int
  • Print formatted greeting with calculated age
Sample I/O
Name: Alice
Birth year: 1998
Hello, Alice! You are 26 years old.
▶Toggle solution
SOLUTION
name = input("Name: ")
year = int(input("Birth year: "))
age = 2024 - year
print(f"Hello, {name}! You are {age} years old.")
Exercise 3

Odd/Even Checker

Goal: Read an integer and print whether it is odd or even.

Requirements
  • Use input() to read an integer
  • Use % operator
  • Print 'even' or 'odd'
Sample I/O
Enter a number: 7
7 is odd
▶Toggle solution
SOLUTION
n = int(input("Enter a number: "))
if n % 2 == 0:
    print(f"{n} is even")
else:
    print(f"{n} is odd")
Exercise 4

BMI Calculator

Goal: Calculate and print BMI from weight and height.

Requirements
  • Read weight (kg) and height (m) from input
  • BMI = weight / height**2
  • Print result with 2 decimal places
Sample I/O
Weight (kg): 65
Height (m): 1.70
BMI: 22.49
▶Toggle solution
SOLUTION
w = float(input("Weight (kg): "))
h = float(input("Height (m): "))
bmi = w / h**2
print(f"BMI: {bmi:.2f}")
Example code / lecture materials

All lecture materials and example code are openly available on GitHub.

View on GitHub ↗

Comments 0

No comments yet. Be the first.

Only members can comment.

Comments with ads, abuse, personal information or illegal content are hidden or removed. Comments are shown with your nickname. Privacy Policy