DEV Community

Cover image for 🐍 Python Programming: From Basics to Control Flow
Abhishek Jaiswal
Abhishek Jaiswal

Posted on

🐍 Python Programming: From Basics to Control Flow

Learning Python is like learning to ride a bike πŸš΄β€β™‚οΈ β€” at first, balancing feels tricky, but once you get it, you’ll never forget. In this blog, we’ll go step by step through Python basics and control flow, covering everything from installation to loops, with clear explanations and examples you can try yourself.


1. Python Basics

πŸ”Ή Introduction to Python

Python is one of the most popular programming languages today, and for good reason.

  • History: Created by Guido van Rossum in 1991, inspired by ABC language.
  • Why named Python? Not the snake 🐍, but after the comedy group Monty Python!
  • Features:

    • Easy to read and write (feels like English).
    • Cross-platform (Windows, Mac, Linux).
    • Large community & libraries (NumPy, Pandas, TensorFlow, Django, Flask).
    • Versatile (AI, Web Dev, Automation, Data Science, Scripting).

πŸ‘‰ Python vs Other Languages:

  • Compared to Java/C++: Python is slower but far simpler and more productive.
  • Compared to JavaScript: Python isn’t mainly for frontend, but dominates in data science and backend.
  • Compared to R: Python is general-purpose, while R is specialized in statistics.

πŸ”Ή Python Syntax & Execution

Python files use the .py extension. You can run code in two ways:

  • Interactive Mode β†’ Directly in the Python shell (great for quick tests).
  • Script Mode β†’ Save code in .py file and run it via python filename.py.

Example:

print("Hello, Python!")  
Enter fullscreen mode Exit fullscreen mode

βœ… Unlike C, C++, or Java:

  • No semicolons required (unless multiple statements in one line).
  • No curly braces {}. Instead, indentation (spaces/tabs) defines code blocks.

πŸ”Ή Variables & Data Types

Variables are like containers storing data. In Python, you don’t declare types explicitly.

x = 10         # int
y = 3.14       # float
name = "Alice" # string
is_coding = True # boolean
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Dynamic Typing: You can reassign a variable to another type:

x = 42
x = "Now I’m a string!"
Enter fullscreen mode Exit fullscreen mode

Common Data Types:

  • int β†’ whole numbers
  • float β†’ decimal numbers
  • str β†’ text
  • bool β†’ True/False
  • list, tuple, set, dict β†’ collections

πŸ”Ή Keywords & Identifiers

  • Keywords: Reserved words like if, else, for, while, class, def. (You can’t use them as variable names.)
  • Identifiers: Names you give to variables, functions, classes.

    • Must start with a letter/underscore.
    • Case-sensitive: Name β‰  name.

Example (βœ… valid):

first_name = "Abhishek"
_age = 25
Enter fullscreen mode Exit fullscreen mode

Example (❌ invalid):

class = "Student"  # ❌ because 'class' is a keyword
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Input & Output

  • Output: Use print() function.
print("Welcome to Python!")
Enter fullscreen mode Exit fullscreen mode
  • Input: Use input() function. Always returns a string.
name = input("Enter your name: ")
print("Hello,", name)
Enter fullscreen mode Exit fullscreen mode
  • String Formatting:
name = "Alice"
age = 25
print(f"My name is {name}, and I’m {age} years old.")   # f-string
print("My name is {}, and I’m {} years old.".format(name, age))  # format()
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Operators

Operators are symbols to perform operations on values.

  1. Arithmetic Operators:
x, y = 10, 3
print(x + y)  # 13
print(x - y)  # 7
print(x * y)  # 30
print(x / y)  # 3.333...
print(x // y) # 3 (floor division)
print(x % y)  # 1 (modulus)
print(x ** y) # 1000 (power)
Enter fullscreen mode Exit fullscreen mode
  1. Comparison Operators:
print(x > y)   # True
print(x == y)  # False
Enter fullscreen mode Exit fullscreen mode
  1. Logical Operators:
print(x > 5 and y < 5)  # True
print(not (x > y))      # False
Enter fullscreen mode Exit fullscreen mode
  1. Assignment Operators:
x += 2   # same as x = x + 2
Enter fullscreen mode Exit fullscreen mode
  1. Membership Operators:
nums = [1, 2, 3]
print(2 in nums)       # True
print(5 not in nums)   # True
Enter fullscreen mode Exit fullscreen mode
  1. Identity Operators:
a = [1,2,3]
b = a
c = [1,2,3]
print(a is b)   # True (same object in memory)
print(a is c)   # False (different objects, even if same values)
Enter fullscreen mode Exit fullscreen mode

2. Control Flow

Now let’s move beyond basic syntax and start making decisions in our programs.


πŸ”Ή Conditional Statements

Conditions let your program decide what to do next.

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Adding more conditions with elif:

marks = 85
if marks >= 90:
    print("Grade: A")
elif marks >= 75:
    print("Grade: B")
else:
    print("Grade: C")
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Loops

Loops help us repeat tasks without rewriting code.

for loop β†’ Iterates over a sequence:

for i in range(5):
    print(i)
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Looping through a list:

fruits = ["apple", "banana", "mango"]
for fruit in fruits:
    print(fruit)
Enter fullscreen mode Exit fullscreen mode

while loop β†’ Runs until condition is false:

n = 5
while n > 0:
    print(n)
    n -= 1
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Loop Control Statements

  • break β†’ exit loop immediately.
  • continue β†’ skip current iteration, move to next.
  • pass β†’ do nothing (placeholder).

Example:

for i in range(5):
    if i == 3:
        break
    print(i)   # prints 0,1,2
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή Iterators & Generators (Intro)

  • Iterator β†’ An object you can loop through (e.g., list).
nums = [1,2,3]
it = iter(nums)
print(next(it))  # 1
print(next(it))  # 2
Enter fullscreen mode Exit fullscreen mode
  • Generator β†’ A function that yields values one at a time (saves memory).
def my_gen():
    yield 1
    yield 2
    yield 3

for val in my_gen():
    print(val)
Enter fullscreen mode Exit fullscreen mode

πŸ”Ή List Comprehensions & Generator Expressions

Python offers a concise way to create lists and generators.

  • List Comprehension:
squares = [x**2 for x in range(5)]
print(squares)   # [0, 1, 4, 9, 16]
Enter fullscreen mode Exit fullscreen mode
  • Generator Expression:
squares = (x**2 for x in range(5))
print(next(squares))  # 0
print(next(squares))  # 1
Enter fullscreen mode Exit fullscreen mode

🎯 Final Thoughts

This is the foundation of everything in Python. In the next stages, we will dive into functions, data structures, OOP, file handling, and advanced modules.

πŸš€ Practice small coding exercises daily β€” build a calculator, a number guessing game, or automate a simple task. That’s how Python will truly β€œclick” for you.


Top comments (0)