0% found this document useful (0 votes)
3 views4 pages

Python Learning Notes

This document serves as a practical reference and study guide for Python programming, covering core syntax, structures, and idioms. It includes sections on variables, data types, control flow, core collections, functions, object-oriented programming, and exception handling. The guide emphasizes Python's readability and flexibility, making it suitable for both beginners and experienced programmers.
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)
3 views4 pages

Python Learning Notes

This document serves as a practical reference and study guide for Python programming, covering core syntax, structures, and idioms. It includes sections on variables, data types, control flow, core collections, functions, object-oriented programming, and exception handling. The guide emphasizes Python's readability and flexibility, making it suitable for both beginners and experienced programmers.
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 Essentials

Comprehensive Core Syntax, Structures, and Idioms

A PRACTICAL REFERENCE AND STUDY GUIDE

1. Introduction & Setup


Python is a high-level, interpreted, dynamically typed, and garbage-collected programming language designed
with an emphasis on code readability. Its syntax allows programmers to express concepts in fewer lines of
code than languages like C++ or Java.

Note: Python uses indentation (whitespace) to delimit code blocks rather than curly braces {} or
keywords like begin/end .

2. Variables and Basic Data Types


In Python, variables do not require explicit declaration to reserve memory space. The declaration happens
automatically when a value is assigned to a variable.

Data Type Description Example Syntax

int Arbitrary precision integers age = 25

float Double-precision floating point numbers pi = 3.14159

str Immutable sequences of Unicode characters name = "Alice"

bool Boolean values is_valid = True

NoneType Special constant representing absence of value result = None

Python Programming Essentials 1


Type Casting
You can convert between types explicitly using constructor functions:

x = int("10") # Convert string to int


y = float(5) # Convert int to float
z = str(23.4) # Convert float to string

3. Control Flow
Control flow structures control the execution path of a program based on conditional evaluation and loops.

Conditional Statements

score = 85

if score >= 90:


print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C")

Loops
Python supports for loops (used for iterating over a sequence) and while loops (executed as long as a
condition holds true).

# Iterating over a range


for i in range(3):
print(f"Index: {i}")

# While loop
count = 0
while count < 3:
print(f"Count: {count}")
count += 1

4. Core Collections & Data Structures


Python offers built-in data structures that are flexible and powerful.

Python Programming Essentials 2


Lists (Mutable Sequences)

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


[Link]("orange") # Modifies the list
print(fruits[0]) # Access by index -> "apple"
print(fruits[1:3]) # Slicing -> ['banana', 'cherry']

Tuples (Immutable Sequences)

coordinates = (10.0, 20.0)


# coordinates[0] = 15.0 # Raises TypeError: immutable

Dictionaries (Key-Value Pairs)

user = {"name": "Bob", "age": 30}


print(user["name"]) # Accessing value -> "Bob"
user["email"] = "bob@[Link]" # Adding a new pair

Sets (Unordered Unique Collections)

unique_numbers = {1, 2, 3, 3, 4}
print(unique_numbers) # Output: {1, 2, 3, 4}

5. Functions and Scope


Functions are defined using the def keyword. They allow modular code grouping and execution reuse.

def greet(name, greeting="Hello"):


"""Docstring explaining the function functionality."""
return f"{greeting}, {name}!"

message = greet("Alice")
print(message) # Output: Hello, Alice!

Lambda Functions
Small anonymous functions can be created using the lambda keyword:

square = lambda x: x ** 2
print(square(4)) # Output: 16

Python Programming Essentials 3


6. Object-Oriented Programming (OOP)
Python is a fully object-oriented language, allowing the creation of classes to encapsulate attributes and
behaviors.

class Animal:
def __init__(self, name):
[Link] = name # Instance attribute

def speak(self):
return "Generic sound"

class Dog(Animal): # Inheritance


def speak(self): # Polymorphism (Method Overriding)
return "Woof!"

my_dog = Dog("Buddy")
print(my_dog.name) # Output: Buddy
print(my_dog.speak()) # Output: Woof!

7. Exception Handling
Errors during execution can be gracefully managed using try , except , else , and finally blocks.

try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error encountered: {e}")
else:
print("Executed safely with no exceptions.")
finally:
print("This block always runs.")

Python Programming Essentials 4

You might also like