Python Tutorial



Complete Python Tutorial for Beginners: Start Coding Today

Python Tutorial - Learn Python programming for beginners. Explore basic syntax, data types, control structures, functions, file handling

Python Tutorial Overview

This Python tutorial is designed to introduce you to the basics of Python programming. Whether you're a beginner or looking to refresh your skills, this guide covers essential topics to get you started.

1. Getting Started with Python

  • Installation: Download and install Python from python.org.
  • Running Python: Use the command line (or terminal) to run Python scripts. You can also use an IDE like PyCharm or a text editor like Visual Studio Code.

2. Basic Syntax

  • Hello, World!

    print("Hello, World!")
  • Comments: Use # for single-line comments and ''' or """ for multi-line comments.

    # This is a comment

3. Variables and Data Types

  • Variables: Assign values to variables using the = operator.

    name = "Alice"
    age = 30
  • Data Types: Common types include:

    • Strings: str
    • Integers: int
    • Floats: float
    • Booleans: bool

4. Basic Operators

  • Arithmetic Operators: +, -, *, /, // (floor division), % (modulus), ** (exponentiation).

    sum = 5 + 3  # 8
  • Comparison Operators: ==, !=, >, <, >=, <=.

5. Control Structures

  • If Statements:

    if age >= 18:
        print("Adult")
    else:
        print("Minor")
  • Loops:

    • For Loop:
      for i in range(5):
          print(i)  # Outputs 0 to 4
    • While Loop:
      count = 0
      while count < 5:
          print(count)
          count += 1
      

6. Functions

  • Defining Functions:
    def greet(name):
        return f"Hello, {name}!"
    
    print(greet("Alice"))  # Output: Hello, Alice

7. Data Structures

  • Lists: Ordered and mutable collections.

    fruits = ["apple", "banana", "cherry"]
  • Tuples: Ordered and immutable collections.

    print("Hello, World!")
  • Dictionaries: Key-value pairs.

    person = {"name": "Alice", "age": 30}
  • Sets: Unordered collections of unique items.

    unique_numbers = {1, 2, 3}

8. File Handling

  • Reading from a File:

    with open('file.txt', 'r') as file:
        content = file.read()
  • Writing to a File:

    with open('file.txt', 'w') as file:
        file.write("Hello, World!")
     

9. Error Handling

  • Try and Except:
    try:
        result = 10 / 0
    except ZeroDivisionError:
        print("Cannot divide by zero!")

10. Modules and Packages

  • Importing Modules:

    import math
    print(math.sqrt(16))  # Output: 4.0
     
    Creating Your Own Module: Create a Python file (e.g., mymodule.py) and define functions. You can import it into another script.