1

First Program & Variables

Variables

Python is a high-level, interpreted, object-oriented, general-purpose language created by Guido van Rossum. Its popularity in engineering comes from its simple syntax, powerful libraries, and direct applicability to scientific computing and AI.

Let's write our first program! In your VS Code, Spyder, or py3roid, type:

python
print("Hello, I can write program!!")
Hello, I can write program!!

Congratulations — you are officially a programmer now! 🎉

Now, dear engineers, let's move forward together. Put a piece of paper in front of you and imagine you're solving a civil engineering problem. How would you define parameters on paper? Obviously, with variables:

🐍 Naming rules for variables in Python: Think like a Python snake!
  • Only English letters, digits, and underscore _ are allowed
  • Cannot start with a digit (2name ❌ — name2 ✅)
  • Case-sensitive (Age ≠ age)
  • Avoid reserved keywords such as if and for
python
# Integer variable
x = 5
y = 10

# String variable
name = "Shayan"

# Float variable
pi = 3.14

print(x)       # 5
print(name)    # Shayan
5
Shayan

Basic data types: (click the cards)

🔢
Integer
int
Whole numbers like 5, -3, 1000 — no decimals
💧
Float
float
Decimal numbers like 3.14, -0.5 — written with a dot
📝
String
str
Text within single or double quotes: "Hello" or 'Hi'
✅
Boolean
bool
Two logical values: True or False — equivalent to 1 and 0
2

Numbers in Python

Numbers

Python has three main number types: integer (int), float, and complex. For engineering, the first two are the most relevant.

📌 Remember, dear engineer:
  • int — whole numbers from −∞ to +∞, no decimals
  • float — same range, but you can freely add a . next to the number

Example — a simple calculation:

python
a = 10
b = 3

print(a + b)   # 13
print(a - b)   # 7
print(a * b)   # 30
print(a / b)   # 3.3333...
print(a // b)  # 3  (integer division)
print(a % b)   # 1  (remainder)
print(a ** b)  # 1000 (power)
⚡ Engineering note: For more precise calculations, use the math library. For instance, math.sqrt(16) returns the square root of 16.
+
-
×
÷
%
**

3D rotating cube of math operators — hover to speed it up

3

Strings

Strings

Remember how you became a programmer with a single message? We write all our messages as strings, using either " " or ' '. There is also a dedicated constructor (str()) which we'll get to later.

python
name = "Shayan"
full = 'Civil Engineer'

print(name + " Dolat Yari")
print("=" * 20)
print(len(name))   # 6

# f-string — modern formatting
age = 25
print(f"My name is {name} and I am {age}")
Shayan Dolat Yari
====================
6
My name is Shayan and I am 25
🎯 Common string methods: .upper() — .lower() — .strip() — .replace() — .split() — .join()
4

Booleans

Booleans

Booleans are logical values with only two states: False and True — or, as we say informally, equivalent to 0 and 1. I wrote them in that order so you'd get it. 😄

python
a = 10
b = 20

print(a > b)     # False
print(a < b)     # True
print(bool(0))      # False
print(bool(1))      # True
📌 Golden rule: Zero, empty strings, empty lists, and None are all treated as False in Python. That's enough for now; if you find any data type I've missed, feel free to email me.
5

Operators

Operators

We have several operator types that you should compare with the symbols you use on paper. Fortunately, most of them match the standard engineering notation.

Arithmetic operators:

OperatorDescriptionExampleResult
+Addition3 + 25
-Subtraction3 - 21
*Multiplication — the star of our story!3 * 26
/Division7 / 23.5
//Integer (floor) division7 // 23
%Remainder7 % 21
**Power — twice as dramatic as multiplication!2 ** 38
+=Increment — adds to the variablex += 5x = x + 5
-=Decrement — subtracts from the variablex -= 3x = x - 3

Comparison operators:

OperatorMeaningExample
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True
>Greater than5 > 3 → True
<Less than5 < 3 → False
>=Greater than or equal5 >= 5 → True
<=Less than or equal5 <= 3 → False

Logical operators:

and — always False unless both statements are True
or — always True unless both statements are False
not — inverts the value

"To be, or not to be — that is the question!" — and this Shakespeare quote is always True. 😄

python
a = 5
b = 10

print(a > 0 and b > 0)   # True
print(a > 100 or b > 0)  # True
print(not (a > 0))          # False
6

Conditions

if / elif / else

Before we discuss conditions, remember: a condition activates only when the evaluated value is boolean and it must be True for us to enter the conditional body.

The conditional body is indented by 4 spaces or one Tab. And what do we need before writing a condition? Operators! So if you're unsure, review the previous lesson first.

A condition begins with if and ends with a colon :. If it's not satisfied, we can use elif (short for else if). If we simply have two branches, we use else.

python
age = 20

if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")
You are an adult

Engineering example — checking a concrete beam's safety:

python
stress = 250   # stress in MPa
limit  = 300   # allowable stress

if stress < limit:
    print("✅ Safe")
elif stress == limit:
    print("⚠️ At the limit")
else:
    print("❌ Danger")
✅ Safe
7

Loops

for / while

Python has two main loop types: the conditional loop and the counted (for) loop.

🔁 Conditional loop — while: Begins with while and continues as long as the condition holds, unless break exits it prematurely.
🔢 Counted loop — for: Begins with for and iterates over a range or sequence, continuing to the end unless break stops it.

For loop:

python
# Print numbers from 1 to 5
for i in range(1, 6):
    print(i)

names = ["Ali", "Sara", "Reza"]
for name in names:
    print(name)
1
2
3
4
5
Ali
Sara
Reza

While loop:

python
i = 1
while i <= 5:
    print(i)
    i += 1   # equivalent to i = i + 1
🚨 Warning: Always control the exit condition in a while loop, otherwise you'll create an infinite loop. Use break to exit immediately and continue to skip an iteration.

Engineering example — average of 5 stress samples:

python
stresses = [240, 255, 260, 245, 250]
total = 0

for s in stresses:
    total += s

avg = total / len(stresses)
print(f"Average = {avg} MPa")
Average = 250.0 MPa
8

User Input

Input

With input() we can ask the user to provide input and store it in a variable.

📌 Important: input always returns a string, so we must convert it with one of the following functions:
  • int() — convert to integer
  • float() — convert to floating point
  • eval() — auto-detect type
  • bool() — convert to boolean
python
# Get name
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Get number (must be converted)
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}")

height = float(input("Enter your height (m): "))
💡 Note: If you don't convert, Python treats the input as a string and "20" + 1 raises an error.
9

Functions

Functions

Functions in Python are used when we want to build an algorithm and call it whenever needed, avoiding repetition of loops, conditions, and so on.

Functions are reusable code blocks defined with the keyword def.

python
# Simple function
def greet(name):
    print(f"Hello, {name}!")

greet("Shayan")

# Function with return value
def add(a, b):
    return a + b

result = add(5, 3)
print(result)   # 8

# Function with default argument
def power(base, exp=2):
    return base ** exp

print(power(5))       # 25
print(power(2, 3))    # 8
Hello, Shayan!
8
25
8

Engineering example — area of a circular section:

python
import math

def circle_area(r):
    return math.pi * r ** 2

print(circle_area(5))   # 78.5398...
10

Data Structures

Data Structures

Data comes in two flavors:

  • Local — lists, tuples, dictionaries, and so on
  • Global — files, CSV files, server-side data, datasets, and so on

Python has four main local data structures:

📋
List
list
Ordered and mutable
[1, 2, 3]
🔒
Tuple
tuple
Ordered but immutable
(1, 2, 3)
📚
Dictionary
dict
Key-value pairs
{"name": "Ali"}
🎯
Set
set
Unique elements only
{1, 2, 3}
python
# List
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")

# Dictionary
person = {"name": "Shayan", "age": 25}
print(person["name"])   # Shayan

# Set
nums = {1, 2, 2, 3, 3}
print(nums)   # {1, 2, 3}
{1, 2, 3}
11

Libraries

math / numpy / matplotlib

Python has extremely powerful libraries essential for engineering and scientific work. We import them with import.

📚 Common engineering libraries:
  • math — math functions (sqrt, sin, cos, pi)
  • numpy — numerical computing and arrays
  • matplotlib — plotting
  • sympy — symbolic math
  • pandas — data analysis and CSV handling
python
import math

print(math.sqrt(16))    # 4.0
print(math.sin(0))      # 0.0
print(math.pi)           # 3.14159...

def hypotenuse(a, b):
    return math.sqrt(a ** 2 + b ** 2)

print(hypotenuse(3, 4))   # 5.0
4.0
0.0
3.141592653589793
5.0
12

Graphics & Plotting

matplotlib

For visualizing data and engineering results, we use the matplotlib library.

python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)

plt.plot(x, y, color="cyan", linewidth=2)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.grid(True)
plt.show()
🎨 Plot types: plot() line — bar() bar — scatter() scatter — hist() histogram — pie() pie

Engineering example — stress-strain curve:

python
import matplotlib.pyplot as plt

strain = [0, 0.001, 0.002, 0.003, 0.004]
stress = [0, 50, 100, 150, 200]

plt.plot(strain, stress, marker="o")
plt.title("Stress-Strain Curve")
plt.xlabel("Strain")
plt.ylabel("Stress (MPa)")
plt.grid(True)
plt.show()
13

Object-Oriented Programming

OOP

OOP is a programming paradigm in which data and behavior are organized into "objects". In Python, everything is an object — numbers, strings, lists, even functions.

Suppose we want to design a car and our company is "Eng. Dolat Yari's Company". To build a general system and structure — with us as the manufacturer — and then export cars that other engineers can import into their own programs with import, we turn to OOP.

🏛️ Four pillars of OOP:
  • Encapsulation — hiding internal details
  • Inheritance — inheriting attributes from another class
  • Polymorphism — one method, many behaviors
  • Abstraction — hiding complexity behind a simple interface

Defining a class and creating an object:

python
class Student:
    # Constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"My name is {self.name}, I am {self.age}")

# Create an object
s1 = Student("Shayan", 25)
s1.introduce()
My name is Shayan, I am 25

Inheritance:

python
class Engineer(Student):
    def __init__(self, name, age, field):
        super().__init__(name, age)   # call parent constructor
        self.field = field

    def introduce(self):   # method override
        print(f"I am {self.name}, a {self.field} engineer")

e1 = Engineer("Shayan", 25, "Civil")
e1.introduce()
I am Shayan, a Civil engineer
🎯 Key notes:
  • self — reference to the instance (mandatory in methods)
  • __init__ — constructor executed when creating an object
  • super() — access the parent class
  • Names surrounded by __ are magic methods

Engineering example — concrete beam class:

python
class Beam:
    def __init__(self, length, width, height):
        self.length = length
        self.width = width
        self.height = height

    def volume(self):
        return self.length * self.width * self.height

    def weight(self, density=2500):   # kg/m³ for concrete
        return self.volume() * density

b = Beam(5, 0.3, 0.5)
print(f"Volume: {b.volume()} m³")
print(f"Weight: {b.weight()} kg")
Volume: 0.75 m³
Weight: 1875.0 kg

Your Feedback, My Fuel

If this course has been useful to you, I would love to hear your thoughts, suggestions, or critiques. Every message you send becomes fuel to prepare more content in civil engineering and programming. If feedback is positive and plentiful, more specialized courses will appear on this site very soon.

0 Lessons
0 Code Examples
0 Hours of Study
0 Free
Thank you! Your feedback has been received. To finalize, click the email button below or copy your message and send it via email.
Contact Me Directly For any question, suggestion, or critique, email me directly.
dolat_yari@yahoo.com

Roadmap for Future Courses

AI in Civil Engineering
Structural Design Automation
Engineering Data Analysis
AutoCAD Automation with Python
BIM Modeling
Numerical Simulation