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

Python Notes

This document provides comprehensive Python programming notes for beginners, covering essential topics such as basic syntax, data types, control flow, functions, and object-oriented programming. It emphasizes an example-focused style and includes practical applications of libraries like NumPy, Pandas, and Flask. The notes aim to guide first-time learners through Python's features and functionalities in a structured manner.

Uploaded by

labdino2
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 views16 pages

Python Notes

This document provides comprehensive Python programming notes for beginners, covering essential topics such as basic syntax, data types, control flow, functions, and object-oriented programming. It emphasizes an example-focused style and includes practical applications of libraries like NumPy, Pandas, and Flask. The notes aim to guide first-time learners through Python's features and functionalities in a structured manner.

Uploaded by

labdino2
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

Comprehensive Python Notes for First-Time Learner with Example-Focused Style Including NumPy,

Pandas, and Flask

Python Programming Notes (Beginner to Fluent)

Introduction to Python

Python is a high-level, interpreted language that is easy to learn and very powerful. It has high-level
data structures and supports object-oriented [Link]. Python uses indentation
(whitespace) to define code blocks instead of braces, making its syntax clean and readable. The
language is dynamically typed (you don’t declare variable types explicitly) and comes with an
extensive standard library and vibrant ecosystem. Beginners often find Python’s syntax simple and its
interactive interpreter great for experimenting.

 Official Description: Python’s own tutorial describes it as “easy to learn, powerful… with
elegant syntax and dynamic typing”[Link]. This makes it ideal for rapid
development and scripting.

 Getting Started: To try Python, install it from [Link] or use an online REPL. You can write
code in a file (.py) and run it, or use the interactive prompt (>>>).

Basic Syntax and Variables

Python code consists of statements and expressions. Each statement usually ends at the end of a
line. Key points:

 Comments: Use # to add a comment. Everything from # to the end of the line is ignored by
[Link].

python

CopyEdit

# This is a comment. Python ignores it.

x = 5 # This is a comment after a statement

 Printing: Use print() to output data. For example:

python

CopyEdit

name = "Alice"

print("Hello,", name) # Output: Hello, Alice

 Variables: Variables are created by assignment. You do not declare types explicitly. Python
figures out the type at runtime.

python

CopyEdit

age = 30 # age is an int

price = 19.99 # price is a float


greeting = "Hi" # greeting is a string

is_valid = True # is_valid is a boolean

 Naming Rules: Variable names can include letters, digits, and underscores, but cannot start
with a digit. Conventionally use lowercase names with underscores (my_var).

Data Types

Python has several built-in data types. Important ones include:

 Numbers: int (integers), float (floating-point), and complex (complex numbers, using j for
imaginary part). Python even has Decimal and Fraction for precise arithmetic
[Link].

 Strings: Sequences of characters, denoted by quotes. Can use single ('...') or double ("...")
quotes [Link]. Multi-line strings use triple quotes ('''...''').

 Booleans: The bool type has two values, True and False, used in logical operations.

 None: A special type NoneType with the single value None, used to denote “no value”.

Strings and Text Manipulation

Strings (str) are immutable sequences of [Link]. Key points:

 Quotes: You can write strings in single or double quotes:

python

CopyEdit

s1 = 'Hello'

s2 = "World"

s3 = 'He said "Hello"' # Use opposite quotes to include quotes in text

s4 = "It's fine" # Use double quotes to include a single quote

 Escaping: Use backslash \ to escape quotes or special characters: \', \", \\, \n (newline), etc.
[Link]. Or use raw strings (prefix r) to ignore escapes.

 Concatenation and Repetition: You can join strings with + and repeat with *:

python

CopyEdit

print("Hi " + "there!") # Hello there!

print("na" * 4 + " Batma" + "n") # nanana Batman

 Formatted Strings (f-strings): Prefix a string with f to embed expressions inside {}


[Link]. This is a powerful way to format output:

python

CopyEdit
year = 2025

name = "Alice"

print(f"{name} learned Python in {year}.")

# Output: Alice learned Python in 2025.

Reference: Formatted string literals (f-strings) let you include Python expressions inside strings by
prefixing the string with [Link].

Lists

Lists are mutable sequences (ordered collections) of arbitrary [Link]. You can add,
remove, and change elements.

 Creation: Use square brackets:

python

CopyEdit

numbers = [1, 2, 3, 4]

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

mixed = [1, "two", 3.0, False]

 Indexing & Slicing: Access elements by index (0-based). Negative indices count from the end
(-1 is last element). Slicing lets you get sublists: lst[1:4] gives elements at indices 1,2,3.

python

CopyEdit

print(numbers[0]) # 1

print(numbers[-1]) # 4

print(fruits[0:2]) # ['apple', 'banana']

 Modifying: Lists support methods like .append(x), .pop(), .remove(x), .sort(), etc. For
example:

python

CopyEdit

[Link](5) # numbers is now [1,2,3,4,5]

[Link]() # removes and returns last element

[Link]() # sorts the list in place

 As Stacks/Queues: Lists can act as stacks using append() and pop()[Link]. (For
queues, use [Link] for [Link].)

Tuples
Tuples are like lists but immutable (cannot change them after creation)[Link]
[Link]. They use parentheses (a, b, c) (commas actually create them). Useful for fixed
collections of items. Example:

python

CopyEdit

point = (2, 3) # a 2D point

person = ("Alice", 30)

You cannot do person[0] = "Bob" (that would error). Tuples can be used as dictionary keys if they
contain only immutable elements.

 Unpacking: You can unpack a tuple into variables:

python

CopyEdit

x, y = point

print(x, y) # 2 3

 Single-element tuple: Note the comma: (42,) is a tuple, (42) is just 42.

Sets

A set is an unordered collection of unique [Link]. Use {...} or set([...]). Sets are great
for removing duplicates and testing membership. Example:

python

CopyEdit

fruits = {"apple", "orange", "apple", "pear"}

print(fruits) # {'apple', 'orange', 'pear'} (duplicates removed)

print("apple" in fruits) # True

Sets support operations like union |, intersection &, difference -, [Link].

 Empty set: Use set(), since {} is an empty [Link].

 Set Comprehension: Similar to list comprehensions, e.g. {x for x in range(5) if x%2==0}


produces {0,2,4}.

Dictionaries

Dictionaries (dict) are mappings from keys to values. Keys must be immutable (like strings, numbers,
or tuples) and are unique. Use {key: value} pairs. For example:

python

CopyEdit

person = {"name": "Bob", "age": 25}


print(person["name"]) # "Bob"

person["age"] = 26 # update value for key "age"

A dictionary is essentially a set of key:value [Link]. Use {} for an empty dict. You can
add (person["city"] = "NY"), retrieve (person[key]), or delete (del person[key]) entries.

Data Type Shortcuts and Conversions

 Multiple assignment: a, b = 5, 10 sets a=5, b=10.

 Swapping: a, b = b, a swaps two variables without a temporary.

 Casting: Use int(x), float(x), str(x) to convert types. For example, num = int("123").

Operators

Python supports a variety of operators:

 Arithmetic Operators: + (add), - (subtract), * (multiply), / (divide), // (floor division), %


(modulo), ** (power). For example: 2 + 2 yields 4, and 50 - 5*6 yields [Link].

 Comparison Operators: ==, !=, <, >, <=, >= produce boolean results. You can chain
comparisons: e.g. 1 < x < 10.

 Logical Operators: and, or, not combine boolean expressions. For example, (x > 0) and (x <
10) is true if x is between 0 and 10.

 Assignment Operators: =, and augmented forms like +=, -=, *=, /=, etc., modify variables in-
place. E.g. x += 1 increments x by 1.

 Membership Operators: in, not in test membership (e.g. "a" in "cat" is True).

 Identity Operators: is, is not check if two names refer to the same object.

Control Flow

Conditionals (if / elif / else)

Use if to run code only when a condition is true. Use elif (short for “else if”[Link]) and else
for additional branches. Example:

python

CopyEdit

x = int(input("Enter an integer: "))

if x < 0:

print("Negative number")

elif x == 0:

print("Zero")

else:

print("Positive number")
 The if statement tests a condition.

 You can have multiple elif branches and an optional else.

 According to Python docs, elif helps avoid excessive indentation by combining multiple
[Link].

Loops (for and while)

for loop: Iterates over items of a sequence (like a list or string) in [Link]. Unlike some
languages, Python’s for does not use a loop index by default; it loops directly over elements.
Example:

python

CopyEdit

words = ['cat', 'window', 'defenestrate']

for w in words:

print(w, len(w))

# cat 3

# window 6

# defenestrate 12

This loop prints each word and its length.

 To loop over a range of numbers, use range(n), which generates 0,1,...,[Link]:

python

CopyEdit

for i in range(5):

print(i) # prints 0,1,2,3,4

You can also do range(start, stop, step). Note the end-point is [Link].

 while loop: Continues as long as a condition is true. Example:

python

CopyEdit

count = 0

while count < 3:

print("Count is", count)

count += 1

 Loop Control: Use break to exit the innermost loop immediately, and continue to skip to the
next [Link]. For example:
python

CopyEdit

for n in range(2, 10):

for x in range(2, n):

if n % x == 0:

print(f"{n} equals {x} * {n//x}")

break # exit inner loop

This finds and prints a factor of n then breaks out of the inner [Link].

 Loop else clause: (Advanced) Python allows an else after a loop, which runs if the loop
finished normally (no break). For example:

python

CopyEdit

for x in range(2, 5):

if x == 3:

break

else:

print("Loop ended without break")

Here the else block is skipped because break occurred. If no break happens, the else block would run
[Link].

Functions

Functions encapsulate reusable code. Use def to define [Link]. For example:

python

CopyEdit

def greet(name):

"""Return a greeting for the given name."""

return f"Hello, {name}!"

print(greet("Alice")) # Hello, Alice!

 def syntax: Start with def, function name, parentheses with parameters, then a colon. The
function body is [Link].

 Docstrings: The first statement in a function can be a string literal (triple quotes) called a
[Link]. It describes what the function does. Example:
python

CopyEdit

def fib(n):

"""Print Fibonacci numbers less than n."""

a, b = 0, 1

while a < n:

print(a, end=' ')

a, b = b, a+b

print()

Here """Print Fibonacci numbers less than n.""" is a docstring used for documentation
[Link].

 Return Value: Use return to give back a value. If no return is specified, the function returns
None by [Link]. For example, fib() above prints values and returns None.

 Arguments: Functions can take arguments (positional, keyword, default). We won’t cover all
details here, but you can define defaults (def add(x, y=0):) and accept arbitrary args (*args,
**kwargs).

Classes and Objects (Object-Oriented Programming)

Python is object-oriented, and classes let you define new object types. A class is like a blueprint for
creating objects (instances). Example structure:

python

CopyEdit

class Person:

def __init__(self, name, age):

[Link] = name # attribute

[Link] = age

def introduce(self):

return f"My name is {[Link]}, I am {[Link]}."

# Create an object (instance)

p = Person("Bob", 25)

print([Link]) # Bob

print([Link]()) # My name is Bob, I am 25.


 Defining a class: Use class ClassName: followed by indented definitions. Commonly, an
__init__ method initializes object [Link].

 __init__: This special method runs when a new object is created. Its first parameter is always
self, representing the instance. You assign attributes via [Link] = [Link].

 Instantiating: Call ClassName(...) to create an object. You can then access attributes (e.g.
[Link]) and methods (e.g. [Link]()).

 Methods: Functions defined inside a class act on instances. In the example, introduce() is a
method.

 __str__: (Optional) Define __str__(self) to control what print(obj) shows. By default, printing
an object gives something like <Person object at 0x...>.

Reference Example: A tutorial shows creating a Person class with __init__ to set name and age
[Link].

Modules and Packages

Organize code into modules (Python files) and packages (directories of modules). Key points:

 Importing: Use import module_name to bring in definitions from another file or library. For
example, import math lets you use [Link]().

 from imports: You can import specific names: from math import sqrt, pi or everything (from
math import *). (Importing * is generally discouraged outside interactive use)
[Link].

python

CopyEdit

import math

print([Link])

from math import sqrt

print(sqrt(16))

 Search Path: Python looks for modules in built-in locations, the current directory, and paths
in [Link]. Ensure your .py files (modules) are in these paths, or use packages with
__init__.py.

 Creating modules: Any .py file is a module. If you have [Link] with functions, you can do
import fibo or from fibo import *. The module’s name is available as __name__ inside it
[Link].

 Standard Library: Python comes with many built-in modules (sys, os, random, etc.). Use
them via import.

 Installing Packages: Use pip install to add third-party libraries (e.g. NumPy, Pandas, Flask).
After installing, import works the same way.
File Handling

Python lets you read and write files using built-in functions. The open() function is key:

python

CopyEdit

f = open('[Link]', 'r', encoding='utf-8') # open for reading (default 'r')

text = [Link]() # read entire file into a string

[Link]() # close the file

 open(filename, mode, encoding): Returns a file [Link]. Modes: 'r' = read, 'w'
= write (truncates file), 'a' = append, 'r+' = read/write. Add 'b' for binary mode. The default
mode is 'r' if [Link].

 Reading:

o [Link]() reads the whole file (or a given number of bytes).

o [Link]() reads one line at a time.

o [Link]() returns a list of all lines.

o Or iterate: for line in f: ....

 Writing: [Link]("some text") writes strings (in text mode). In binary mode, write bytes.

 Closing: Always [Link]() after done to free resources. Better yet, use a with statement:

python

CopyEdit

with open('[Link]', 'w', encoding='utf-8') as f:

[Link]("Hello\n")

# no need to call [Link](); it's automatic

The with block ensures the file is closed automatically, even if errors [Link]. This is
the recommended practice.

Example: Read a file and print its contents:

python

CopyEdit

with open('[Link]', 'r', encoding='utf-8') as file:

contents = [Link]()

print(contents)

Exception Handling

Use try/except to handle runtime errors (exceptions) gracefully. Syntax:


python

CopyEdit

try:

risky_operation()

except SomeError as e:

handle_error()

else:

run_if_no_error()

finally:

cleanup()

 Basic: Wrap code in try:. If an exception occurs, execution jumps to the matching except
block. Example:

python

CopyEdit

try:

value = int(input("Enter a number: "))

except ValueError:

print("That was not a valid number.")

else:

print(f"You entered {value}.")

Here, if int() fails, the ValueError block runs; otherwise, the else block executes.

 Multiple except: You can catch different exceptions separately. Only the first matching except
runs.

 finally: Code under finally: always runs last, regardless of exceptions. Use it for cleanup (e.g.,
closing files). Python docs note that a finally clause will execute as the last task, whether or
not an exception [Link].

 Raising Exceptions: Use raise ExceptionType("message") to signal an error.

 Common Example:

python

CopyEdit

try:

f = open("[Link]")
except FileNotFoundError:

print("Config file not found, using defaults.")

else:

data = [Link]()

[Link]()

Useful Patterns, Tips and Tricks

 List Comprehensions: A concise way to create lists from existing [Link].

python

CopyEdit

squares = [x**2 for x in range(10)] # [0,1,4,...,81]

evens = [x for x in range(10) if x%2==0] # [0,2,4,6,8]

This is equivalent to using a loop with append, but shorter and often [Link].

 Dictionary and Set Comprehensions: Similar syntax for dicts ({k:v for ...}) and sets ({x for ...}).

 enumerate(): When looping, use for idx, item in enumerate(list): to get index and value
together.

 zip(): Iterate multiple lists in parallel: for a, b in zip(list1, list2): ....

 F-Strings: As shown above, f-strings are a handy shortcut for string formatting
[Link].

 Ternary Operator: A compact if for expressions: x = a if condition else b.

 Unpacking: You can unpack tuples/lists directly: a, b = 1, 2. Also:

python

CopyEdit

nums = [1,2,3,4]

first, *middle, last = nums

print(first, middle, last) # 1 [2,3] 4

 Swapping: a, b = b, a swaps two variables in one line.

 Default args caution: Using mutable defaults can lead to surprises (learn more later).

 Error Messages: Read tracebacks; they point to the error type and line. They’re your best
debugging friend as you learn.

Introduction to Key Libraries

NumPy Basics
NumPy is the fundamental library for numerical computing in Python. Its core is the ndarray, a
homogeneous N-dimensional array. According to NumPy docs, “NumPy’s main object is the
homogeneous multidimensional array… all of the same type” indexed by non-negative integers
[Link]. Key points:

 Creating Arrays:

python

CopyEdit

import numpy as np

a = [Link]([1, 2, 3, 4]) # 1D array

b = [Link]((2,3)) # 2x3 array of zeros

c = [Link](5) # [0,1,2,3,4]

 Dimensions and Shape: [Link] gives number of axes (dimensions), [Link] is a tuple of
array [Link]. E.g., [Link] == (2,3).

 Array Operations: Arithmetic on arrays is element-wise:

python

CopyEdit

x = [Link]([1,2,3])

print(x * 2) # [2,4,6]

print(x + x) # [2,4,6]

 Indexing/Slicing: Similar to lists but more powerful (multi-dimensional slicing).

 Performance: NumPy operations are implemented in C and much faster than pure Python
loops for large data. It’s used for vectorized computations (linear algebra, Fourier transforms,
etc.).

For more, see the [NumPy Quickstart Guide] which explains arrays and [Link].

Pandas Basics

Pandas is a library for data analysis, built on NumPy. It provides the Series and DataFrame data
[Link]:

 Series: 1D labeled array (like a column) that can hold various types.

 DataFrame: 2D table of rows and columns (like a spreadsheet)[Link]. Each


column in a DataFrame is a Series.

Example usage:

python

CopyEdit

import pandas as pd
import numpy as np

# Create DataFrame from a NumPy array

dates = pd.date_range("20230101", periods=5)

df = [Link]([Link](5,3), index=dates, columns=list("ABC"))

print([Link]()) # show first rows

# Create from dict

df2 = [Link]({"Name": ["Alice", "Bob"], "Age": [25, 30]})

print(df2)

 Reading data: Pandas can read CSV, Excel, JSON, SQL, etc. For example,
pd.read_csv("[Link]") reads a CSV into a [Link].

 Writing data: Use methods like df.to_csv("[Link]") to [Link].

 Basic operations: You can select columns (df["A"]), filter rows (df[df["A"] > 0]), add/drop
columns, group data, etc.

 Viewing data: [Link]() shows top rows, [Link]() bottom [Link]. These are
useful to inspect your data quickly.

Flask Basics

Flask is a lightweight web framework for building web apps or APIs. A minimal Flask app looks like
[Link]:

python

CopyEdit

from flask import Flask

app = Flask(__name__)

@[Link]("/")

def hello_world():

return "<p>Hello, World!</p>"

if __name__ == "__main__":

[Link](debug=True)
 Flask class: You create a Flask instance (often passing __name__) which becomes your WSGI
[Link].

 Routes: Use the @[Link]("/path") decorator to bind a URL path to a Python function
[Link]. When a user visits that URL, Flask calls your function and returns
its result.

 Running the app: Running this script and visiting [Link] in a browser will
display Hello, World!. The content type is HTML by default, so you can return HTML strings.

 Development server: Flask includes a built-in server for testing (not for production). Running
with debug=True auto-reloads on code changes and shows an interactive debugger on
errors.

For example, you might define multiple routes and even dynamic routes like /user/<username>. The
Flask Quickstart guide provides more [Link].

Daily Learning Roadmap (1–2 hours/day)

A structured plan helps reinforce concepts. Here’s a suggested roadmap for a beginner (~4 weeks).
Each day ~1–2 hours:

1. Day 1: Setup & “Hello, World!” – Install Python, set up environment (IDE or editor), run first
script printing “Hello World”. Learn how to run Python from a file and interactively.

2. Day 2: Basic Syntax, Variables, Data Types – Study variables, integers, floats, strings,
booleans. Practice assignments and printing. Example: write code that does simple math and
prints results.

3. Day 3: Strings & Input/Output – Dive into string manipulation (concatenation, formatting, f-
[Link]). Use input() to get user data. Example: a program that asks name
and greets the user.

4. Day 4: Lists, Tuples, Sets, Dicts – Learn and practice each built-in data structure. Write code
to create and modify lists, iterate over them, and use list methods. Do examples with tuples,
[Link], and dictionaries.

5. Day 5: Operators & Expressions – Experiment with arithmetic, comparison, and logical
operators. Write small expressions and predict the output. Example: calculate and display
the result of some math formula.

6. Day 6: If Statements – Write conditional logic. Example: check even/odd, positive/negative,


or simple grading logic (A/B/C grade based on score).

7. Day 7: For Loops & Range – Loop over sequences. Use range()[Link]. Practice with
lists and strings. Example: print each character of a string on a new line.

8. Day 8: While Loops & Loop Control – Practice while. Learn break and continue
[Link]. Example: loop until user enters a specific word.

9. Day 9: Functions – Write simple functions using [Link]. Use parameters and
return values. Example: a function that calculates factorial or Fibonacci.
10. Day 10: Modules & Imports – Learn to import Python modules. Explore the math module
and use functions like [Link]() or [Link]. Create your own small module (e.g.,
[Link]) and import from it.

11. Day 11: File I/O – Practice reading from and writing to [Link].
Example: read a text file and count the number of lines or words. Use with open(...).

12. Day 12: Exception Handling – Introduce try/except [Link].


Example: safely handle invalid input (e.g., catching ValueError when converting to int).

13. Day 13: Classes/Objects – Create a class, use __init__, and instantiate objects (see the Person
example above)[Link]. Practice adding methods and attributes.

14. Day 14: Project Practice – Combine topics: e.g., read data from a file, process it, and write
results. Practice debugging errors.

After the first two weeks, start exploring libraries:

 Week 3: NumPy & Pandas Intro – Follow beginner tutorials. Practice NumPy arrays (creation,
indexing, arithmetic)[Link]. Use Pandas to load a CSV (e.g., user makes a simple data
file), explore with [Link](), filter rows, etc.

 Week 4: Web Basics & Flask – Learn basic web concepts. Build and run the minimal Flask app
[Link]. Make simple routes returning HTML
or JSON.

Continue with daily practice and small projects. Review and repeat exercises. This roadmap is
flexible: spend extra days on topics that need reinforcement. The key is consistent practice and
building projects bit by bit. You’ll become more fluent over time.

Happy coding! You’re building a strong Python foundation. Each new concept builds on the last, and
practicing with code examples is the best way to learn.

You might also like