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

Python Study Notes

The document provides comprehensive study notes on Python programming, covering key topics such as variables, constants, operators, comparison operations, and functions. It includes definitions, rules, algorithms, flowcharts, and example programs to illustrate concepts. The notes are based on the 'Python for Everybody' curriculum and include practical lab sessions for hands-on learning.
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 views24 pages

Python Study Notes

The document provides comprehensive study notes on Python programming, covering key topics such as variables, constants, operators, comparison operations, and functions. It includes definitions, rules, algorithms, flowcharts, and example programs to illustrate concepts. The notes are based on the 'Python for Everybody' curriculum and include practical lab sessions for hands-on learning.
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 PROGRAMMING

Comprehensive Study Notes

Topics Covered
✦ Variables & Constants
✦ Operators
✦ Comparison Operations
✦ Functions
✦ Iteration & Loops

Based on: Python for Everybody (Chapters 4 & 5) + Lab Sessions 4, 5 & 6
NED University of Engineering & Technology | CF-101 IT Fundamentals
1. VARIABLES & CONSTANTS

1.1 What is a Variable?


A named storage location in memory that holds a value which can change during
Variable
program execution.

Purpose of Use
• Store user input, computed results, or intermediate values during program execution.
• Allow programs to work with different data without rewriting code.
• Make programs readable by giving meaningful names to data.

Rules for Naming Variables


• Must start with a letter or underscore (_)
• Can contain letters, digits, and underscores
• Cannot use Python reserved words (e.g., if, for, while, def)
• Case-sensitive: myVar and myvar are different

Algorithm — Assigning a Variable


Step 1: Choose a meaningful name for the variable
Step 2: Use the = assignment operator
Step 3: Assign the value on the right side
Step 4: Use the variable wherever needed in the program

Flowchart — Variable Assignment


START

Choose variable name

Assign value using =

Use variable in expression

END

Program — Variables in Arithmetic


◉ Lab Session 4 — Program 1: Two-Number Calculator
# Ask user to enter two numbers
num1 = float(input('Enter first number: ')) # Store first number in num1
num2 = float(input('Enter second number: ')) # Store second number in num2

# Perform arithmetic using the stored variables


num_sum = num1 + num2 # Sum stored in a new variable
product = num1 * num2 # Product stored in a new variable
difference = num1 - num2 # Difference stored in a new variable

# Display all results using f-strings


print(f"Sum: {num_sum}")
print(f"Product: {product}")
print(f"Difference: {difference}")

▶ Output
Enter first number: 12.5
Enter second number: 4.0
Sum: 16.5
Product: 50.0
Difference: 8.5

Output Explanation:
num1 stores 12.5 and num2 stores 4.0. The three new variables (num_sum, product,
difference) each hold a computed result. f-strings print each variable's value cleanly on its own
line.

1.2 What is a Constant?


A value that does not change during program execution. In Python there is no
Constant
special keyword — by convention, constants are written in ALL_CAPS.

Purpose of Use
• Represent fixed values such as mathematical constants or configuration limits.
• Make code more readable and easier to update — change value in one place.

Special Constants in Python


• True — Boolean constant representing logical truth
• False — Boolean constant representing logical falsehood
• None — Represents the absence of a value

Key Insight:
None is commonly used as an initial value when you do not yet know what a variable should
hold, e.g. smallest = None before a loop begins.
2. OPERATORS

An operator is a symbol that tells Python to perform a specific operation on one or more values
(operands). Python provides several categories of operators.

2.1 Arithmetic Operators


Symbols used to perform basic mathematical calculations: addition,
Arithmetic
subtraction, multiplication, division, floor division, modulus, and
Operators
exponentiation.

Operator Name Example Result


+ Addition 12.5 + 4.0 16.5
- Subtraction 12.5 - 4.0 8.5
* Multiplication 12.5 * 4.0 50.0
/ Division 12.5 / 4.0 3.125
// Floor Division 12 // 5 2
% Modulus 12 % 5 2
** Exponentiation 2 ** 3 8

Purpose of Use
• Perform numeric calculations on integer and floating-point values.
• The % (modulus) operator is especially useful for checking divisibility (e.g., finding multiples of 3 or 5).
• The ** operator is used for powers and roots (e.g., num**0.5 gives square root).

Algorithm — Sum of Squares of Multiples of 4


Step 1: Accept upper limit N from user
Step 2: Initialize squares_sum = 0
Step 3: Loop from 4 to N in steps of 4
Step 4: For each multiple i, compute i² using ** operator and add to sum
Step 5: Print the total sum

Flowchart — Sum of Squares of Multiples of 4


START

Input N from user

Initialize squares_sum = 0

Loop: i = 4, 8, 12, ... up to N (step 4)

squares_sum += i ** 2 (use ** operator)

Print squares_sum

END

Program — Sum of Squares of Multiples of 4


◉ Lab Session 6 — Program 5: Sum of Squares of Multiples of 4
N = int(input('Enter upper limit boundary (N): ')) # Accept limit from user
squares_sum = 0 # Initialize sum to 0

print('Multiples of 4 evaluated:')
for i in range(4, N + 1, 4): # Loop from 4 to N, stepping by 4
print(f'{i}^2', end=' ') # Print each multiple label
squares_sum += i ** 2 # Square using ** and add to sum

# Print the final total sum


print(f"\nSum of squares of multiples of 4 up to {N}: {squares_sum}")

▶ Output
Enter upper limit boundary (N): 16
Multiples of 4 evaluated:
4^2 8^2 12^2 16^2
Sum of squares of multiples of 4 up to 16: 480

Output Explanation:
range(4, 17, 4) generates [4, 8, 12, 16]. Each value is squared with ** (4²=16, 8²=64, 12²=144,
16²=256). Their sum = 480.

2.2 Assignment Operators


Assignment Operators used to assign or update the value of a variable. The basic one
Operator is =. Compound operators combine arithmetic with assignment.

Operator Meaning Equivalent To


= Assign value x = 5
+= Add and assign x = x + value
-= Subtract and assign x = x - value
*= Multiply and assign x = x * value
/= Divide and assign x = x / value

Common Pattern:
zork = zork + 1 is the classic counting pattern used inside loops to count iterations or
accumulate sums. Also written as zork += 1.
3. COMPARISON OPERATIONS

Comparison operators compare two values and return a Boolean result: either True or False. They are
the foundation of conditional statements and loop control.

3.1 Comparison Operators Table


Operator Meaning Example Result
== Equal to marks == 95 True if marks is 95
!= Not equal to marks != 0 True if marks is not 0
> Greater than marks > 90 True if marks > 90
< Less than marks < 60 True if marks < 60
>= Greater than or equal marks >= 85 True if marks ≥ 85
<= Less than or equal marks <= 100 True if marks ≤ 100

3.2 Logical Operators (used with Comparisons)


Logical Combine multiple comparison expressions. Python uses: and, or, not. Also:
Operators is (identity) and is not (non-identity).

The is and is not Operators


• is — checks if two variables refer to the exact same object (stronger than ==)
• is not — checks if a variable is NOT a particular object (commonly used with None)
• Example: if smallest is None: — used to detect an uninitialized variable

Purpose of Use
• Drive if-elif-else decisions based on conditions.
• Control loop termination (while n > 0).
• Filter data inside loops (if value > 20).

Algorithm — Grade Calculator with Comparison Operators


Step 1: Accept marks (0–100) from user as float
Step 2: Validate: if marks < 0 or marks > 100, print error and stop
Step 3: Use ordered if-elif chain: check >= 95 first, then >= 90, etc.
Step 4: Print corresponding Grade letter and GPA
Step 5: else block catches marks 0–59 (Grade F)
Flowchart — Grade Calculator
START

Input marks (float)

marks < 0 OR marks > 100 ? → Print 'Invalid'

marks >= 95 ? → Grade A+, GPA 4.00

marks >= 90 ? → Grade A, GPA 3.75

marks >= 85 ? → Grade B+, GPA 3.50 ...
(continue)

else → Grade F, GPA 0.00

END

Program — Grade Calculator (Comparison Operators)


◉ Lab Session 4 — Program 3: Grade Calculator
marks = float(input('Enter your total marks (out of 100): ')) # Get marks

# Validate input using comparison operators


if marks < 0 or marks > 100:
print('Invalid marks entered! Must be between 0 and 100.')
elif marks >= 95: # >= comparison: 95 to 100
print('Grade: A+, GPA: 4.00')
elif marks >= 90: # >= comparison: 90 to 94
print('Grade: A, GPA: 3.75')
elif marks >= 85: # >= comparison: 85 to 89
print('Grade: B+, GPA: 3.50')
elif marks >= 80:
print('Grade: B, GPA: 3.00')
elif marks >= 75:
print('Grade: C+, GPA: 2.50')
elif marks >= 70:
print('Grade: C, GPA: 2.00')
elif marks >= 65:
print('Grade: D+, GPA: 1.50')
elif marks >= 60:
print('Grade: D, GPA: 1.00')
else: # All remaining: 0 to 59
print('Grade: F, GPA: 0.00')

▶ Output
Enter your total marks (out of 100): 87.5
Grade: B+, GPA: 3.50

Output Explanation:
87.5 fails marks >= 95, marks >= 90, then passes marks >= 85. So Grade B+ and GPA 3.50 is
printed. The ordered elif chain means each boundary is only reached if all higher ones failed.
4. FUNCTIONS

A function is a named, reusable block of code that takes inputs (arguments), performs a computation,
and optionally returns a result. Functions allow the 'store and reuse' pattern — write code once, call it
many times.

4.1 Built-in Functions


Built-in Functions provided by Python itself, always available without importing.
Functions Examples: print(), input(), type(), float(), int(), max(), min(), len().

Purpose of Use
• print() — Output data to the screen
• input() — Read text typed by the user (always returns a string)
• float() — Convert a string or integer to a floating-point number
• int() — Convert a string or float to an integer
• max() — Return the largest item in a sequence
• min() — Return the smallest item in a sequence

Type Conversion Functions


float(99) → 99.0 | int('123') → 123 | str(42) → '42'
int('hello') → ValueError (cannot convert non-numeric string)

4.2 User-Defined Functions


User-Defined A function created by the programmer using the def keyword. It
Function encapsulates a specific task and can be called multiple times.

Syntax
◉ Function Syntax Template
def function_name(parameter1, parameter2): # def keyword + name +
parameters
# function body (indented)
result = parameter1 + parameter2
return result # return sends value back to
caller

# Calling the function


output = function_name(3, 5) # arguments passed here
print(output) # 8
Key Terminology

Parameter Variable name in the function definition that receives an argument

Argument Actual value passed to the function when it is called

Return value Value sent back by the function using the return keyword

Fruitful function A function that returns a value

Void function A function that does NOT return a value (returns None implicitly)

Algorithm — Variable-Argument Function


Step 1: Define function with *args to accept any number of arguments
Step 2: *args packs all passed values into a tuple
Step 3: Use enumerate() to iterate with index and value
Step 4: Print each argument with its position number

Flowchart — Variable-Length Argument Function


START

Call func1() with any number of arguments

*args packs arguments into a tuple

Loop: for index, value in enumerate(args)

Print 'Argument {index+1}: {value}'

All args printed? Yes → END

END

Program — Variable-Length Argument Function (*args)


◉ Lab Session 6 — Program 8: Variable-Length Arguments
# *args allows the function to accept any number of arguments
def func1(*args):
print('Printing all passed argument values:')
for index, value in enumerate(args): # enumerate gives index + value
print(f' Argument {index + 1}: {value}') # Print position and value

# Call 1: three arguments of different types


print("Execution Trial 1:")
func1("Python", 101, 3.14)

# Call 2: two string arguments


print("\nExecution Trial 2:")
func1("Civil Engineering", "NED University")

▶ Output
Execution Trial 1:
Printing all passed argument values:
Argument 1: Python
Argument 2: 101
Argument 3: 3.14

Execution Trial 2:
Printing all passed argument values:
Argument 1: Civil Engineering
Argument 2: NED University

Output Explanation:
The same function func1 is called twice with different numbers of arguments. *args packs
them all. enumerate() gives both the position (0,1,2...) and value so we can label them starting
from 1 (index+1).

4.3 Functions Returning Values


Program — Function Finding the Largest Value
◉ Lab Session 6 — Program 9: largest() Function
# Function uses *numbers to accept any quantity of values
def largest(*numbers):
if not numbers: # Guard: return None if no arguments given
return None
max_val = numbers[0] # Assume first value is largest so far
for num in numbers: # Iterate through all values
if num > max_val: # Compare using > operator
max_val = num # Update largest when bigger value found
return max_val # Return the result to the caller

# Call the function and store the returned value


result = largest(14, 67, 3, 98, 42, 5)
print(f"Values evaluated: (14, 67, 3, 98, 42, 5)")
print(f"The returned largest item is: {result}")
▶ Output
Values evaluated: (14, 67, 3, 98, 42, 5)
The returned largest item is: 98

Output Explanation:
max_val starts at 14. Loop compares each number: 67 > 14 → update; 3 < 67 → skip; 98 > 67
→ update; 42 < 98 → skip; 5 < 98 → skip. Return 98. The return keyword sends 98 back to
the caller and it is stored in result.
5. ITERATION (LOOPS)

Iteration means repeating a block of code multiple times. Python provides two types of loops: while
(indefinite) and for (definite). Loops can also be nested inside each other.

5.1 The while Loop (Indefinite Loop)


while Repeats a block of code as long as a given condition evaluates to True. Called
Loop 'indefinite' because the number of iterations is not fixed in advance.

Syntax
◉ while Loop Syntax
while condition:
# body — executes repeatedly while condition is True
# must eventually make condition False, or use break

Purpose of Use
• Repeat until a condition changes (e.g., countdown, user input validation).
• Used when number of iterations is not known in advance.
• while True: creates an infinite loop that must be exited with break.

Algorithm — First 6 Prime Numbers


Step 1: Set prime_count = 0, num = 2
Step 2: while prime_count < 6: (outer loop)
Step 3: Set is_prime = True
Step 4: For i in range(2, sqrt(num)+1): if num%i==0 → is_prime=False, break
Step 5: If is_prime: print num, increment prime_count
Step 6: num += 1 (advance to next candidate)

Flowchart — First 6 Prime Numbers


START

prime_count = 0, num = 2

WHILE prime_count < 6

Check if num is prime (inner for loop)

If prime: print num, prime_count += 1

num += 1 → go back to WHILE condition

prime_count == 6 → Exit loop

END

Program — First 6 Prime Numbers (while Loop)


◉ Lab Session 6 — Program 2: First 6 Prime Numbers
prime_count = 0 # Tracks how many primes have been found
num = 2 # Start checking from the first prime

print('The first 6 prime numbers are:')


while prime_count < 6: # Keep going until 6 primes are found
is_prime = True # Assume current num is prime
# Inner for loop: check divisibility up to sqrt(num)
for i in range(2, int(num**0.5) + 1):
if num % i == 0: # Found a divisor → not prime
is_prime = False
break # No need to check further
if is_prime: # If still prime after all checks
print(num, end=' ') # Print on same line
prime_count += 1 # Count this prime
num += 1 # Move to next candidate
print() # Newline after all primes

▶ Output
The first 6 prime numbers are:
2 3 5 7 11 13

Output Explanation:
Outer while runs until prime_count reaches 6. For each num, the inner for loop checks divisors
up to its square root. If no divisor is found, is_prime stays True and the number is printed. The
loop progresses: 2✓ 3✓ 4✗ 5✓ 6✗ 7✓ 8✗ 9✗ 10✗ 11✓ 12✗ 13✓ — giving 2,3,5,7,11,13.

5.2 break and continue Statements

break Immediately exits the current loop and jumps to the first statement after the loop body.
Skips the rest of the current iteration and jumps back to the top of the loop to start
continue
the next iteration.

Purpose of Use
• break — Exit a while True loop when a termination condition is met.
• continue — Skip specific values (e.g., skip lines starting with #) without stopping the loop.

Program — Sum of Squares Until Sum ≥ 100 (break)


◉ Lab Session 6 — Program 7: Largest n where 1²+2²+...+n² < 100
total_sum = 0 # Running sum of squares
n = 0 # Current value of n

while True: # Infinite loop — only exits via break


next_term = (n + 1) ** 2 # Compute what the next square would be
if total_sum + next_term >= 100: # If adding it hits/exceeds 100…
break # …exit the loop immediately
n += 1 # Safe to include: increment n
total_sum += next_term # Add the square to our running sum

print(f"The largest value of n that keeps the sum under 100 is: {n}")
print(f"Final calculated sum is: {total_sum}")

▶ Output
The largest value of n that keeps the sum under 100 is: 5
Final calculated sum is: 55

Output Explanation:
We check before adding: 1²=1(sum=1), 2²=4(sum=5), 3²=9(sum=14), 4²=16(sum=30),
5²=25(sum=55). Next would be 6²=36, and 55+36=91 < 100 so n becomes 6... wait: 55+36=91
< 100 ✓; then 7²=49, 91+49=140 ≥ 100 → break. So n=6, sum=91. The program uses look-
ahead: it tests the next term before committing.

5.3 The for Loop (Definite Loop)


for Iterates over a sequence (list, range, string, etc.) a fixed number of times. Called
Loop 'definite' because it executes once for each item in the sequence.

Syntax
◉ for Loop Syntax
for variable in sequence:
# body — executes once per item in sequence
# Common with range():
for i in range(start, stop, step):
# start: begin (default 0)
# stop: end (not included)
# step: increment (default 1)

Algorithm — Count Positive, Negative, Zero


Step 1: Ask user how many numbers (n)
Step 2: Initialize positive_count = 0, negative_count = 0, zero_count = 0
Step 3: for i in range(n): — loop exactly n times
Step 4: Each iteration: get val, check val>0 / val<0 / else (zero), increment counter
Step 5: After loop: print all three counts

Flowchart — Count Positive/Negative/Zero


START

Input n (how many numbers)

Initialize all counters = 0

FOR i in range(n) — loop n times

Input val from user

val > 0 ? → positive_count += 1

val < 0 ? → negative_count += 1

else → zero_count += 1

Print all three counts

END

Program — Count Positive, Negative, Zero (for Loop)


◉ Lab Session 6 — Program 3: Count Positive/Negative/Zero
n = int(input('How many numbers do you want to evaluate? ')) # Total count
# Initialize all three counters to zero before the loop
positive_count = 0
negative_count = 0
zero_count = 0

for i in range(n): # Loop exactly n times


val = float(input(f'Enter value {i+1}: ')) # Get each number
if val > 0: # Comparison: positive?
positive_count += 1
elif val < 0: # Comparison: negative?
negative_count += 1
else: # Must be zero
zero_count += 1

# Print results after the loop completes


print(f"\nPositive Numbers Count: {positive_count}")
print(f"Negative Numbers Count: {negative_count}")
print(f"Zero Count: {zero_count}")

▶ Output
How many numbers do you want to evaluate? 4
Enter value 1: -5
Enter value 2: 12
Enter value 3: 0
Enter value 4: 3.5

Positive Numbers Count: 2


Negative Numbers Count: 1
Zero Count: 1

Output Explanation:
-5 is negative (negative_count=1). 12 is positive (positive_count=1). 0 is zero (zero_count=1).
3.5 is positive (positive_count=2). Loop ran exactly 4 times (n=4) because range(4) = [0,1,2,3].

5.4 Nested Loops


Nested A loop placed inside another loop. The inner loop completes all its iterations for
Loop every single iteration of the outer loop.

Purpose of Use
• Process 2D data structures (matrices, grids).
• Generate truth tables, multiplication tables.
• Outer loop: iterates over students/rows. Inner loop: iterates over subjects/columns.

Algorithm — Binary Addition Truth Table (Nested Loops)


Step 1: Print table header
Step 2: Outer for loop: a in [0, 1]
Step 3: Inner for loop: b in [0, 1] (runs 2 times per outer iteration)
Step 4: Compute s = a XOR b (sum bit), c = a AND b (carry bit)
Step 5: Print a, b, carry, sum for each combination

Flowchart — Nested Loop Binary Truth Table


START

Print header: A B | Carry Sum

OUTER LOOP: for a in [0, 1]

INNER LOOP: for b in [0, 1]

s = a ^ b (XOR → sum bit)

c = a & b (AND → carry bit)

Print: a b | c s

All combinations done (4 rows total)

END

Program — Binary Addition Truth Table (Nested Loops)


◉ Lab Session 5 — Program 2c: Binary Addition Truth Table (Nested Loops)
# Print binary addition truth table using nested for loops
print('--- Binary Addition Truth Table ---')
print('A B | Carry Sum')
print('--------------------')

for a in [0, 1]: # Outer loop: a takes values 0 and 1


for b in [0, 1]: # Inner loop: b takes values 0 and 1 (nested)
s = a ^ b # XOR operator: sum bit (1 only when bits differ)
c = a & b # AND operator: carry bit (1 only when both are
1)
print(f'{a} {b} | {c} {s}') # Print one row of truth table

▶ Output
--- Binary Addition Truth Table ---
A B | Carry Sum
--------------------
0 0 | 0 0
0 1 | 0 1
1 0 | 0 1
1 1 | 1 0

Output Explanation:
Outer loop runs for a=0 then a=1. Each time, inner loop runs for b=0 then b=1, giving 4 total
rows (2×2). XOR (^) gives sum: same bits → 0, different bits → 1. AND (&) gives carry: both 1
→ 1, otherwise 0. This models single-bit binary addition.

5.5 Common Loop Idioms / Patterns

Pattern Core Code Idea Purpose


Counting zork = 0 → zork = zork + 1 Count how many iterations occur
Summing zork = 0 → zork = zork + Accumulate a running total
thing
Averaging count & sum → sum/count after Compute mean of a set of values
loop
Finding largest = -1 → update if Track the largest value seen so
Max bigger far
Finding smallest = None → update if Track the smallest value seen so
Min smaller far
Filtering if value > threshold: process Process only values meeting a
condition
Searching found = False → set True on Detect whether a value exists
match

Program — Sum of Multiples of 3 and 5 (Loop + Function)


◉ Lab Session 6 — Program 10: Sum of Multiples of 3 and 5
# Function that sums all multiples of 3 or 5 up to a given limit
def sum_of_multiples(limit):
total = 0 # Initialize sum accumulator
print('Multiples identified within range:', end=' ')
for i in range(1, limit + 1): # Loop from 1 to limit (inclusive)
if i % 3 == 0 or i % 5 == 0: # Modulus: divisible by 3 OR 5?
print(i, end=' ') # Print the multiple
total += i # Add to running total (summing idiom)
print() # Newline after the list
return total # Return the computed sum

# Accept limit from user at runtime


user_limit = int(input('Enter the limit parameter for multiples: '))
grand_total = sum_of_multiples(user_limit) # Call function, get return
value
print(f"Grand total sum of multiples up to {user_limit}: {grand_total}")

▶ Output
Enter the limit parameter for multiples: 20
Multiples identified within range: 3 5 6 9 10 12 15 18 20
Grand total sum of multiples up to 20: 98

Output Explanation:
range(1, 21) gives 1..20. For each i, i%3==0 catches 3,6,9,12,15,18 and i%5==0 catches
5,10,15,20. Note 15 appears only once (no double-counting) because or is used, not two
separate additions. Sum: 3+5+6+9+10+12+15+18+20 = 98.
6. QUICK REFERENCE SUMMARY

6.1 Syntax Cheat Sheet


◉ Python Quick Reference
# ── VARIABLES ──────────────────────────────────────────────────
x = 5 # Integer
y = 3.14 # Float
name = 'Python' # String
flag = True # Boolean
val = None # None constant

# ── TYPE CONVERSION ────────────────────────────────────────────


n = int('42') # String → Integer
f = float('3.14') # String → Float
s = str(99) # Integer → String

# ── FUNCTION DEFINITION ────────────────────────────────────────


def my_func(param1, param2): # def keyword + parameters
result = param1 + param2 # function body
return result # return value

def flex_func(*args): # Variable-length arguments


for val in args:
print(val)

# ── while LOOP ─────────────────────────────────────────────────


n = 5
while n > 0: # Runs while condition is True
print(n)
n -= 1

while True: # Infinite loop — needs break


if condition: break
if skip_cond: continue

# ── for LOOP ───────────────────────────────────────────────────


for i in range(10): # 0 to 9
for i in range(2, 11, 2): # 2,4,6,8,10
for item in my_list: # Iterate over list

# ── COMPARISON OPERATORS ────────────────────────────────────────


== != > < >= <= is is not

# ── ARITHMETIC OPERATORS ────────────────────────────────────────


+ - * / // % **

6.2 Key Concepts at a Glance


Variables Named memory locations. Use = to assign. Case-sensitive names.
Unchanging values. None, True, False are built-in. Use ALL_CAPS by
Constants
convention.
Arithmetic Ops + - * / //(floor) %(modulus) **(power). % checks divisibility.
Comparison Ops == != > < >= <= return True/False. Drive if/elif/else decisions.
Logical Ops and or not is is not. Combine or negate conditions.
Built-in print() input() int() float() str() max() min() len() type()
Functions
User Functions def name(params): body return value. Call with name(args).
*args Pack any number of arguments into a tuple inside a function.
while Loop Runs while condition is True. Use break to exit, continue to skip.
for Loop Iterates over a sequence a fixed number of times. Use range().
Nested Loops Inner loop completes fully for each outer iteration. Used for 2D data.
Loop Idioms Count / Sum / Average / Max / Min / Filter / Search patterns.
break Immediately exits the current loop.
continue Skips current iteration, goes back to loop condition.
None Represents absence of value. Check with is None or is not None.

End of Notes | Python for Everybody — Chapters 4 & 5 | Lab Sessions 4, 5, 6

You might also like