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

Python Basics Complete Notes

The document provides comprehensive notes on Python basics, covering topics such as variables, type conversion, arithmetic and comparison operators, conditionals, loops, and nested loops. It includes examples and explanations for each concept, emphasizing the importance of understanding data types and control flow in programming. Additionally, it outlines common mistakes and offers methods for constructing nested loops and patterns.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Python Basics Complete Notes

The document provides comprehensive notes on Python basics, covering topics such as variables, type conversion, arithmetic and comparison operators, conditionals, loops, and nested loops. It includes examples and explanations for each concept, emphasizing the importance of understanding data types and control flow in programming. Additionally, it outlines common mistakes and offers methods for constructing nested loops and patterns.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Basics — Complete Notes

Attaullah's Python Foundation: Variables through Nested Loops

1. Variables, Input, and Print


Variables store values. input() always returns a string, so numbers must be converted using int() or float().
name = input("Enter your name ")
age = int(input("Enter your age "))
print(f"My name is {name} I am {age} years old")

Note: str() around input() is redundant since input() already returns a string.

f-strings
The letter f before a string tells Python to evaluate whatever is inside curly braces {} instead of treating it as
plain text.
name = "Ali"
print(f"My name is {name}") # My name is Ali
print("My name is {name}") # My name is {name} (no f, prints literally)

2. Type Conversion
The + operator behaves differently based on type: for strings it concatenates (joins text), for numbers it adds.
num_1 = input("Enter first number ")
num_2 = input("Enter second number ")
print(num_1 + num_2) # "5" + "3" = "53" (string joining, NOT math)

num_1 = int(input("Enter first number "))


num_2 = int(input("Enter second number "))
print(num_1 + num_2) # 5 + 3 = 8 (real addition)

3. Arithmetic Operators
Operator Meaning Example (10, 3)

+ Addition 13

- Subtraction 7

* Multiplication 30

/ Division (float) 3.333...

// Floor division (whole number) 3

% Modulus (remainder) 1

Note: % (modulus) is used constantly for even/odd checks: if num % 2 == 0: means even.
4. Comparison and Logical Operators
>= <= > < == != # comparison operators

and # True only if BOTH sides are True


or # True if EITHER side is True
not # flips True/False

age = 20
if age >= 18 and age <= 60:
print("Working age")
if age < 18 or age > 60:
print("Outside working age")

5. float, bool, type()


price = float(input("Enter price: ")) # decimal numbers
is_student = True # bool: True / False
print(type(age)) # <class 'int'>

6. Basic String Methods


name = "Attaullah"
print(len(name)) # 8 (number of characters)
print([Link]()) # ATTAULLAH
print([Link]()) # attaullah

7. Conditionals: if / elif / else


marks = int(input("Enter your marks: "))

if marks >= 90:


print("Grade A")
elif marks >= 80:
print("Grade B")
elif marks >= 70:
print("Grade C")
elif marks >= 60:
print("Grade D")
else:
print("Fail")

Note: With elif, you don't need upper-bound checks (like marks<90) because Python only reaches an elif if all above
it were False.
8. Loops — while and for
while loop
Repeats code AS LONG AS a condition stays True.
count = 1
while count <= 5:
print(count)
count += 1
# Output: 1 2 3 4 5

Note: If you forget to update the loop variable (count += 1), the condition never becomes False -> INFINITE LOOP.

for loop with range()


range(start, stop, step) generates numbers starting at 'start', stopping BEFORE 'stop'.
range(5) # 0,1,2,3,4 (starts at 0, stops before 5)
range(2, 6) # 2,3,4,5 (starts at 2, stops before 6)
range(0, 10, 2) # 0,2,4,6,8 (step of 2)

for i in range(1, 11):


print(i) # prints 1 through 10

break and continue


for i in range(10):
if i == 5:
break # exits the loop completely
print(i)
# Output: 0 1 2 3 4

for i in range(5):
if i == 2:
continue # skips just this one iteration
print(i)
# Output: 0 1 3 4

else with loops


Runs only if the loop finishes WITHOUT hitting break.
for i in range(5):
print(i)
else:
print("Loop finished without break")

9. Common Loop Mistakes (from practice)


Mistake 1: Wrong starting value changes the whole sequence.
# Wanted even numbers 2-20, but started at 1 -> got odd numbers instead
i = 1
while i <= 20:
print(i)
i += 2 # BUG: gives 1,3,5,7... not 2,4,6,8...
# FIX: start at i = 2

Mistake 2: Increment placed inside an if-block causes infinite loops.


i = 1
while i <= 20:
if i % 2 == 0:
print(i)
i += 1 # BUG: i only increases when even -> stuck forever at i=1
# FIX: move i += 1 OUTSIDE the if, so it runs every iteration
10. Nested Loops
A loop inside another loop. The RULE: the inner loop runs COMPLETELY through all its values before the
outer loop moves to its next value.
for i in range(1, 4): # outer: i = 1, 2, 3
for j in range(1, 3): # inner: j = 1, 2 (every time)
print(i, j)

# Output:
# 1 1
# 1 2
# 2 1
# 2 2
# 3 1
# 3 2

Note: i stays FROZEN for the entire inner loop. It only changes after ALL j-values are used up.

Classic bug: reusing the same variable name


# WRONG - inner loop overwrites outer loop's variable
for i in range(1,6):
for i in range(1,5): # BUG: should be 'j', not 'i'
print(i)

# CORRECT
for i in range(1,6):
for j in range(1,5):
print(j)

The 4-Step Method for finding inner loop range


This is the reliable method built during practice for figuring out any nested loop pattern:
STEP 1 - COUNT: How many items appear in each row of the pattern?
Build a table: i vs count

STEP 2 - FORMULA: Compare i to count in the table.


- Are they equal? -> count = i
- Goes up/down by 1? -> count = i + k or count = k - i
- Doubles/triples? -> count = k * i
- Stays constant? -> count = fixed number
Solve for k using ONE row, then verify with the rest.

STEP 3 - CONVERT TO RANGE (fixed rule, NEVER changes):


range(1, 1 + count)
(because range(1, N) always gives N-1 values, so add 1 back)

STEP 4 - VERIFY: Plug in each i value and confirm it matches the pattern.

Worked Example: Triangle Pattern


Pattern:
1
1 2
1 2 3
1 2 3 4

Step 1: counts are 1,2,3,4 for i=1,2,3,4. Step 2: count = i (identical, no extra number needed). Step 3: range(1,
i+1). Step 4: verified correct for every row.
for i in range(1, 5):
for j in range(1, i + 1):
print(j, end=" ")
print()

Worked Example: Decreasing Pattern


Pattern:
X X X X X
X X X X
X X X
X X
X

Step 1: counts are 5,4,3,2,1. Step 2: count goes down by 1 as i goes up -> count = k - i. Test i=1: 5 = k-1 ->
k=6, so count = 6-i. Step 3: range(1, 7-i). Step 4: verified.
for i in range(1, 6):
for j in range(1, 7 - i):
print('*', end=" ")
print()

Worked Example: Multiplying Pattern


Pattern:
X X
X X X X
X X X X X X

Step 1: counts are 2,4,6. Step 2: count doubles i -> count = 2*i. Step 3: range(1, 1+2*i). Step 4: verified (2,4,6
match).
for i in range(1, 4):
for j in range(1, 1 + 2*i):
print('*', end=" ")
print()

Deciding WHAT to print (i, j, or a formula)


This is a separate skill from finding the range. Four cases seen in practice:
1. Counting/changing numbers in the row -> print(j)
Example: 1 2 3 -> for j in range(1,4): print(j)

2. Same number as the row number, repeated -> print(i)


Example: 2 2 (row i=2) -> for j in range(1,3): print(i)
3. Fixed literal value, unrelated to row -> print the literal
Example: 3 3 3 (always 3, never changes) -> print(3)

4. Shifted / combined value -> print a formula using i and j


Example: row i=1 -> "1 2", row i=2 -> "2 3"
-> print(i + j - 1)

Note: There is no single universal formula for 'what to print' - it requires reading the actual numbers in the pattern
each time, unlike the range formula which is always fixed.
11. Coming Up Next
Lists, tuples, dictionaries, and functions (def) - the next stages of the roadmap, building directly on the loop
skills covered here since looping through lists is one of the most common patterns in Python.

You might also like