0% found this document useful (0 votes)
2 views6 pages

Python Basic to Intermediate Notes 2

This document provides comprehensive visual notes on Python programming, covering topics from basics and syntax to intermediate concepts. It includes sections on operators, control flow, strings, data structures, functions, and modules/packages, with code examples for each concept. The notes serve as a quick reference for essential Python programming skills and practices.

Uploaded by

badalfreefire007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Python Basic to Intermediate Notes 2

This document provides comprehensive visual notes on Python programming, covering topics from basics and syntax to intermediate concepts. It includes sections on operators, control flow, strings, data structures, functions, and modules/packages, with code examples for each concept. The notes serve as a quick reference for essential Python programming skills and practices.

Uploaded by

badalfreefire007
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python — Basic to Intermediate Notes

Python Programming
Basic to Intermediate — Complete Visual Notes

■ 1. Basics & Syntax ■ 2. Operators


■ 3. Control Flow ■ 4. Strings
■ 5. Data Structures ■ 6. Functions
■ 7. Modules & Packages

Page 1
Python — Basic to Intermediate Notes

1. Basics & Syntax


Concept Description Code
print() Display output to console print("Hello, World!")
Comments Single-line comment starts with # # this is a comment
"""
Docstring Multi-line comment / documentation Multi-line comment
"""
No declaration needed; dynamically x = 10
Variables
typed name = "Aman"
Data Types int, float, str, bool, complex, None type(x) # <class 'int'>
# --- String input ---
name = input("Enter your name: ")
print("Hello,", name)

# --- Integer input (cast str -> int) ---


Takes user input — always returns a
input() age = int(input("Enter your age: "))
string; cast it to use as a number
print("Next year you will be", age + 1)

# --- Float input (cast str -> float) ---


height = float(input("Enter height in m: "))
print("Height in cm:", height * 100)

2. Operators
Concept Description Code
7 // 2 # 3 (floor div)
Arithmetic + - * / // % ** 7 % 2 # 1 (modulus)
2 ** 3 # 8 (power)
Comparison == != > < >= <= 5 == 5 # True
Logical and, or, not (5 > 2) and (3 < 4)
Assignment = += -= *= /= x += 1 # x = x + 1
Membership in, not in "a" in "cat" # True
Identity is, is not a is b # same object?
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Arithmetic
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)
print("Quotient:", num1 / num2)
Full program that takes two numbers print("Floor Division:", num1 // num2)
Complete Example
and applies arithmetic, comparison & print("Modulus:", num1 % num2)
(2 inputs)
logical operators print("Power:", num1 ** num2)

# Comparison
print("Equal:", num1 == num2)
print("Greater:", num1 > num2)

# Logical
print("Both positive:", (num1 > 0) and (num2 > 0))

3. Control Flow
Control flow statements decide the order in which code runs. Python uses indentation (not { }) to mark blocks — every line inside an if/for/while
must be indented consistently. Conditionals test a condition and branch; loops repeat a block until a condition ends.

Concept Description Code


if / elif / else Test conditions and branch into x = 10

Page 2
Python — Basic to Intermediate Notes

Concept Description Code

if x > 0:
print("positive")
elif x == 0:
different blocks print("zero")
else:
print("negative")

# Output: positive
age = 20
has_id = True

if age >= 18:


Nested if An if statement inside another if if has_id:
print("Entry allowed")
else:
print("ID required")
else:
print("Too young")
fruits = ["apple", "banana", "cherry"]

Iterate over a sequence (list, string, for fruit in fruits:


for loop
range...) print(fruit)

# apple banana cherry


count = 0

while count < 5:


Repeat a block while a condition stays
while loop print(count)
True
count += 1

# 0 1 2 3 4
for i in range(10):
if i == 5:
Exit the loop immediately, skipping break
break print(i)
remaining iterations

# 0 1 2 3 4
for i in range(5):
if i == 2:
Skip the rest of this iteration, move to continue
continue print(i)
the next

# 0 1 3 4
def todo():
pass # implement later
Empty placeholder statement — does
pass
nothing
if True:
pass # no action yet
for i in range(3):
for j in range(2):
A loop inside another loop — runs print(i, j)
Nested loops
inner loop fully for each outer step
# 0 0 / 0 1 / 1 0 / 1 1 / 2 0 / 2 1
for i in range(5):
if i == 10:
break
The else block runs only if the loop else:
for...else
finishes WITHOUT a break print("Loop completed fully")

# Loop completed fully


x = 7
Ternary
One-line if-else that returns a value result = "even" if x % 2 == 0 else "odd"
(conditional expr)
print(result) # odd

Page 3
Python — Basic to Intermediate Notes

Concept Description Code


for i in range(2, 10, 2):
Generates a sequence of numbers: print(i)
range()
start, stop, step
# 2 4 6 8
items = ["a", "b", "c"]
for idx, val in enumerate(items):
Loop with both index and value print(idx, val)
enumerate()
together
# 0 a / 1 b / 2 c
names = ["Tom", "Jerry"]
ages = [5, 3]
Loop over two (or more) sequences in for n, a in zip(names, ages):
zip() print(n, a)
parallel

# Tom 5 / Jerry 3

4. Strings
Concept Description Code
s = "Python"
Indexing Access a character by position s[0] # 'P'
s[-1] # 'n'
s[1:4] # 'yth'
Slicing Extract a substring
s[::-1] # reverse string
Concatenation Join strings with + "Hello" + " " + "World"
f-strings Formatted string literals f"Hello {name}, age {age}"
[Link](); [Link]()
Common Methods upper/lower/strip/split/replace [Link](); [Link](",")
[Link]("a","b")
len() Length of a string len(s) # 6

5. Data Structures
Python has four built-in collection types. List and Dictionary are mutable (can change after creation); Tuple is immutable (fixed once created) and
Set stores only unique, unordered values. Picking the right one affects both performance and how clearly your code expresses intent.

Concept Description Code


fruits = ["apple", "banana", "cherry"]

[Link]("mango") # add to end


[Link](1, "kiwi") # add at index 1
Ordered, mutable collection — allows [Link]("banana") # remove by value
duplicate values. Best for sequences
List
you need to change print(fruits[0]) # first item
(add/remove/reorder). print(fruits[-1]) # last item
print(fruits[1:3]) # slice

for f in fruits:
print(f)
point = (10, 20)
print(point[0]) # 10

Ordered, IMMUTABLE collection —


# point[0] = 99 # ERROR - tuples cannot be
once created, items cannot be changed.
Tuple modified
Used for fixed data (coordinates, RGB
values) and as dictionary keys.
# Unpacking a tuple
x, y = point
print(x, y) # 10 20
Dictionary Unordered collection of key-value student = {"name": "Aman", "age": 25}
pairs. Keys must be unique; values are
looked up by key instead of position — print(student["name"]) # access by key

Page 4
Python — Basic to Intermediate Notes

Concept Description Code


student["course"] = "ML" # add new key
student["age"] = 26 # update existing key
del student["course"] # remove a key
very fast lookup.
for key, value in [Link]():
print(key, ":", value)
colors = {"red", "green", "blue"}
[Link]("yellow")
Unordered collection of UNIQUE [Link]("green")
values — automatically removes
Set
duplicates. Useful for membership tests a = {1, 2, 3}
and set algebra (union, intersection). b = {2, 3, 4}
print([Link](b)) # {1, 2, 3, 4}
print([Link](b)) # {2, 3}
lst = [3, 1, 2]
[Link]() # [1, 2, 3]
Common List Quick reference for frequently used list [Link]() # [3, 2, 1]
Methods operations [Link]() # removes & returns last item
[Link]([9, 9]) # append multiple items
len(lst) # number of items
d = {"a": 1, "b": 2}
[Link]() # dict_keys(['a', 'b'])
Common Dict Quick reference for frequently used
[Link]() # dict_values([1, 2])
Methods dictionary operations
[Link]("c", 0) # default 0 if key missing
[Link]("a") # removes & returns value

6. Functions
A function is a named, reusable block of code created with the def keyword. It runs only when called, can optionally accept inputs (parameters), and
can optionally send a result back with return. Functions avoid repeating code and make programs easier to read and test.

Concept Description Code


def greet():
print("Hello there!")
def — basic Defines a function with no parameters;
function simply runs its block when called
greet() # calling the function
# Output: Hello there!
def greet(name):
Parameters let you pass data into the print(f"Hi {name}, welcome!")
def — with
function so it can work with different
parameters
values each time greet("Aman") # Hi Aman, welcome!
greet("Riya") # Hi Riya, welcome!
def greet(name="Guest"):
print(f"Hi {name}")
def — default A default value is used automatically if
parameter value the caller does not provide one
greet() # Hi Guest
greet("Aman") # Hi Aman
def add(a, b):
result = a + b
return sends a result back to wherever return result
def — return value the function was called, so it can be
stored or reused
total = add(5, 3)
print(total) # 8
def calculate(a, b):
total = a + b
def — multiple A function can take several inputs and diff = a - b
parameters & return several values at once (as a return total, diff
returns tuple)
s, d = calculate(10, 4)
print(s, d) # 14 6

7. Modules & Packages

Page 5
Python — Basic to Intermediate Notes
A module is a single .py file containing reusable functions, classes, and variables. A package is a folder of related modules with an __init__.py file.
Python ships with a large Standard Library, and pip lets you install third-party packages (pandas, numpy, requests...). Below are the 5 core concepts
you'll use constantly.

Concept Description Code


import math
Brings an ENTIRE module into your print([Link](25)) # 5.0
program; every function/variable inside print([Link](5)) # 120
it is accessed using dot notation print([Link]) # 3.14159...
import
([Link]). Keeps your own
namespace clean since nothing is import random
imported directly. print([Link](1, 10)) # random int 1-10
print([Link](["a","b","c"])) # random pick
from math import sqrt, pi
Imports SPECIFIC names directly, so print(sqrt(25)) # 5.0 (no math. prefix needed)
you call them without the module print(pi) # 3.14159...
from ... import prefix. Cleaner code when you only
need a couple of functions from a from random import randint, choice
module. print(randint(1, 100))
print(choice(["red", "blue", "green"]))
import numpy as np
arr = [Link]([1, 2, 3])
Imports a module under a shorter print([Link]()) # 6
ALIAS — the standard convention for
import ... as
large libraries, especially in data
science. import pandas as pd
df = [Link]({"a": [1, 2], "b": [3, 4]})
print(df)
# in terminal / command prompt:
Installs THIRD-PARTY packages that pip install pandas
are not part of the Standard Library, pip install numpy scikit-learn
pip install downloaded from PyPI (Python pip install pandas==2.2.0 # specific version
Package Index). Run from the terminal,
not inside a normal .py script. # inside a Jupyter notebook:
!pip install requests
import math
print(dir(math)) # list all names in math
Introspection tools — dir() lists module
everything defined inside a help([Link]) # show docs for sqrt
dir() / help() module/object; help() shows its function
documentation. Useful for exploring an
unfamiliar library.
print(dir(str)) # list all string methods
help([Link]) # show docs for [Link]

Page 6

You might also like