Python Syntax Basics - WittyWriter

Python Syntax Basics

📘 Key Concepts and Definitions

🧮 Code Block Structure

Python's structure is defined by colons : and indentation. A block of code starts after a colon and is indented.

Function Structure

def function_name(parameter1, parameter2):
    # This block is indented
    result = parameter1 + parameter2
    return result

Conditional Structure

if condition1:
    # Do something if condition1 is true
elif condition2:
    # Do something if condition2 is true
else:
    # Do something if no conditions are true

🛠️ Core Syntax Reference

Variables and Data Types

# No type declaration needed
name = "Alice"      # str
age = 30            # int
height = 5.5        # float
is_student = True   # bool

Common Data Structures

# List (ordered, mutable)
my_list = [1, "apple", 3.14]

# Tuple (ordered, immutable)
my_tuple = (1, "apple", 3.14)

# Dictionary (unordered, key-value pairs)
my_dict = {"name": "Bob", "age": 25}

# Set (unordered, unique elements)
my_set = {1, 2, 3, 3, 4} # Becomes {1, 2, 3, 4}

Operators

Control Flow

# For loop
for item in my_list:
    print(item)

# While loop
count = 0
while count < 5:
    print(count)
    count += 1

String Formatting (f-strings)

name = "Charlie"
age = 40
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Charlie and I am 40 years old.

🧭 Basic Scripting Workflow

  1. Import necessary modules at the top of your file (e.g., import os).
  2. Define functions to encapsulate reusable logic.
  3. Initialize variables to hold state or data.
  4. Write the main logic of your script. This might involve loops, conditionals, and function calls.
  5. Use a main block to make your script reusable as a module:
    if __name__ == "__main__":
        # Your main script execution code goes here
        pass
    

⌨️ Productivity Tips

📊 Data Type Overview

TypeCategorySyntax ExampleMutable?
int, floatNumericx = 10, y = 3.14No
strSequences = "Hello"No
boolBooleanis_true = TrueNo
listSequencemy_list = [1, 2, 3]Yes
tupleSequencemy_tuple = (1, 2, 3)No
dictMappingmy_dict = {'key': 'value'}Yes
setSetmy_set = {1, 2, 3}Yes

🧪 Example: Word Count Script

A simple script to count the frequency of words in a given text.

def count_words(text):
    """Counts the frequency of each word in a string."""
    word_counts = {}
    words = text.lower().split() # Lowercase and split into words

    for word in words:
        # Remove punctuation for better counting
        cleaned_word = word.strip(".,!?")
        if cleaned_word:
            word_counts[cleaned_word] = word_counts.get(cleaned_word, 0) + 1
    
    return word_counts

if __name__ == "__main__":
    sample_text = "Hello world! This is a test. Hello again."
    counts = count_words(sample_text)
    print("Word frequencies:")
    for word, count in counts.items():
        print(f"- {word}: {count}")

🧹 Troubleshooting Common Errors

📚 References and Further Reading

🍪 We use cookies to improve your experience. Learn more