Python Code Example Handbook – Sample Script Coding Tutorial for Beginners
Python has taken the programming world by storm. According to the TIOBE Index, as of 2023, Python is the #1 most popular programming language, overtaking Java and C. Its rise to the top is due in large part to its beginner-friendliness, versatility, and thriving community.
As a full-stack developer who uses Python daily, I can attest to its power and simplicity. Whether you‘re interested in web development, data science, machine learning, or automation, Python is a fantastic language to learn. In this comprehensive guide, we‘ll dive into the fundamentals of Python programming with code examples for each concept. By the end, you‘ll have a strong foundation to build your own projects.
Python Basics
Variables and Data Types
Variables are used to store data values. Python is a dynamically-typed language, meaning you don‘t need to explicitly declare a variable‘s type. Python will infer it based on the value assigned. Here are the built-in data types:
- Numeric types:
int
,float
,complex
- Sequences:
list
,tuple
,range
- Text:
str
- Boolean:
bool
- Dictionaries:
dict
x = 5 # int
price = 9.99 # float
name = "Alice" # str
is_new = True # bool
numbers = [1, 2, 3] # list
Operators
Python supports various operators for performing operations on variables and values:
- Arithmetic:
+
,-
,*
,/
,%
,**
,//
- Assignment:
=
,+=
,-=
,*=
,/=
,%=
,**=
,//=
- Comparison:
==
,!=
,>
,<
,>=
,<=
- Logical:
and
,or
,not
x = 10
y = 3
z = x + y # Addition: 13
z = x - y # Subtraction: 7
z = x * y # Multiplication: 30
z = x / y # Division: 3.33
z = x % y # Modulo: 1
z = x ** y # Exponentiation: 1000
x += 1 # Increment x by 1
y -= 1 # Decrement y by 1
print(x > y) # Greater than: True
print(x == 10) # Equal to: False
print(x != 5) # Not equal to: True
Control Flow
Conditional Statements
Conditional statements allow you to execute code based on whether certain conditions are true or false. Python uses if
, elif
(else if), and else
keywords.
age = 25
if age < 18:
print("You are a minor")
elif age >= 18 and age < 65:
print("You are an adult")
else:
print("You are a senior")
Loops
Loops allow you to repeatedly execute a block of code. The two main types are:
for
loops: iterate over a sequencewhile
loops: repeat as long as a condition is true
# For loop to print squares of numbers 1 to 5
for i in range(1, 6):
print(i**2)
Output:
1
4
9
16
25
# While loop to print numbers 1 to 5
i = 1
while i <= 5:
print(i)
i += 1
Output:
1
2
3
4
5
Functions
Functions are reusable blocks of code that perform a specific task. They promote code modularity and reusability. In Python, we define functions using the def
keyword followed by the function name, parentheses containing any input parameters, and a colon. The function body is indented.
def greet(name):
"""Prints a greeting to the given person."""
print("Hello, " + name + "!")
greet("John")
Output:
Hello, John!
Python functions can accept multiple arguments and return values using the return
keyword. Default parameter values can also be specified.
def add_numbers(x, y=10):
"""Adds two numbers together."""
return x + y
print(add_numbers(5)) # Output: 15
print(add_numbers(5, 7)) # Output: 12
Data Structures
Python provides several built-in data structures to efficiently store and organize data.
Lists
Lists are ordered, mutable sequences that can hold items of different types. They are defined using square brackets []
.
numbers = [1, 2, 3, 4, 5]
Some common list operations:
numbers = [1, 2, 3]
print(len(numbers)) # Get length: 3
print(numbers[0]) # Access by index: 1
numbers.append(4) # Append new item: [1, 2, 3, 4]
numbers.pop() # Remove last item: [1, 2, 3]
numbers[1] = 10 # Modify by index: [1, 10, 3]
numbers.sort() # Sort list in-place: [1, 3, 10]
Lists can be sliced using the [start:end:step]
syntax to extract sublists.
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # [2, 3, 4]
print(numbers[::2]) # [1, 3, 5]
print(numbers[::-1]) # [5, 4, 3, 2, 1]
Tuples
Tuples are similar to lists but are immutable, meaning their values cannot be changed after creation. They are defined using parentheses ()
.
point = (3, 5)
Tuples are commonly used to group related values together.
person = ("Alice", 30, "New York")
name, age, city = person # Tuple unpacking
print(name) # Alice
print(age) # 30
Dictionaries
Dictionaries are unordered collections of key-value pairs, providing fast lookups by key. They are defined using curly braces {}
.
person = {"name": "Alice", "age": 30, "city": "New York"}
Dictionary operations:
person = {"name": "Alice", "age": 30}
print(person["name"]) # Get value by key: Alice
print(person.get("age")) # Get value by key: 30
person["email"] = "[email protected]" # Add new key-value pair
person["age"] = 31 # Modify existing value
del person["city"] # Remove key-value pair
Dictionaries are commonly used to represent structured data or configuration settings in Python programs.
Sets
Sets are unordered collections of unique elements. They are defined using curly braces {}
like dictionaries but without key-value pairs.
fruits = {"apple", "banana", "orange"}
Set operations:
a = {1, 2, 3}
b = {2, 3, 4}
print(a | b) # Union: {1, 2, 3, 4}
print(a & b) # Intersection: {2, 3}
print(a - b) # Difference: {1}
print(a ^ b) # Symmetric difference: {1, 4}
Sets are useful for removing duplicates and performing mathematical set operations.
Advanced Topics
List Comprehensions
List comprehensions provide a concise way to create lists based on existing lists or other iterables. They consist of an expression followed by a for
clause and zero or more if
clauses, all inside square brackets.
# List comprehension to create list of squares
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# List comprehension with conditional
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
Dictionary and set comprehensions follow a similar syntax but use curly braces.
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Set comprehension
squares_set = {x**2 for x in range(1, 6)}
print(squares_set) # {1, 4, 9, 16, 25}
Lambda Functions
Lambda functions are small, anonymous functions defined using the lambda
keyword. They can take any number of arguments but can only have one expression.
# Lambda function to square a number
square = lambda x: x ** 2
print(square(5)) # 25
Lambda functions are often used in combination with built-in functions like map()
, filter()
, and reduce()
.
# Map lambda function to list
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
print(squares) # [1, 4, 9, 16, 25]
# Filter list using lambda function
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
Regular Expressions
Regular expressions (regex) are a powerful tool for pattern matching and manipulation of strings. Python provides the re
module for working with regular expressions.
import re
text = "The quick brown fox jumps over the lazy dog."
# Check if string contains "fox"
print(re.search("fox", text)) # <re.Match object; span=(16, 19), match=‘fox‘>
# Find all occurrences of "the"
print(re.findall("the", text)) # [‘the‘, ‘the‘]
# Replace "dog" with "cat"
print(re.sub("dog", "cat", text)) # The quick brown fox jumps over the lazy cat.
Learning regex can greatly enhance your string processing capabilities in Python.
Python Ecosystem
One of Python‘s greatest strengths is its vast ecosystem of libraries and frameworks. Some popular ones include:
- Web Development: Django, Flask, FastAPI
- Data Science: NumPy, Pandas, Matplotlib
- Machine Learning: scikit-learn, TensorFlow, PyTorch
- GUI Development: Tkinter, PyQt, wxPython
- Test Automation: Selenium, pytest, Robot Framework
Python also has a large standard library providing modules for common tasks like file I/O, networking, multithreading, and more. It‘s worth exploring the standard library to see what‘s available before installing third-party packages.
To install additional packages, Python provides the pip
package manager. You can install packages from the command line using pip install package_name
.
Resources for Learning
The Python community offers a wealth of resources for learners of all levels:
- Official Python Documentation: Comprehensive reference for the Python language and standard library
- Python.org Beginners Guide: Collection of tutorials and resources for beginners
- Real Python Tutorials: In-depth tutorials on various Python topics
- Codecademy Python Course: Interactive online course for learning Python
- Automate the Boring Stuff with Python: Free online book teaching practical Python programming
As you progress in your Python journey, I encourage you to practice regularly, work on projects, and participate in coding challenges. Sites like HackerRank, LeetCode, and Project Euler offer great problem-solving practice.
Conclusion
Python is a powerful, versatile language that can take you from beginner to professional. Its clean syntax, extensive ecosystem, and supportive community make it an excellent choice for learners.
As a full-stack developer, I use Python daily for everything from scripts to web applications to data analysis. Its simplicity and expressiveness allow me to focus on solving problems rather than getting bogged down in language complexities.
Remember, becoming a proficient Python programmer is a journey. Start with the basics, practice consistently, and don‘t be afraid to tackle challenging projects. Embrace the Python Zen‘s guiding principles, especially "Simple is better than complex" and "Readability counts".
I hope this guide has provided you with a solid foundation in Python programming. Keep coding, keep learning, and most importantly, have fun!