Operations in Python

This section introduces arithmetic operations, string manipulations, and type conversions in Python.

Arithmetic Operations

Operation Symbol Example Result
Addition + 5 + 3 8
Subtraction - 5 - 2 3
Multiplication * 4 * 2 8
Division / 10 / 3 3.333
Floor Division // 10 // 3 3
Modulus % 10 % 3 1
Exponentiation ** 2 ** 3 8
a = 10
b = 3

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Floor Division: 3
Modulus: 1
Exponentiation: 1000

Exercise: BMI Calculator

Given a weight in kilograms and a height in meters, calculate Body Mass Index (BMI):

Formula: BMI = weight / (height ** 2)

weight = 70
height = 1.75
bmi = weight / (height ** 2)
print(f"Your BMI is: {bmi}")
Your BMI is: 22.857142857142858

String Operations

Use + to concatenate strings, and * to repeat them.

first_name = "Alice"
last_name = "Smith"

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

print("Hi! " * 3)
Alice Smith
Hi! Hi! Hi! 

Type Conversion

Convert between types using int(), float(), and str().

age = 25
height = 1.75

print("I am " + str(age) + " years old.")
print(f"My height is {height} meters.")
I am 25 years old.
My height is 1.75 meters.

Summary

  • Arithmetic operations: +, -, *, /, //, %, **
  • String operations: concatenation and repetition
  • Type conversion: int(), float(), str()
  • Use f-strings for clean and readable output