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

Python Study Notes

These Python study notes cover fundamental concepts including numbers, variables, core data structures, comparison operators, methods, and functions. Key topics include variable assignment, dynamic typing, dictionaries, tuples, sets, file handling, and the use of lambda expressions. The notes also explain scope, the LEGB rule, and how to use *args and **kwargs for flexible function arguments.

Uploaded by

danishsyed1123
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 views20 pages

Python Study Notes

These Python study notes cover fundamental concepts including numbers, variables, core data structures, comparison operators, methods, and functions. Key topics include variable assignment, dynamic typing, dictionaries, tuples, sets, file handling, and the use of lambda expressions. The notes also explain scope, the LEGB rule, and how to use *args and **kwargs for flexible function arguments.

Uploaded by

danishsyed1123
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

STUDY NOTES

Object & Data Structure Basics · Methods & Functions · Python Statements
CONTENTS

● Part 1 — Numbers & Variables


● Part 2 — Core Data Structures
● Part 3 — Comparison Operators & Boolean Logic
● Part 4 — Methods
● Part 5 — Functions, Scope & Advanced Arguments
● Part 6 — Python Statements (Control Flow)
● Quick-Reference Glossary
PART 1

Numbers & Variables

1.1 Numbers
Definition — Python has two core numeric types used constantly throughout the language.

Type Definition Examples

Integer (int) A whole number, positive or negative, no decimal point 2, -5, 1000

Float (float) A number with a decimal point, or exponential notation 1.2, -0.5, 2e2, 3E2

● Basic Arithmetic
2 + 1 # 3 Addition
2 - 1 # 1 Subtraction
2 * 2 # 4 Multiplication
3 / 2 # 1.5 Division (true/classic division -- keeps decimals)
7 // 4 # 1 Floor division (truncates decimal, no rounding)
7 % 4 # 3 Modulo -- returns the REMAINDER of division
2 ** 3 # 8 Exponent (power)
4 ** 0.5 # 2.0 Roots via fractional exponents

NOTE / gives the real-number result; // truncates to a whole number; % returns what's left over after that division. // does
not round.

● Order of Operations
2 + 10 * 10 + 3 # 105 (multiplication happens first)
(2 + 10) * (10 + 3) # 156 (parentheses override precedence)

1.2 Variable Assignment


Definition — A single equals sign = is the assignment operator -- it binds a name (label) to an object in memory. This
differs from ==, the comparison operator.

a = 5
a + a # 10
a = 10 # reassignment -- Python allows overwriting a name
a = a + a # 20 -- a variable's current value can be used to redefine itself

● Rules for Variable Names


● Cannot start with a number
● Cannot contain spaces -- use _ instead
● Cannot use symbols: : ' " , < > / ? | \ ( ) ! @ # $ % ^ & * ~ - +
● PEP8 best practice: lowercase with underscores (snake_case)
● Avoid single-character names l, O, I (confused with 1 and 0)
● Avoid Python built-in keywords like list or str as names

● Dynamic Typing
Python lets you reassign the same variable name to a completely different data type -- unlike statically typed languages
(e.g. C++), where a variable's type is fixed.

my_dogs = 2 # my_dogs is now an int


my_dogs = ['Sammy', 'Frankie'] # my_dogs is now a list -- totally legal!

Pros: faster to write, flexible. Cons: can cause subtle bugs -- always be aware of type().

● Augmented Assignment & type()


a += 10 # same as a = a + 10
a *= 2 # same as a = a * 2 (also: -=, /=)
type(a) # returns int, float, str, list, tuple, dict, set, or bool
PART 2

Core Data Structures

2.1 Dictionaries
Definition — A mapping -- a collection of key: value pairs. Unlike a sequence (list, string, tuple), a dictionary is
unordered and items are retrieved by key, not position. Values can be any Python object.

my_dict = {'key1': 'value1', 'key2': 'value2'}


my_dict['key2'] # 'value2' -- access by key

my_dict = {'key1': 123, 'key3': ['item0', 'item1', 'item2']}


my_dict['key3'][0] # 'item0' -- index into a value
my_dict['key3'][0].upper() # 'ITEM0' -- call a method on that value

my_dict['key1'] -= 123 # shorthand for my_dict['key1'] = my_dict['key1'] - 123

d = {}
d['animal'] = 'Dog'
d['answer'] = 42 # {'animal': 'Dog', 'answer': 42}

● Nesting Dictionaries
d = {'key1': {'nestkey': {'subnestkey': 'value'}}}
d['key1']['nestkey']['subnestkey'] # 'value' -- chain keys to go deeper

Method Returns

[Link]() view of all keys

[Link]() view of all values

[Link]() view of (key, value) tuples

NOTE keys()/values()/items() return VIEW objects, not independent lists -- cast with list() if you need a real list.

2.2 Tuples
Definition — Like a list, but immutable -- once created, it cannot be changed. Used when data must not be modified
(e.g. days of the week).

t = (1, 2, 3)
len(t) # 3
t = ('one', 2) # can mix types
t[0] # 'one' -- indexing works like a list
t[-1] # 2 -- negative indexing works too

[Link]('one') # 0 -- returns the index of a value


[Link]('one') # 1 -- counts occurrences
● Immutability in Action
t[0] = 'change' # TypeError: 'tuple' object does not support item assignment
[Link]('nope') # AttributeError: 'tuple' object has no attribute 'append'

NOTE Use tuples over lists when you need to GUARANTEE data won't be accidentally changed -- data integrity.

2.3 Sets and Booleans


Set -- Definition — An unordered collection of UNIQUE elements. Built with set().

x = set()
[Link](1)
[Link](2)
[Link](1) # ignored -- 1 already in the set; sets never store duplicates
x # {1, 2}

list1 = [1,1,2,2,3,4,5,6,1,1]
set(list1) # {1, 2, 3, 4, 5, 6} -- casting strips out duplicates

NOTE Curly braces {} here do NOT indicate a dictionary. A set is like a dictionary with only keys, no values.

Boolean -- Definition — True and False are Python's Boolean values (internally behave like 1 and 0).

a = True
1 > 2 # False -- comparison operators produce booleans
b = None # None is a placeholder object -- "nothing assigned yet"
print(b) # None

2.4 Files
Definition — Python uses file objects to read/write external files via the built-in open() function.

myfile = open('[Link]') # opens in READ mode by default


[Link]() # returns file contents as one string
[Link]() # '' -- cursor is now at the end!
[Link](0) # resets the read cursor back to the start
[Link]() # returns a LIST of lines (careful with huge files)
[Link]() # always close a file when done

Mode Meaning

'r' (default) Read only

'w' Write -- TRUNCATES / overwrites the file!

'w+' Read and write, truncates first

'a' Append -- pointer starts at end of file

'a+' Read and append; creates the file if missing

my_file = open('[Link]', 'w+')


my_file.write('This is a new line') # returns number of characters written
my_file.close()

my_file = open('[Link]', 'a+')


my_file.write('\nThis is text being appended to [Link]')

● Iterating Over a File


for line in open('[Link]'):
print(line)

NOTE By not calling .read(), the entire file is never loaded into memory at once -- useful for huge files.
PART 3

Comparison Operators & Boolean Logic

3.1 Comparison Operators


Definition — These operators compare two values and always return a Boolean (True/False).

Operator Meaning Example (a=3, b=4)

== equal to a == b -> False

!= not equal to a != b -> True

> greater than a > b -> False

< less than a < b -> True

>= greater than or equal to a >= b -> False

<= less than or equal to a <= b -> True

NOTE == is comparison; = is assignment. Mixing these up is one of the most common beginner bugs.

3.2 Chained Comparison Operators


Definition — Python lets you chain multiple comparisons together as shorthand for a compound Boolean expression.

1 < 2 < 3 # True -- same as: 1 < 2 and 2 < 3


1 < 3 > 2 # True -- same as: 1 < 3 and 3 > 2
1 == 2 or 2 < 3 # True -- 'or' only needs ONE side to be true
1 == 1 or 100==1 # True

● and → both sides must be True for the whole expression to be True.
● or → only one side needs to be True.
PART 4

Methods

Definition — Methods are functions built into objects. They perform an action ON the object they're called on, and
can take arguments just like a function.

[Link](arg1, arg2, ...)

NOTE Later (in OOP) you'll learn methods secretly take a hidden first argument, self, referring to the object itself.

lst = [1,2,3,4,5]
[Link](6) # adds an element to the END of the list -> [1,2,3,4,5,6]
[Link](2) # counts occurrences of a value -> 1

help([Link]) # prints documentation for a method

NOTE In Jupyter, press Tab after object. to see all available methods, and Shift+Tab inside a method call to see its
docstring.
PART 5

Functions, Scope & Advanced Arguments

5.1 Function Practice — Concepts Emphasized


The practice-exercise problems (Warmup -> Level 1 -> Level 2 -> Challenging) build fluency with progressively stacked
tools:
● Conditional logic (if/elif/else) — e.g. lesser_of_two_evens, makes_twenty
● String indexing/slicing & methods — animal_crackers, old_macdonald, master_yoda (" ".join([Link]()[::-1]))
● Iterating over sequences with loops — has_33 (adjacent pairs), paper_doll (building a string char by char)
● Multi-condition branching & accumulation — blackjack, summer_69 (a "skip mode" flag while looping)
● Sequential pattern matching — spy_game (tracking progress through [0,0,7] in order)
● Nested loops / algorithmic thinking — count_primes (checking divisibility for every candidate)
NOTE Core takeaway: as problems get harder, tools stack -- conditionals -> string/list methods -> loops -> loops-with-
state (a flag or counter carried between iterations).

5.2 Lambda Expressions, map() and filter()


map() — Definition — Applies ("maps") a function to every item in an iterable, returning a map object (cast to list()
to see results).

def square(num):
return num**2

my_nums = [1,2,3,4,5]
list(map(square, my_nums)) # [1, 4, 9, 16, 25]

filter() — Definition — Returns only the items of an iterable for which a function returns True. The function passed in
must return a Boolean.

def check_even(num):
return num % 2 == 0

nums = [0,1,2,3,4,5,6,7,8,9,10]
list(filter(check_even, nums)) # [0, 2, 4, 6, 8, 10]

Lambda — Definition — A way to write small, anonymous (unnamed) functions in a single line, without def. A
lambda's body must be a SINGLE expression -- not a block of statements -- and that value is automatically returned.

def square(num): return num**2 # a one-line def


square = lambda num: num ** 2 # the lambda equivalent

list(map(lambda num: num ** 2, my_nums)) # [1, 4, 9, 16, 25]


list(filter(lambda n: n % 2 == 0, nums)) # [0, 2, 4, 6, 8, 10]

lambda s: s[0] # grab first character


lambda s: s[::-1] # reverse a string
lambda x, y: x + y # multiple arguments are allowed

NOTE Use lambda for simple, throwaway, single-use functions (especially as an argument to map/filter). def handles
anything needing multiple statements or reuse.

5.3 Nested Statements & Scope (LEGB Rule)


Scope — Definition — The region of code where a variable name is recognized/visible. Every name lives in a
namespace, and Python looks it up using a strict search order.

Letter Scope Meaning

L Local Names assigned inside the current function (def or lambda)

E Enclosing Names in the local scope of any enclosing function (inner -> outer)

G Global Names assigned at the top level of the module/file

B Built-in Names Python pre-defines, like len, open, range

x = 25

def printer():
x = 50 # this x is LOCAL to printer() -- doesn't touch the global x
return x

print(x) # 25 -- global x, untouched


print(printer()) # 50 -- the function's own local x

● Enclosing Scope Example


name = 'This is a global name'

def greet():
name = 'Sammy' # enclosing-scope name
def hello():
print('Hello ' + name) # finds 'Sammy' via ENCLOSING scope
hello()

greet() # Hello Sammy

● Local Variables Don't Leak Out


x = 50
def func(x):
print('x is', x) # uses the local parameter x (=50, passed in)
x = 2 # reassigns the LOCAL x only
print('Changed local x to', x)

func(x)
print('x is still', x) # still 50 -- untouched outside the function

● The global Keyword


Required to MODIFY a global variable from inside a function (you can read an outer variable without it, but not reassign
it).

x = 50
def func():
global x # tells Python: "x" here refers to the module-level x
x = 2 # this DOES change the global x now
func()
print(x) # 2

NOTE Use global sparingly -- it makes code harder to trace. globals() and locals() inspect current namespaces.

5.4 *args and **kwargs


*args — Definition — Lets a function accept an arbitrary number of positional arguments, collected into a TUPLE. The
name args is just convention -- any name works if preceded by *.

def myfunc(*args):
return sum(args) * .05

myfunc(40, 60, 20) # 6.0

**kwargs — Definition — Lets a function accept an arbitrary number of keyword arguments, collected into a
DICTIONARY.

def myfunc(**kwargs):
if 'fruit' in kwargs:
print(f"My favorite fruit is {kwargs['fruit']}")
else:
print("I don't like fruit")

myfunc(fruit='pineapple') # My favorite fruit is pineapple


myfunc() # I don't like fruit

● Combining Both — Order Matters!


*args must always come before **kwargs, in both the function definition and the call.

def myfunc(*args, **kwargs):


print(f"I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}")
print(f"May I have some {kwargs['juice']} juice?")

myfunc('eggs', 'spam', fruit='cherries', juice='orange')


# I like eggs and spam and my favorite fruit is cherries
# May I have some orange juice?

NOTE Putting a keyword argument BEFORE a positional one raises a SyntaxError.

5.5 Functions & Methods Homework — Worked Solutions


# Volume of a sphere: (4/3) * pi * r^3
def vol(rad):
return (4/3) * (3.14) * (rad**3)
vol(2) # 33.49333333333333

# Range check (inclusive)


def ran_check(num, low, high):
if num in range(low, high+1):
print('{} is in range between {} and {}'.format(num, low, high))
else:
print('The number is outside the range.')

def ran_bool(num, low, high):


return num in range(low, high+1) # boolean-only version

# Count uppercase vs lowercase letters


def up_low(s):
d = {"upper": 0, "lower": 0}
for c in s:
if [Link]():
d["upper"] += 1
elif [Link]():
d["lower"] += 1
print("Upper case characters: ", d["upper"])
print("Lower case characters: ", d["lower"])

# Unique elements of a list (order-preserving)


def unique_list(lst):
x = []
for a in lst:
if a not in x:
[Link](a)
return x
# Alternative one-liner: list(set(lst)) -- does NOT preserve order

# Multiply all numbers in a list


def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total

# Palindrome check
def palindrome(s):
s = [Link](' ', '') # remove spaces so phrases work too
return s == s[::-1] # compare string to its reverse (slicing trick)

# Pangram check -- contains every letter of the alphabet at least once


import string
def ispangram(str1, alphabet=string.ascii_lowercase):
alphaset = set(alphabet)
str1 = [Link](" ", '').lower()
return set(str1) == alphaset
NOTE Recurring patterns: s[::-1] reverses any sequence via slicing. Converting to set() quickly checks "contains all of /
same unique elements as." A running-total accumulator (total = 1, then total *= x) is the standard loop pattern.
PART 6

Python Statements (Control Flow)

6.1 Introduction to Python Statements


● Python replaces { } and ; (used in C-like languages) with a colon : and whitespace/indentation.
● The end of a line is the end of a statement -- no semicolons needed.
● Indentation is not just style -- it is syntactically required and defines code blocks.
# Other languages: if (a>b){ a = 2; b = 4; }
# Python:
if a > b:
a = 2
b = 4

6.2 if / elif / else Statements


Definition — Conditional branching -- "if this happens, do this; otherwise, check the next condition."

if case1:
pass # perform action1
elif case2:
pass # perform action2
else:
pass # perform action3 (runs only if none of the above matched)

if True:
print('It was true!')

x = False
if x:
print('x was True!')
else:
print('I will be printed in any case where x is not true')

loc = 'Bank'
if loc == 'Auto Shop':
print('Welcome to the Auto Shop!')
elif loc == 'Bank':
print('Welcome to the bank!')
else:
print('Where are you?')

NOTE You can chain as many elif blocks as needed, but only ONE if and, at most, one final else.

6.3 for Loops


Definition — Iterates over items in a sequence (or any iterable) -- string, list, tuple, dict, etc.

for item in object:


pass # statements

17 % 5 # 2 -- remainder of 17/5
num % 2 == 0 # True when num is even

for num in [1,2,3,4,5,6,7,8,9,10]:


if num % 2 == 0:
print(num) # prints only even numbers

list_sum = 0 # running tally / accumulator pattern


for num in list1:
list_sum += num

for letter in 'This is a string.': # strings are iterable too


print(letter)

for t in (1,2,3,4,5): # so are tuples


print(t)

● Tuple Unpacking in a for Loop


list2 = [(2,4),(6,8),(10,12)]
for (t1, t2) in list2:
print(t1) # 2, 6, 10 -- unpacks each tuple automatically

● Iterating Dictionaries
d = {'k1':1,'k2':2,'k3':3}
for item in d: # iterates over KEYS only, by default
print(item)

for k, v in [Link](): # dictionary (key, value) unpacking


print(k, v)

list([Link]()) # cast a view object to an actual list


sorted([Link]()) # dictionaries are unordered -- sort explicitly

6.4 while Loops


Definition — Repeats a block of code as long as a condition remains True.

while test:
pass # code statements
else:
pass # runs once, only if the loop finished WITHOUT hitting a break

x = 0
while x < 10:
print('x is currently: ', x)
x += 1
else:
print('All Done!') # only prints if loop wasn't broken out of early

Statement Effect

break Immediately exits the closest enclosing loop

continue Skips the rest of this iteration, jumps back to the loop's top

pass Does nothing -- a syntactic placeholder

x = 0
while x < 10:
x += 1
if x == 3:
print('Breaking because x==3')
break # loop stops; the while's else will NOT run
else:
continue

NOTE Danger: while True: with no break runs forever -- always make sure a loop has a real exit condition.

6.5 Useful Operators

● range(start, stop, step)


Generates integers; stop is EXCLUDED (like slicing). range() is a generator -- cast with list() to materialize it.

list(range(0,11)) # [0,...,10]
list(range(0,11,2)) # [0,2,4,6,8,10] -- step size of 2

● enumerate()
Gives you the index AND the item together, avoiding manual counters.

for i, letter in enumerate('abcde'):


print(f"At index {i} the letter is {letter}")

● zip()
"Zips" two (or more) iterables together into pairs of tuples.

mylist1 = [1,2,3,4,5]
mylist2 = ['a','b','c','d','e']
list(zip(mylist1, mylist2)) # [(1,'a'), (2,'b'), (3,'c'), (4,'d'), (5,'e')]

● in / not in, min/max, random, input


'x' in ['x','y','z'] # True -- membership testing
'x' not in [1,2,3] # True

min(mylist); max(mylist) # smallest / largest value in an iterable


from random import shuffle, randint
shuffle(mylist) # shuffles a list IN PLACE (returns None)
randint(0, 100) # random int, inclusive of both ends

input('Enter Something: ') # pauses execution, returns typed input AS A STRING

6.6 List Comprehensions


Definition — A compact way to build a list in a single line -- effectively a for loop written inside [ ].

lst = [x for x in 'word'] # ['w','o','r','d']


lst = [x**2 for x in range(0,11)] # [0,1,4,9,...,100]
lst = [x for x in range(11) if x % 2 == 0] # [0,2,4,6,8,10] -- filter condition

fahrenheit = [((9/5)*temp + 32) for temp in [0,10,20.1,34.5]]

lst = [x**2 for x in [x**2 for x in range(11)]] # nested comprehension

NOTE General template: [ expression for item in iterable if condition ]

6.7 Statements Assessment — Worked Solutions


# Words starting with 's'
st = 'Print only the words that start with s in this sentence'
for word in [Link]():
if word[0] == 's':
print(word)

# Even numbers 0-10


list(range(0,11,2))

# Numbers 1-50 divisible by 3 (list comprehension)


[x for x in range(1,51) if x % 3 == 0]

# Words with even length


st = 'Print every word in this sentence that has an even number of letters'
for word in [Link]():
if len(word) % 2 == 0:
print(word + " <-- has an even length!")

# FizzBuzz -- classic multi-condition loop


for num in range(1,101):
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
print("Buzz")
else:
print(num)
# First letters of every word (list comprehension)
st = 'Create a list of the first letters of every word in this string'
[word[0] for word in [Link]()]

6.8 Guessing Game Challenge — Annotated Walkthrough


Concepts combined: while True loops, break/continue, input(), a list as running memory, and comparison logic.

import random
num = [Link](1,100) # secret number

guesses = [0] # placeholder; 0 is "falsy" so it signals "no guess yet"

# --- Loop 1: get a valid guess ---


while True:
guess = int(input("What is your guess? "))
if guess < 1 or guess > 100:
print('OUT OF BOUNDS! Please try again: ')
continue # skip straight back to the top, ask again
break # valid guess -- leave the loop

# --- Loop 2: full game logic ---


while True:
guess = int(input("What is your guess? "))

if guess < 1 or guess > 100:


print('OUT OF BOUNDS! Please try again: ')
continue

if guess == num:
print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')
break

[Link](guess)

# guesses[-2] is the PREVIOUS guess (or the 0 placeholder on turn 1)


if guesses[-2]: # truthy check: real previous guess?
if abs(num-guess) < abs(num-guesses[-2]):
print('WARMER!')
else:
print('COLDER!')
else: # first real guess
if abs(num-guess) <= 10:
print('WARM!')
else:
print('COLD!')

NOTE Key technique: using 0 as a placeholder works because 0 evaluates to False in a Boolean context, letting the code
distinguish "first guess" from "later guesses" without an extra counter variable.
QUICK-REFERENCE GLOSSARY
Core definitions worth memorizing

Term Definition

Mutable Can be changed after creation (list, dict, set)

Immutable Cannot be changed after creation (tuple, string, int, float)

Sequence An ordered collection accessed by index/position (str, list, tuple)

Mapping A collection accessed by key, not position (dict)

Iterable Any object you can loop over with for (str, list, tuple, dict, set, range, file)

Method A function that belongs to an object: [Link]()

Function A reusable, named (or anonymous/lambda) block of code, called independently:


function()

Scope Which part of the code a variable name is visible/accessible in

LEGB Search order for names: Local -> Enclosing -> Global -> Built-in

Generator Produces values on demand instead of storing them all in memory (range(), map())

Boolean True or False, the result of comparison/logical operations

*args Collects extra positional arguments into a tuple

**kwargs Collects extra keyword arguments into a dictionary

List comprehension One-line syntax to build a list: [expr for item in iterable if cond]

Covers all notebook content shared: Numbers, Variable Assignment, Dictionaries, Tuples, Sets/Booleans, Files, Comparison Operators,
Methods, Function Practice, Lambda/Map/Filter, Scope, args/kwargs, Functions Homework, and all Statements notebooks.

You might also like