DEV Community

Avnish
Avnish

Posted on

Python Code Example Handbook – Sample Script Coding Tutorial for Beginners

Detailed Explanation with Step-by-Step Guide

1. Variable Definitions in Python

Variables are containers for storing data. Python automatically determines the type based on the value assigned.

Example:

# Defining variables
name = "Alice"  # String
age = 25        # Integer
height = 5.6    # Float
is_student = True  # Boolean

# Print variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Assign values: Each variable is assigned a value. No explicit type declaration is needed.
  2. Print values: Use print() to display the variables. Text and variables can be combined in the output.

2. Hello, World! Program in Python

The simplest program to start with.

Example:

# Print "Hello, World!" to the console
print("Hello, World!")
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. print() function: Displays text on the screen.
  2. String inside quotes: Ensure the text is inside quotes (single or double).

3. Data Types and Built-in Data Structures in Python

Python supports various data types and built-in structures.

Example:

# Data types
integer = 10  # Integer type
floating_point = 3.14  # Float type
string = "Python"  # String type
boolean = True  # Boolean type

# Data structures
my_list = [1, 2, 3]  # List
my_tuple = (4, 5, 6)  # Tuple
my_set = {7, 8, 9}  # Set
my_dict = {"a": 10, "b": 20}  # Dictionary
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Data Types: Examples of numbers, text, and logical values.
  2. Structures:
    • List: Ordered and changeable.
    • Tuple: Ordered but immutable.
    • Set: Unordered, no duplicates.
    • Dictionary: Key-value pairs.

4. Python Operators

Python supports various types of operators for computations and comparisons.

Example:

# Arithmetic operators
print(5 + 3)  # 8
print(5 - 3)  # 2
print(5 * 3)  # 15
print(5 / 3)  # 1.666...

# Comparison operators
print(5 > 3)   # True
print(5 == 3)  # False

# Logical operators
print(True and False)  # False
print(True or False)   # True
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Arithmetic: Perform calculations like addition (+), subtraction (-), etc.
  2. Comparison: Compare values using operators like >, <, ==.
  3. Logical: Combine conditions using and, or.

5. Conditionals in Python

Control the flow of execution based on conditions.

Example:

x = 10
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. if block: Executes if the condition is true.
  2. elif block: Adds additional conditions.
  3. else block: Executes when none of the conditions are true.

6. For Loops in Python

Iterate over a sequence of values.

Example:

for i in range(5):
    print("Iteration:", i)
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. range(5): Generates numbers from 0 to 4.
  2. for loop: Runs the block for each value in the range.

7. While Loops in Python

Execute a block of code repeatedly while a condition is true.

Example:

count = 0
while count < 5:
    print("Count:", count)
    count += 1
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Condition: The loop continues while count < 5 is true.
  2. Increment: Use count += 1 to avoid an infinite loop.

8. Nested Loops in Python

A loop inside another loop.

Example:

for i in range(3):
    for j in range(2):
        print(f"i={i}, j={j}")
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Outer loop: Controls the rows.
  2. Inner loop: Runs completely for each iteration of the outer loop.

9. Functions in Python

Encapsulate reusable code.

Example:

def greet(name):
    return f"Hello, {name}!"

print(greet("Alice"))
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Define function: Use def and provide a name and parameters.
  2. Call function: Pass arguments to execute.

10. Recursion in Python

A function calling itself.

Example:

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(5))  # Output: 120
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Base case: Stops recursion when n == 1.
  2. Recursive step: Calls the function with a smaller value.

11. Exception Handling in Python

Handle runtime errors gracefully.

Example:

try:
    x = 1 / 0
except ZeroDivisionError as e:
    print("Cannot divide by zero:", e)
finally:
    print("Cleanup done.")
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. try block: Code that might cause an error.
  2. except block: Handles the error.
  3. finally block: Executes regardless of an error.

12. Object-Oriented Programming in Python

Create objects with attributes and methods.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        print(f"Hi, I'm {self.name}.")

p = Person("Alice", 25)
p.greet()
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Class: Use class to define.
  2. Attributes: Defined in __init__().
  3. Methods: Functions inside a class.

13. How to Work with Files in Python

Read and write files.

Example:

# Write to file
with open("example.txt", "w") as file:
    file.write("Hello, File!")

# Read from file
with open("example.txt", "r") as file:
    print(file.read())
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. open() function: Use modes like w (write) and r (read).
  2. with block: Ensures the file is closed after operations.

14. Import Statements in Python

Access external modules.

Example:

import math

print(math.sqrt(16))  # 4.0
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. Import: Use import to load a module.
  2. Use functions: Call functions with module.function().

15. List and Dictionary Comprehension in Python

Create lists and dictionaries efficiently.

Example:

# List comprehension
squares = [x**2 for x in range(5)]
print(squares)

# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict)
Enter fullscreen mode Exit fullscreen mode

Step-by-Step:

  1. List comprehension: [expression for item in iterable].
  2. Dictionary comprehension: {key: value for item in iterable}.

Top comments (0)