Learn Python Fundamentals

1. Using Python as a Calculator

We can use python terminal as a calculator. Such as –

>>> 2+2
4
>>> 2-2
0
>>> 2/2
1.0
>>> 2*2
4
>>> 2%2
0
>>> a = 5
>>> b = 3
>>> c = (a+b)*(a+b)
>>> print(c)
64
>>> a = 5
>>> b = 6
>>> a + b
11
>>> print(_)
11

Glossary:

_ (underscore) is a special varible which holds last result

2. Strings or character arrays

2.1 Creating Strings

>>> s1 = 'single quotes'
>>> s2 = "double quotes"
>>> s3 = '''triple quotes for
... multi-line strings'''
>>> s4 = str(123)  # convert to string

2.2 Indexing & Slicing

+---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5
  -6  -5  -4  -3  -2  -1
>>> s = "Python"
>>> s[0]      # 'P'  (first char)
>>> s[-1]     # 'n'  (last char)
>>> s[1:4]    # 'yth' (start:end, end exclusive)
>>> s[:3]     # 'Pyt'
>>> s[3:]     # 'hon'
>>> s[::-1]   # 'nohtyP' (reverse)
>>> s[::2]    # 'Pto'  (every 2nd char)

2.3 Common Methods

>>> s = "Hello World"
>>> s.upper()
'HELLO WORLD'
>>> s.lower()
'hello world'
>>> s.title()
'Hello World'
>>> s.capitalize()
'Hello world'
>>> s.swapcase()
'hELLO wORLD'
>>> s.strip()
'Hello World'
>>> s.lstrip()
'Hello World'
>>> s.rstrip()
'Hello World'
>>> s.strip('Hd')
'ello Worl'
>>> s.replace('World', 'Python')
'Hello Python'
>>> s.split()
['Hello', 'World']
>>> "a,b,c".split(',')
['a', 'b', 'c']
>>> '-'.join(['a', 'b', 'c'])
'a-b-c'
>>> s.find('World')
6
>>> s.index('World')
6
>>> s.count('l')
3
>>> s.startswith('Hello')
True
>>> s.endswith('World')
True
>>> s.isalpha()
False
>>> "abc".isalpha()
True
>>> "123".isdigit()
True
>>> "abc123".isalnum()
True
>>> "  ".isspace()
True
>>> "Hello".islower()
False
>>> "HELLO".isupper()
True
>>> s.center(20, '*')
'****Hello World*****'
>>> s.ljust(15, '-')
'Hello World----'
>>> s.rjust(15, '-')
'----Hello World'
>>> s.zfill(15)
'0000Hello World'

2.4 String Concatenation & Repetition

>>> "Hello" + " " + "World"
'Hello World'
>>> "ab" * 3
'ababab'

2.5 f-Strings (Formatted Strings)

>>> name = "Alice"
>>> age = 25
>>> f"My name is {name} and I am {age}"
'My name is Alice and I am 25'
>>> f"{3.14159:.2f}"
'3.14'
>>> f"{age:05d}"
'00025'
>>> f"{name:>10}"
'     Alice'
>>> f"{name:<10}"
'Alice     '
>>> f"{name:^10}"
'  Alice   '
>>> f"{'yes' if age>18 else 'no'}"
'yes'

2.6 Checking Membership

>>> "World" in "Hello World"
True
>>> "world" not in "Hello World"
True

2.7 Iterating Over Strings

>>> for ch in "abc":
...     print(ch)   
a
b
c
>>> for i, ch in enumerate("abc"):
...     print(i, ch)   
0 a
1 b
2 c

2.8 Strings Are Immutable

>>> s = "hello"
>>> s[0]= "H"
Traceback (most recent call last):
  File "<python-input-48>", line 1, in <module>
    s[0]= "H"
    ~^^^
TypeError: 'str' object does not support item assignment
>>> s = 'H' + s[1:]    # create new string
>>> print(s)
Hello

2.9 Escape Characters

"\n"   # newline
"\t"   # tab
"\\"   # backslash
"\'"   # single quote
"\""   # double quote
r"C:\new\file"   # raw string (no escaping)

3. Lists

3.1 Creating Lists

empty = []
nums = [1, 2, 3, 4, 5]
mixed = [1, "two", 3.0, True, None]
nested = [[1, 2], [3, 4]]
from_range = list(range(5))        # [0, 1, 2, 3, 4]
from_str = list("abc")             # ['a', 'b', 'c']
from_tuple = list((1, 2, 3))       # [1, 2, 3]
repeated = [0] * 5                 # [0, 0, 0, 0, 0]
comprehension = [x**2 for x in range(5)]  # [0, 1, 4, 9, 16]

3.2 Indexing & Slicing

lst = [10, 20, 30, 40, 50]
lst[0]        # 10
lst[-1]       # 50
lst[1:4]      # [20, 30, 40]
lst[:3]       # [10, 20, 30]
lst[2:]       # [30, 40, 50]
lst[::-1]     # [50, 40, 30, 20, 10]
lst[::2]      # [10, 30, 50]
lst[1:5:2]    # [20, 40]

3.3 Adding Elements

lst = [1, 2, 3]

lst.append(4)            # [1, 2, 3, 4]         — add one item at end
lst.extend([5, 6])       # [1, 2, 3, 4, 5, 6]    — add multiple items
lst.insert(0, 0)         # [0, 1, 2, 3, 4, 5, 6] — insert at index
lst += [7, 8]            # [0, 1, 2, 3, 4, 5, 6, 7, 8] — concatenation

3.4 Removing Elements

lst = [1, 2, 3, 2, 4]

lst.remove(2)            # removes first occurrence of 2 → [1, 3, 2, 4]
lst.pop()                # removes & returns last item → 4, lst=[1, 3, 2]
lst.pop(0)               # removes & returns index 0 → 1, lst=[3, 2]
del lst[0]               # delete by index
del lst[1:3]             # delete slice
lst.clear()              # [] — remove all items

3.5 Searching & Counting

lst = [10, 20, 30, 20, 40]

lst.index(20)            # 1  (first occurrence, raises ValueError if missing)
lst.index(20, 2)         # 3  (start search from index 2)
lst.count(20)            # 2
20 in lst                # True
50 not in lst            # True

3.6 Sorting

lst = [3, 1, 4, 1, 5, 9, 2]

lst.sort()                        # in-place ascending → [1, 1, 2, 3, 4, 5, 9]
lst.sort(reverse=True)            # descending
lst.sort(key=lambda x: -x)        # custom key

sorted(lst)                       # returns new sorted list (original unchanged)
sorted(lst, reverse=True)
sorted(["bb", "a", "ccc"], key=len)   # ['a', 'bb', 'ccc']

# Sort list of tuples by second element
pairs = [(1, 'b'), (2, 'a'), (3, 'c')]
pairs.sort(key=lambda p: p[1])    # [(2, 'a'), (1, 'b'), (3, 'c')]

3.7 Reversing

lst = [1, 2, 3, 4]
lst.reverse()             # in-place → [4, 3, 2, 1]
list(reversed(lst))       # returns new reversed list
lst[::-1]                 # slicing → new reversed list

3.8 Copying Lists

lst = [1, 2, 3]

copy1 = lst.copy()         # shallow copy
copy2 = lst[:]             # shallow copy via slice
copy3 = list(lst)          # shallow copy via constructor
copy4 = lst                # NOT a copy — same reference!

import copy
deep = copy.deepcopy(nested)  # deep copy (for nested lists)

3.9 Concatenation & Repetition

a = [1, 2]
b = [3, 4]

a + b            # [1, 2, 3, 4]  (new list)
a * 3            # [1, 2, 1, 2, 1, 2]
a.extend(b)      # modifies a in-place

3.10 Length, Min, Max, Sum

lst = [3, 1, 4, 1, 5]

len(lst)         # 5
min(lst)         # 1
max(lst)         # 5
sum(lst)         # 14
sum(lst) / len(lst)   # average
any(x > 4 for x in lst)   # True
all(x > 0 for x in lst)   # True

3.11 Iterating

lst = ['a', 'b', 'c']

for x in lst:
    print(x)

for i, x in enumerate(lst):
    print(i, x)

for i, x in enumerate(lst, start=1):    # start index at 1
    print(i, x)

3.12 List Comprehensions

[x**2 for x in range(5)]              # [0, 1, 4, 9, 16]
[x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8]
[x.upper() for x in ['a', 'b']]       # ['A', 'B']
[(i, x) for i, x in enumerate('ab')]  # [(0, 'a'), (1, 'b')]

# Nested comprehension
[[i*j for j in range(1, 4)] for i in range(1, 4)]
# [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

# Flatten nested list
matrix = [[1, 2], [3, 4], [5, 6]]
[x for row in matrix for x in row]    # [1, 2, 3, 4, 5, 6]

4. Control Flow and Loops

4.1 While Loop

>>> a, b = 0, 1
>>> while a < 10:
...     print(a)
...     a, b = b, a+b
...     
0
1
1
2
3
5
8

4.2 if Statements

x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')

4.3 for Statements

# Measure some strings:
words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))

4.4 The range() Function

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

4.5 break and continue Statements

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(f"{n} equals {x} * {n//x}")
            break
for num in range(2, 10):
    if num % 2 == 0:
        print(f"Found an even number {num}")
        continue
    print(f"Found an odd number {num}")

4.6 else Clauses on Loops

for n in range(2, 10):
    for x in range(2, n):
        if n % x == 0:
            print(n, 'equals', x, '*', n//x)
            break
    else:
        # loop fell through without finding a factor
        print(n, 'is a prime number')

4.7 pass Statements

while True:
    pass  # Busy-wait for keyboard interrupt (Ctrl+C)

4.8 match Statements

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

5. Functions

def fib(n):    # write Fibonacci series less than n
    """Print a Fibonacci series less than n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

# Now call the function we just defined:
fib(2000)

6. Data Structures

6.1 Lists

fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
fruits.count('apple')

fruits.count('tangerine')

fruits.index('banana')

fruits.index('banana', 4)  # Find next banana starting at position 4

fruits.reverse()
fruits

fruits.append('grape')
fruits

fruits.sort()
fruits

fruits.pop()

6.2 Tuples and Sequences

t = 12345, 54321, 'hello!'
t[0]

t

# Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
u

# Tuples are immutable:
t[0] = 88888
# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v

# they support unpacking just like lists:
x = [1, 2, 3]
0, *x, 4

6.3 Sets

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)                      # show that duplicates have been removed

'orange' in basket                 # fast membership testing

'crabgrass' in basket


# Demonstrate set operations on unique letters from two words

a = set('abracadabra')
b = set('alacazam')
a                                  # unique letters in a

a - b                              # letters in a but not in b

a | b                              # letters in a or b or both

a & b                              # letters in both a and b

a ^ b                              # letters in a or b but not both

6.4 Dictionaries

tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
tel

tel['jack']

tel['irv']
print(tel.get('irv'))

del tel['sape']
tel['irv'] = 4127
tel

list(tel)

sorted(tel)

'guido' in tel

'jack' not in tel

7. Modules

from fibo import *
fib(500)

8. Input Output

name = input("Enter your name: ")

print("Hello,", name)

9. Errors and Exceptions

while True:
    try:
        x = int(input("Please enter a number: "))
        break
    except ValueError:
        print("Oops!  That was no valid number.  Try again...")

10. Classes

class Student:

    def introduce(self):
        print("Hello! I am a student.")

# Create an object
student1 = Student()

# Call the method
student1.introduce()

11. Standard Library

import os

print("Current directory:", os.getcwd())
print("Operating system:", os.name)
print("Files:", os.listdir())

12. Virtual Environments

# Create virtual environment
python -m venv .venv

# Activate virtual environment
source .venv/bin/activate

# Upgrade pip
python -m pip install --upgrade pip

# Install packages
pip install numpy scipy sympy matplotlib

# List installed packages
pip list

# Deactivate
deactivate

# Remove environment
rm -rf .venv

Leave a Reply

Your email address will not be published. Required fields are marked *