Understanding Python Basics
Python is an interpreted, object-oriented, high-level,case-sensitive and strongly typed programming language.
- Python code can either be:
- Directly interpreted and executed line by line, or
- Compiled into bytecode, which can then be executed on different machines.
- Python file extension:
.py
Variables in Python
A variable is a symbolic name assigned to a value — it acts as a reference (or pointer) to an object stored in memory.
a = 10
b = 10
print(id(a), id(b))
- In Python, if two variables are assigned the same immutable value (like integers or strings), they both point to the same object in memory.
- When you assign a new value to either variable, it stops pointing to the old object and instead points to a new one.
- What’s Actually Happening? When you write:
a = 10
print(a)
Python does the following internally:
- Creates an integer object
- Assigns it to the variable a
- Displays it in the console using the object’s class method (str)
- To check the class/type of any object:
print(type(a))
- Object Lifetime = An object exists as long as there is at least one variable referencing it
- Once no variable points to it, Python’s garbage collector removes it automatically
- Variable names cannot be Python keywords (like if, for, class, etc.)
- Variable names must start with a letter or underscore (_), not a number
- They are case-sensitive (Name and name are different)
Comments in Python
Comments are used to describe your code and make it more readable.
-Single-line comment
Starts with #
# This is a single-line comment
- Multi-line comment You can use triple quotes (""") for multi-line comments:
"""
This is a
multi-line comment
"""
Data Types in Python
Python supports both primitive and non-primitive data types.
-Primitive Data Types
- int → Integer numbers
a=10 #4bytes
b=int(10)
c=100l #8 bytes
#no type declaration needed
- float → Decimal numbers
x=5.5 #4 bytes
x=float(5.5)
- bool → Boolean (True / False)
- str → String (text)
x="hello world" #1 byte
x=str("hello world")
# Python has no char
# string is immutable, that is, every time you reassign a value new string is created
-complex
x=complex(1j)
- Non-Primitive Data Types sequence type
- list-> Ordered, mutable collection, non-homogeneous
x=["apple","orange"]
x=list(("apple","orange"))
- tuple -> Ordered, immutable collection, non-homogeneous
x=("apple","orange")
x=tuple(("apple","orange"))
x=list/type((a,))
#faster than list
-array->ordered, mutable, homogenous
from array import array
my_array = array('i', [1, 2, 3, 4])
import numpy as np
arr = np.array([1, 2, 3, 4])
-range
x=range(6)
#creates a range object to be used in any function like
z=list(x)
w=tuple(x)
for i in x:
mapping type
- set-> Unordered, unique elements
x={"apple","banana"}
x=set(("apple","banana"))
- dict-> Key-value pairs
x={"apple":"like","banana":"dislike"}
x=dict(("apple":"like","banana":"dislike"))
type conversion and type casting
type conversion
change in data type by itselftype casting
change in the datatype externally
random numbers
Python has no built-in random function, but
import random
print(random.randrange(1,10))
input function
-The input function always reads a string so we need to explicitly typecast it to an integer or a float
a=input("enter here")
print(type(a))
>><class 'str'>
a=input("enter")[4]
a=int(input("eneter a integer"))
print(a)
>><class 'int'>
math module
import math
math.sqrt(25)
math.pow(5)
math.ceil(3.3)
math.floor(3.5)
math.pi/e/etc
operators in Python
-arithmatic oparator
- addition=a+b
- substaraction=a-b
- multiplication=a*b
- division=a/b
- modules=a%b -->gives reminder
- exponential=a**b
- floor division=a//b
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.333...
print(a // b) # 3
print(a % b) # 1
print(a ** b) # 1000
assignment oparators
= -> x=5
+= -> x+=5 -> x=x+5
-= -> x-=5 -> x=x-5
= -> x=5 -> x=x*5
/= -> x/=5 -> x=x/5
//= -> x//=5 -> x=x//5
%= -> x%=5 -> x=x%5
= -> x=5 -> x=x**5
x = 10
x += 5 # 15
x -= 3 # 12
x *= 2 # 24
x /= 4 # 6.0
x //= 2 # 3.0
x %= 2 # 1.0
x **= 3 # 1.0 ** 3 = 1.0
-comparison operators
- == Equal to → returns True if both values are equal
- != Not equal to → returns True if values are different
- > Greater than
- < Less than
- >= Greater than or equal to
- <= Less than or equal to
a = 10
b = 3
print(a == b) # False
print(a != b) # True
print(a > b) # True
print(a < b) # False
print(a >= b) # True
print(a <= b) # False
-logical operators
compares two or more conditions
- and → Returns True if both conditions are true
- or → Returns True if at least one condition is true
- not → Reverses the result (True becomes False, False becomes True)
a = 10
b = 5
print(a > 3 and b < 10) # True (both conditions true)
print(a > 3 or b > 10) # True (one condition true)
print(not(a > 3)) # False (a > 3 is True, not makes it False)
-membership operators
- in → Returns True if a value exists in a sequence (like list, string, tuple, etc.)
- not in → Returns True if a value does not exist in a sequence
x = [1, 2, 3, 4, 5]
print(3 in x) # True (3 is present in the list)
print(10 in x) # False (10 is not in the list)
print(10 not in x) # True (10 is not in the list)
-identity operators
- is → Returns True if both variables refer to the same object in memory
- is not → Returns True if variables refer to different objects in memory
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True (b points to the same list as a)
print(a is c) # False (different objects with same content)
print(a is not c) # True (they are not the same object)
conditional statements
-if
-if,else
-if,elif,else
# IF Statement
x = 10
# Normal way
if x > 5:
print("x is greater than 5")
# One-liner way
if x > 5: print("x is greater than 5")
# IF–ELSE Statement
x = 3
# Normal way
if x % 2 == 0:
print("Even")
else:
print("Odd")
# One-liner way (ternary operator)
print("Even") if x % 2 == 0 else print("Odd")
# IF–ELIF–ELSE Chain
score = 85
# Normal way
if score >= 90:
grade = "A"
elif score >= 75:
grade = "B"
elif score >= 60:
grade = "C"
else:
grade = "D"
print(grade)
loops
-for loop
-while loop
-Python has no do-while, but it can be simulated
#for
for i in range(5):
print(i)
#while
count = 0
while count < 5:
print("Count:", count)
count += 1
- break
- Purpose: Immediately stops the entire loop (for or while).
- Effect: Control jumps outside the loop.
- Use case: When you’ve found what you need and don’t want to continue.
for i in range(5):
if i == 3:
break
print(i)
# Output: 0, 1, 2
- continue
- Purpose: Skips the current iteration and moves to the next one.
- Effect: The loop doesn’t stop; it just jumps to the next cycle.
- Use case: When you want to skip certain conditions but keep looping.
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0, 1, 3, 4
- pass
- Purpose: Does nothing — acts as a placeholder where code is syntactically required.
- Effect: The loop or block runs but performs no action.
- Use case: When you plan to write code later or need an empty block.
for i in range(5):
if i == 2:
pass # nothing happens
print(i)
# Output: 0, 1, 2, 3, 4
Functions
-simple functions
def function_name():
print("idiot")
fucntion_name()
-function with arguments
def sumdata(a,b):
print(a+b)
sumdata(1,5)
-functions with return
def sumdata(a,b):
return(a+b)
print(sumdata(a,b))
oops
class human:
leg = 2 #class variable
def __init__(self,age,height): #attributes/proprty
self.age=age #instance variable
self.height=height
def action(self): #methods/actions/behaviar
print(self.age)
kishore=human(100,100) #1
kishore.action()/human.action(kishore)
Kishore.leg/human.leg
#1: We are calling a construction function called human, which is always the same as the class name
types of methods
class human:
leg=2
eyes=2
def __init__(self,age,race,color): #object initialization method
self.race=race
self.age = age
self.color=color
@class methods #class methods(object not needed to call this)
def chnage_legs():
self.legs=3
@staticmethods
def action(self): # normal methods
print(self.race)
# Running the class method (no object needed)
Human.change_legs(3)
print(Human.legs) # Output: 3
# Creating an object
Tarun = Human(22,"Indian", "Brown")
# Accessing instance attributes
print(Tarun.race) # Output: Indian
# Running the static method
Human.action() # or Tarun.action()
Top comments (0)