Sitemap
Mayank Koli

Mayank Koli

Starter Guide To Python

6 min readJan 28, 2025

--

1. Introduction to Python

- What is Python?

Python is basically a high level programming language.

It is one of the most easiest language to learn out there

It is a interpreted langage.

- Installing Python

  1. Visit python.org.
  2. Download and install the latest stable version of Python for your system (Windows, macOS, Linux).
  3. Verify the installation by typing python --version in your terminal or command prompt.

- Using an IDE

You can use an IDE (Integrated Development Environment) like:

  • Thonny (simple and beginner-friendly)
  • VS Code (more advanced with plugin support)
  • PyCharm (full-featured)

- Writing and Running a Simple Python Program

# This is a simple Python program
print("Hello, World!")
  • To run it, save the code in a file named hello.py, then run python hello.py in your terminal.

2. Basic Syntax and Data Types

- Variables and Data Types

Variables in Python don’t require explicit declaration of type. Python automatically infers the type.

Examples:

x = 10               # Integer
y = 3.14 # Float
name = "Alice" # String
is_active = True # Boolean

- Basic Input/Output

Python provides functions to take input from the user and display output.

Input Example:

name = input("Enter your name: ")
print("Hello, " + name + "!")

- Comments and Docstrings

  • Single-line comments: Use # to comment a line.
# This is a single-line comment
  • Multi-line comments: Use triple quotes ''' or """.
"""
This is a
multi-line comment
"""
  • Docstrings: Used to document functions or classes.
def greet(name):
"""
This function greets the user with their name.
"""
print("Hello, " + name + "!")

- Type Conversion

Python allows you to convert between different types using functions like int(), float(), str(), etc.

x = "10"           # String
y = int(x) # Convert to integer
print(type(y)) # Output: <class 'int'>

3. Operators

- Arithmetic Operators

These are used to perform mathematical operations.

Examples:

a = 10
b = 3
print(a + b) # Addition: 13
print(a - b) # Subtraction: 7
print(a * b) # Multiplication: 30
print(a / b) # Division: 3.333...
print(a % b) # Modulus: 1
print(a // b) # Floor division: 3
print(a ** b) # Exponentiation: 1000

- Comparison Operators

These are used to compare two values.

Examples:

a = 5
b = 10
print(a == b) # Equal to: False
print(a != b) # Not equal to: True
print(a > b) # Greater than: False
print(a < b) # Less than: True
print(a >= b) # Greater than or equal to: False
print(a <= b) # Less than or equal to: True

- Logical Operators

Used to combine conditional statements.

Examples:

x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False

- Assignment Operators

These are used to assign values to variables.

Examples:

x = 5       # Assign
x += 3 # Add and assign: x = x + 3
x -= 2 # Subtract and assign: x = x - 2
x *= 4 # Multiply and assign: x = x * 4
x /= 2 # Divide and assign: x = x / 2

4. Control Flow

- if, elif, else Statements

Conditional statements allow you to execute certain code based on conditions.

Example:

x = 10
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is equal to 5")
else:
print("x is less than 5")

- Nested Conditionals

You can nest conditional statements inside each other.

Example:

x = 10
if x > 5:
if x < 20:
print("x is between 5 and 20")
else:
print("x is greater than or equal to 20")
else:
print("x is less than or equal to 5")

- Boolean Expressions

Boolean expressions evaluate to either True or False.

Example:

x = 5
y = 10
print(x > y) # False
print(x <= 5) # True

5. Loops

- for Loop

The for loop iterates over a sequence (like a list or range).

Example:

for i in range(5):
print(i)

Output:

0
1
2
3
4

- while Loop

The while loop repeats as long as a condition is true.

Example:

x = 0
while x < 5:
print(x)
x += 1

- break, continue, and pass

  • break exits the loop.
  • continue skips to the next iteration.
  • pass does nothing (placeholder).

Example:

for i in range(10):
if i == 5:
break # Exits the loop
print(i)
for i in range(10):
if i == 5:
continue # Skips the iteration
print(i)
for i in range(10):
if i == 5:
pass # Placeholder, does nothing
print(i)

6. Functions

- Defining Functions

Functions allow you to organize your code into reusable blocks. You define a function using the def keyword.

Get Mayank Koli’s stories in your inbox

Join Medium for free to get updates from this writer.

Example:

def greet(name):
print("Hello, " + name + "!")

greet("Alice") # Output: Hello, Alice!

- Parameters and Return Values

Functions can take parameters (inputs) and return values (outputs).

Example:

def add(a, b):
return a + b
result = add(5, 3) # result is 8
print(result)

- Scope (Local vs Global)

  • Local variables are declared inside a function and are not accessible outside.
  • Global variables are declared outside functions and can be accessed anywhere in the code.

Example:

x = 10  # Global variable
def my_function():
y = 5 # Local variable
print(x + y)
my_function() # Output: 15
# print(y) # This would raise an error because y is local to my_function.

- Lambda Functions

A lambda function is a small anonymous function defined using the lambda keyword.

Example:

multiply = lambda a, b: a * b
print(multiply(3, 4)) # Output: 12

7. Data Structures

- Lists

A list is an ordered collection of items, which can be of any type. Lists are mutable (can be changed).

Example:

fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
fruits.append("orange") # Adding an item
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']

- Tuples

A tuple is similar to a list, but it is immutable (cannot be changed after creation).

Example:

point = (2, 3)
print(point[0]) # Output: 2
# point[1] = 4 # This would raise an error because tuples are immutable

- Sets

A set is an unordered collection of unique items.

Example:

my_set = {1, 2, 3, 4}
my_set.add(5) # Add an item
print(my_set) # Output: {1, 2, 3, 4, 5}

- Dictionaries

A dictionary is a collection of key-value pairs, where each key is unique.

Example:

student = {"name": "Alice", "age": 22, "major": "CS"}
print(student["name"]) # Output: Alice
student["age"] = 23 # Update value
print(student) # Output: {'name': 'Alice', 'age': 23, 'major': 'CS'}

8. File Handling

- Opening, Reading, and Writing Files

You can open files using the open() function and specify the mode (r for reading, w for writing, etc.).

Example (Reading a file):

with open('example.txt', 'r') as file:
content = file.read()
print(content)

Example (Writing to a file):

with open('example.txt', 'w') as file:
file.write("Hello, World!")

- File Modes

  • r: Read (default mode)
  • w: Write (creates a new file or overwrites existing file)
  • a: Append
  • b: Binary mode (e.g., rb, wb)

- Context Managers (with statement)

The with statement ensures the file is automatically closed after reading or writing.

Example:

with open('example.txt', 'r') as file:
content = file.read()
# No need to explicitly close the file

9. Error Handling

- Try, Except Blocks

You can handle errors using try and except. If an error occurs in the try block, the except block will execute.

Example:

try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

- Handling Different Types of Exceptions

You can handle different exceptions by specifying multiple except blocks.

Example:

try:
x = int("abc") # Raises ValueError
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")

- Raising Exceptions

You can raise your own exceptions using the raise keyword.

Example:

def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(e) # Output: Cannot divide by zero

10. Object-Oriented Programming (OOP)

- Classes and Objects

A class is a blueprint for creating objects (instances). Objects are instances of classes.

Example:

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} is barking")
dog1 = Dog("Buddy", 3)
dog1.bark() # Output: Buddy is barking

- Attributes and Methods

Attributes are variables inside a class, and methods are functions defined inside a class.

Example:

class Car:
def __init__(self, make, model):
self.make = make
self.model = model
def display(self):
print(f"Car make: {self.make}, model: {self.model}")
car1 = Car("Toyota", "Corolla")
car1.display() # Output: Car make: Toyota, model: Corolla

- Inheritance

Inheritance allows you to create a new class based on an existing class.

Example:

class Animal:
def sound(self):
print("Some sound")
class Dog(Animal):
def sound(self):
print("Woof!")
dog = Dog()
dog.sound() # Output: Woof!

- Polymorphism

Polymorphism allows methods to have different behaviors based on the object.

Example:

class Cat(Animal):
def sound(self):
print("Meow!")
animals = [Dog(), Cat()]
for animal in animals:
animal.sound() # Output: Woof! Meow!

- Encapsulation

Encapsulation is the concept of bundling data and methods that operate on the data within one unit (class).

Example:

class Account:
def __init__(self, balance):
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = Account(1000)
account.deposit(500)
print(account.get_balance()) # Output: 1500

I will also post some simple projects that you can make once you are done with these.

--

--