This blog explains the Python basics every fresher should understand: variables, readability, operators, data types, loops, functions, collections, and object-oriented programming. It is written in a simple learning path, with theory first and a practical Python example after each concept
What Is a Programming Language?
A programming language is a language used to give instructions to a computer. The computer converts those instructions into actions such as displaying output, storing data, or controlling hardware.
Why Python?
- Python is easy to read and learn.
- It is a high-level, general-purpose language.
- It supports web apps, desktop apps, automation, data science, AI, and ML.
- It has many built-in libraries and a large community.
Variables and Readability
A variable is a named container used to store a value.
age = 25 name = "Arun" price = 99.50 is_active = True Readability means writing code that another person can easily understand.
# Bad x = 25 # Good student_age = 25 Use meaningful names, lowercase words with underscores, and avoid single-letter names except in small loops.
_name vs __name
Python does not have true private variables like Java or C++. Instead, underscores communicate intent.
| Syntax | Name | Meaning |
|---|---|---|
| name | Public | Anyone can use it |
| _name | Protected / internal | “Do not use this outside the class”; only a convention |
| __name | Name-mangled | Python changes it internally to ClassName_name |
| name | Dunder | Reserved for Python’s special methods, such as init |
class Student: def __init__(self): self.name = "Arun" # public self._marks = 90 # internal use self.__password = "1234" # name-mangled s = Student() print(s.name) # Arun print(s._marks) # 90 # print(s.__password) # AttributeError print(s._Student__password) # 1234 __name is not ** “strictly private”** in the security sense. Python performs name mangling, making accidental access harder, but the value can still be reached using the changed name.
Reserved Words
Reserved words are words already used by Python for a special meaning. You cannot use them as variable names.
Examples: if, else, while, for, def, class, return, import, True, False, None.
- if means: run this block only when a condition is true
- while means: repeat this block while a condition is true
if age >= 18: print("Adult") while count < 5: print(count) count += 1 Operators
Operators perform operations on values.
| Operator | Example | Result |
|---|---|---|
| + | 5 + 2 | 7 |
| - | 5 - 2 | 3 |
| * | 5 * 2 | 10 |
| / | 5 / 2 | 2.5 |
| // | 5 // 2 | 2 |
| % | 5 % 2 | 1 |
| ** | 5 ** 2 | 25 |
- Floor division (//) removes the decimal part.
- Exponential operator (*) means power: 5 * 2 is =25.
- Python does not have a separate “concat operator”; + is used to join strings.
print(7 // 2) # 3 print(7 % 2) # 1 print(2 ** 3) # 8 print("Py" + "thon") # Python Data Types
Python has built-in data types such as:
age = 25 # int price = 99.5 # float name = "Python" # str is_active = True # bool items = [1, 2, 3] # list point = (10, 20) # tuple ids = {1, 2, 3} # set user = {"name": "Arun"} # dictionary Why Python Does Not Use “Primitive” and “Non-Primitive” Like Java
In languages such as Java, int, char, and boolean are primitive types, while objects are non-primitive.
In Python, everything is an object, including numbers and strings. So Python does not separate data into primitive and non-primitive types in the same way as Java.
print(type(10)) # <class 'int'> print(type("hello")) # <class 'str'> Collections: List, Tuple, Set, Dictionary
| Collection | Syntax | Ordered? | Mutable? | Allows duplicates? |
|---|---|---|---|---|
| List | [1, 2, 3] | Yes | Yes | Yes |
| Tuple | (1, 2, 3) | Yes | No | Yes |
| Set | {1, 2, 3} | No | Yes | No |
| Dictionary | {"a": 1} | Insertion order | Yes | Keys must be unique |
fruits = ["apple", "banana", "mango"] fruits.append("orange") print(fruits) coordinates = (10, 20) # coordinates[0] = 30 # Error: tuple cannot change unique_ids = {101, 102, 103} unique_ids.add(104) student = {"name": "Arun", "age": 21} print(student["name"]) Useful List Methods
numbers = [10, 20, 30]
numbers.append(40) # Add at end numbers.insert(1, 15) # Add at index 1 numbers.remove(20) # Remove value 20 numbers.pop() # Remove last item numbers.sort() # Sort ascending numbers.reverse() # Reverse order print(len(numbers)) # Count items Set pop() and Ordering
A set is unordered, so it does not maintain index positions like a list. pop() removes and returns an arbitrary element; you cannot reliably predict which one it removes.
numbers = {10, 20, 30} removed = numbers.pop() print(removed) print(numbers) range() Function
range() generates a sequence of numbers. It is commonly used with for loops.
for i in range(5): print(i) # 0 1 2 3 4 for i in range(2, 10, 2): print(i) # 2 4 6 8 range(start, stop, step) starts at start, stops before stop, and increases by step.
Logic: print(0 > -1)
print(0 > -1)
Output:
True
Why? On the number line, 0 is greater than -1. Python compares the values and returns a Boolean result: True or False.
Bitwise Operators
Bitwise operators work directly on the binary representation of integers.
| Operator | Name | Example |
|---|---|---|
| & | AND | 5 & 3 |
| \\ | OR | |
| ^ | XOR | 5 ^ 3 |
| ~ | NOT / complement | ~5 |
| << | Left shift | 5 << 1 |
| >> | Right shift | 5 >> 1 |
print(bin(5)) # 0b101 print(5 & 3) # 1 print(5 | 3) # 7 print(5 ^ 3) # 6 print(5 << 1) # 10 print(5 >> 1) # 2 bin() **converts an integer into its binary string form. It is useful when learning bits, masks, permissions, and low-level logic.
**MSB, Signed, and Unsigned Integers
- MSB means Most Significant Bit.
- In binary, the leftmost bit is usually the MSB.
- In signed integers, the MSB can represent the sign: 0 for positive and 1 for negative in fixed-width systems.
- Unsigned integers use all bits for value, so they cannot represent negative numbers.
Example using 4 bits:
0111 = 7 1111 = 15 in unsigned 1111 = -1 in signed two's complement Two’s Complement
Two’s complement is the common method computers use to store negative integers.
To get -5 in 8-bit two’s complement:
5 = 00000101 Invert = 11111010 Add 1 = 11111011 So -5 is stored as 11111011.
User Input and Casting
input() always returns a string. Casting means converting one data type into another.
age = input("Enter your age: ") # String age = int(age) # Convert to integer price = float("99.5") number = str(100) Casting is needed because you cannot perform mathematical operations directly on string input.
# Wrong # age = input("Age: ") # print(age + 1) # Error # Correct age = int(input("Age: ")) print(age + 1) Conditional Statements
marks = 75 if marks >= 90: print("Grade A") elif marks >= 75: print("Grade B") else: print("Need improvement") Loops: for, while, break, continue, pass
Python has for and while loops. It does not have a traditional do-while loop.
# for loop for i in range(1, 6): print(i) # while loop count = 1 while count <= 5: print(count) count += 1 - break stops the loop immediately.
- continue skips the current iteration and moves to the next one.
- pass does nothing; it is used as a placeholder.
for i in range(1, 6): if i == 3: continue # Skip 3 if i == 5: break # Stop at 5 print(i) Even or Odd Logic
number = int(input("Enter a number: ")) if number % 2 == 0: print("Even number") else: print("Odd number") % gives the remainder. If a number divided by 2 has remainder 0, it is even.
Functions: Parameters, Arguments, Return
A parameter is the variable in the function definition. An argument is the actual value passed when calling the function.
def add(a, b): # a and b are parameters return a + b result = add(5, 3) # 5 and 3 are arguments print(result) # 8 return sends a value back to the caller and ends the function.
Method Overloading vs Method Overriding
| Concept | Meaning |
|---|---|
| Method overloading | Same method name with different parameter versions |
| Method overriding | Child class replaces a method inherited from the parent class |
Python** does not support traditional method overloading** directly. The last defined method with the same name replaces the previous one. You can handle different argument counts using default values.
class Animal: def sound(self): print("Some sound") class Dog(Animal): def sound(self): # Overriding print("Bark") Dog().sound() # Bark Classes and Objects
A class is a blueprint. An object is a real instance created from that blueprint.
class Student: def __init__(self, name, age): self.name = name self.age = age def introduce(self): print(f"My name is {self.name} and I am {self.age} years old.") s1 = Student("Arun", 21) s1.introduce() Why self Is Used
self represents the current object. When you call s1.introduce(), Python automatically passes s1 as self.
If you forget self in an instance method, Python will treat the first argument as the object, causing an error when you pass arguments.
# Wrong # def introduce(name): # print(name) # Correct def introduce(self): print(self.name) Constructor and Destructor
A constructor is a special method that runs automatically when an object is created. In Python, it is init().
class Student: def __init__(self, name): print("Constructor called") self.name = name s = Student("Arun") # Constructor runs here A destructor is del(). It is called when an object is about to be destroyed, but Python manages object cleanup automatically, so beginners should not depend on it for important work.
class Student: def __del__(self): print("Object deleted") Instance Variable vs Class Variable
| Type | Defined using | Belongs to |
|---|---|---|
| Instance variable | self.variable | One object |
| Class variable | Directly inside class | All objects of the class |
class Student: school = "ABC School" # Class variable def __init__(self, name): self.name = name # Instance variable s1 = Student("Arun") s2 = Student("Bala") print(s1.school) # ABC School print(s2.school) # ABC School print(s1.name) # Arun print(s2.name) # Bala Types of Class Methods
Python has three common method types:
| Method type | Decorator | First argument | Used for |
|---|---|---|---|
| Instance method | None | self | Work with object data |
| Class method | @classmethod | cls | Work with class-level data |
| Static method | @staticmethod | No automatic first argument | Utility logic |
class Student: school = "ABC School" def instance_method(self): print("Uses object:", self.name) @classmethod def class_method(cls): print("Uses class:", cls.school) @staticmethod def static_method(a, b): return a + b Exception Handling
Exception handling prevents a program from crashing when an error occurs.
try: number = int(input("Enter a number: ")) print(10 / number) except ZeroDivisionError: print("Cannot divide by zero") except ValueError: print("Please enter a valid number") finally: print("Program finished") - try contains risky code.
- except handles the error.
- finally always runs.
