Writing Your First Python Script: Complete Beginner's Guide

Learn to write, execute, and debug your first Python script with this comprehensive guide covering setup, syntax, and best practices for beginners.

Writing Your First Python Script

Introduction

Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. Writing your first Python script is an essential step in learning programming and automation. This comprehensive guide will walk you through everything you need to know about creating, writing, and executing your first Python script.

Python scripts are text files containing Python code that can be executed by the Python interpreter. These scripts can automate tasks, process data, create applications, and solve complex problems with relatively simple syntax compared to other programming languages.

Prerequisites and Setup

Installing Python

Before writing your first script, you need to have Python installed on your system.

| Operating System | Installation Method | Command/Process | |-----------------|-------------------|-----------------| | Windows | Official installer | Download from python.org and run installer | | macOS | Homebrew | brew install python3 | | macOS | Official installer | Download from python.org | | Linux (Ubuntu/Debian) | Package manager | sudo apt-get install python3 | | Linux (CentOS/RHEL) | Package manager | sudo yum install python3 |

Verifying Installation

After installation, verify Python is properly installed by checking the version:

`bash python --version

or

python3 --version `

Setting Up Development Environment

| Editor/IDE | Description | Best For | |-----------|-------------|----------| | IDLE | Built-in Python IDE | Beginners | | Visual Studio Code | Lightweight editor with extensions | General development | | PyCharm | Full-featured Python IDE | Professional development | | Sublime Text | Fast text editor | Quick scripting | | Vim/Nano | Terminal-based editors | Server environments |

Basic Python Script Structure

The Shebang Line

The shebang line tells the system which interpreter to use when executing the script directly:

`python #!/usr/bin/env python3 `

This line should be the first line in your script if you plan to make it executable on Unix-like systems.

Comments and Documentation

Comments are crucial for code readability and maintenance:

`python

This is a single-line comment

""" This is a multi-line comment or docstring that can span multiple lines """

def my_function(): """ This is a function docstring explaining what the function does """ pass `

Basic Script Template

`python #!/usr/bin/env python3 """ Script Name: my_first_script.py Description: A basic Python script template Author: Your Name Date: Current Date """

Import statements

import sys import os

Global variables

SCRIPT_VERSION = "1.0"

Main function

def main(): """Main function that contains the primary logic""" print("Hello, World!")

Script execution

if __name__ == "__main__": main() `

Creating Your First Script

Step 1: Create the Script File

Create a new file with a .py extension:

`bash touch hello_world.py

or

nano hello_world.py

or

vim hello_world.py `

Step 2: Write the Basic Script

`python #!/usr/bin/env python3 """ My First Python Script This script demonstrates basic Python concepts """

Print a welcome message

print("Welcome to Python Programming!")

Variables and data types

name = "Python Programmer" age = 25 height = 5.9 is_learning = True

Display variable information

print(f"Name: {name}") print(f"Age: {age}") print(f"Height: {height} feet") print(f"Currently learning: {is_learning}")

Basic arithmetic operations

num1 = 10 num2 = 5

addition = num1 + num2 subtraction = num1 - num2 multiplication = num1 * num2 division = num1 / num2

print(f"\nBasic Math Operations:") print(f"{num1} + {num2} = {addition}") print(f"{num1} - {num2} = {subtraction}") print(f"{num1} * {num2} = {multiplication}") print(f"{num1} / {num2} = {division}") `

Step 3: Make the Script Executable (Unix/Linux/macOS)

`bash chmod +x hello_world.py `

Running Python Scripts

Method 1: Using Python Interpreter

`bash python hello_world.py

or

python3 hello_world.py `

Method 2: Direct Execution (Unix-like systems)

`bash ./hello_world.py `

Method 3: Using Python Module Execution

`bash python -m hello_world `

Essential Python Concepts for Scripts

Variables and Data Types

| Data Type | Description | Example | |-----------|-------------|---------| | int | Integer numbers | age = 25 | | float | Decimal numbers | price = 19.99 | | str | Text strings | name = "John" | | bool | Boolean values | is_active = True | | list | Ordered collections | numbers = [1, 2, 3] | | dict | Key-value pairs | person = {"name": "John"} |

`python

Variable examples

student_name = "Alice" # String student_age = 20 # Integer student_gpa = 3.75 # Float is_enrolled = True # Boolean courses = ["Math", "Science"] # List student_info = { # Dictionary "name": "Alice", "age": 20, "gpa": 3.75 } `

Input and Output Operations

`python

Getting user input

user_name = input("Enter your name: ") user_age = int(input("Enter your age: "))

Displaying output

print("Hello,", user_name) print(f"You are {user_age} years old")

Formatted output

print("Name: {}, Age: {}".format(user_name, user_age)) print("Name: %s, Age: %d" % (user_name, user_age)) `

Control Flow Statements

#### Conditional Statements

`python

If-elif-else structure

score = int(input("Enter your score: "))

if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" elif score >= 60: grade = "D" else: grade = "F"

print(f"Your grade is: {grade}") `

#### Loops

`python

For loop

fruits = ["apple", "banana", "orange"] for fruit in fruits: print(f"I like {fruit}")

While loop

count = 0 while count < 5: print(f"Count: {count}") count += 1

Range function

for i in range(1, 11): print(f"Number: {i}") `

Functions

`python def greet_user(name, greeting="Hello"): """ Function to greet a user Args: name (str): User's name greeting (str): Greeting message (default: "Hello") Returns: str: Formatted greeting message """ return f"{greeting}, {name}!"

def calculate_area(length, width): """Calculate rectangle area""" return length * width

Function calls

message = greet_user("John") print(message)

area = calculate_area(10, 5) print(f"Area: {area}") `

Advanced Script Features

Command Line Arguments

`python import sys

def main(): # Check if arguments are provided if len(sys.argv) < 2: print("Usage: python script.py ") sys.exit(1) # Access command line arguments script_name = sys.argv[0] first_arg = sys.argv[1] print(f"Script: {script_name}") print(f"First argument: {first_arg}") # Process all arguments for i, arg in enumerate(sys.argv[1:], 1): print(f"Argument {i}: {arg}")

if __name__ == "__main__": main() `

Using argparse for Better Argument Handling

`python import argparse

def main(): # Create argument parser parser = argparse.ArgumentParser(description='My Python Script') # Add arguments parser.add_argument('--name', '-n', required=True, help='Your name') parser.add_argument('--age', '-a', type=int, default=25, help='Your age (default: 25)') parser.add_argument('--verbose', '-v', action='store_true', help='Enable verbose output') # Parse arguments args = parser.parse_args() # Use arguments if args.verbose: print("Verbose mode enabled") print(f"Hello, {args.name}!") print(f"You are {args.age} years old")

if __name__ == "__main__": main() `

File Operations

`python def read_file(filename): """Read content from a file""" try: with open(filename, 'r') as file: content = file.read() return content except FileNotFoundError: print(f"File {filename} not found") return None except IOError: print(f"Error reading file {filename}") return None

def write_file(filename, content): """Write content to a file""" try: with open(filename, 'w') as file: file.write(content) print(f"Content written to {filename}") except IOError: print(f"Error writing to file {filename}")

Example usage

data = "This is sample data\nLine 2\nLine 3" write_file("sample.txt", data)

file_content = read_file("sample.txt") if file_content: print("File content:") print(file_content) `

Error Handling

`python def safe_divide(a, b): """Safely divide two numbers with error handling""" try: result = a / b return result except ZeroDivisionError: print("Error: Cannot divide by zero") return None except TypeError: print("Error: Invalid input types") return None except Exception as e: print(f"Unexpected error: {e}") return None

def main(): # Test error handling print(safe_divide(10, 2)) # Normal division print(safe_divide(10, 0)) # Division by zero print(safe_divide(10, "a")) # Type error `

Complete Example Script

Here's a comprehensive example that demonstrates multiple concepts:

`python #!/usr/bin/env python3 """ Student Grade Calculator A script that calculates student grades and generates reports

Author: Python Learner Version: 1.0 """

import sys import json from datetime import datetime

class StudentGradeCalculator: """Class to handle student grade calculations""" def __init__(self): self.students = {} self.grade_scale = { 'A': (90, 100), 'B': (80, 89), 'C': (70, 79), 'D': (60, 69), 'F': (0, 59) } def add_student(self, name, scores): """Add a student with their scores""" if not isinstance(scores, list) or not scores: raise ValueError("Scores must be a non-empty list") average = sum(scores) / len(scores) grade = self.calculate_grade(average) self.students[name] = { 'scores': scores, 'average': round(average, 2), 'grade': grade } def calculate_grade(self, average): """Calculate letter grade from average""" for grade, (min_score, max_score) in self.grade_scale.items(): if min_score <= average <= max_score: return grade return 'F' def generate_report(self): """Generate a grade report""" if not self.students: return "No students added yet." report = [] report.append("=" * 50) report.append("STUDENT GRADE REPORT") report.append("=" * 50) report.append(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") report.append("") for name, data in self.students.items(): report.append(f"Student: {name}") report.append(f"Scores: {data['scores']}") report.append(f"Average: {data['average']}") report.append(f"Grade: {data['grade']}") report.append("-" * 30) # Calculate class statistics all_averages = [data['average'] for data in self.students.values()] class_average = sum(all_averages) / len(all_averages) report.append("CLASS STATISTICS") report.append(f"Class Average: {round(class_average, 2)}") report.append(f"Highest Average: {max(all_averages)}") report.append(f"Lowest Average: {min(all_averages)}") report.append(f"Total Students: {len(self.students)}") return "\n".join(report) def save_to_file(self, filename): """Save student data to JSON file""" try: with open(filename, 'w') as file: json.dump(self.students, file, indent=2) print(f"Data saved to {filename}") except IOError as e: print(f"Error saving file: {e}") def load_from_file(self, filename): """Load student data from JSON file""" try: with open(filename, 'r') as file: self.students = json.load(file) print(f"Data loaded from {filename}") except FileNotFoundError: print(f"File {filename} not found") except json.JSONDecodeError: print(f"Invalid JSON in file {filename}") except IOError as e: print(f"Error reading file: {e}")

def get_student_input(): """Get student information from user input""" name = input("Enter student name: ").strip() if not name: raise ValueError("Name cannot be empty") scores = [] print("Enter scores (press Enter with empty input to finish):") while True: score_input = input("Score: ").strip() if not score_input: break try: score = float(score_input) if 0 <= score <= 100: scores.append(score) else: print("Score must be between 0 and 100") except ValueError: print("Please enter a valid number") if not scores: raise ValueError("At least one score is required") return name, scores

def main(): """Main function""" calculator = StudentGradeCalculator() print("Welcome to Student Grade Calculator!") print("Commands: add, report, save, load, quit") while True: try: command = input("\nEnter command: ").strip().lower() if command == 'quit': print("Goodbye!") break elif command == 'add': try: name, scores = get_student_input() calculator.add_student(name, scores) print(f"Student {name} added successfully!") except ValueError as e: print(f"Error: {e}") elif command == 'report': report = calculator.generate_report() print(report) elif command == 'save': filename = input("Enter filename: ").strip() if filename: calculator.save_to_file(filename) else: print("Filename cannot be empty") elif command == 'load': filename = input("Enter filename: ").strip() if filename: calculator.load_from_file(filename) else: print("Filename cannot be empty") else: print("Unknown command. Available: add, report, save, load, quit") except KeyboardInterrupt: print("\nOperation cancelled by user") except Exception as e: print(f"Unexpected error: {e}")

if __name__ == "__main__": main() `

Script Execution and Testing

Running the Script

`bash

Make executable

chmod +x grade_calculator.py

Run the script

python3 grade_calculator.py

or

./grade_calculator.py `

Testing Your Scripts

Create a simple test script:

`python #!/usr/bin/env python3 """ Test script for grade calculator """

from grade_calculator import StudentGradeCalculator

def test_grade_calculator(): """Test the StudentGradeCalculator class""" calculator = StudentGradeCalculator() # Test adding students calculator.add_student("John Doe", [85, 92, 78, 90]) calculator.add_student("Jane Smith", [95, 87, 93, 91]) # Test report generation report = calculator.generate_report() print(report) # Test file operations calculator.save_to_file("test_grades.json") # Create new calculator and load data new_calculator = StudentGradeCalculator() new_calculator.load_from_file("test_grades.json") print("Test completed successfully!")

if __name__ == "__main__": test_grade_calculator() `

Common Commands and Operations

| Operation | Command | Description | |-----------|---------|-------------| | Run script | python script.py | Execute Python script | | Check syntax | python -m py_compile script.py | Compile and check syntax | | Interactive mode | python -i script.py | Run script then enter interactive mode | | Help | python -h | Display Python help | | Version | python --version | Show Python version | | Module execution | python -m module_name | Run module as script | | Debugging | python -m pdb script.py | Run script with debugger |

Best Practices and Notes

Code Organization

1. Use meaningful variable and function names 2. Follow PEP 8 style guidelines 3. Add docstrings to functions and classes 4. Use comments to explain complex logic 5. Organize imports at the top of the file

Error Handling

1. Always handle potential exceptions 2. Use specific exception types when possible 3. Provide meaningful error messages 4. Log errors for debugging purposes

Performance Considerations

1. Use list comprehensions when appropriate 2. Avoid global variables when possible 3. Use generators for large datasets 4. Profile your code to identify bottlenecks

Security Notes

1. Validate all user inputs 2. Be careful with file operations 3. Avoid using eval() with user input 4. Use secure methods for handling sensitive data

This comprehensive guide provides you with the foundation to write, execute, and maintain Python scripts effectively. Start with simple scripts and gradually incorporate more advanced features as you become comfortable with the basics.

Tags

  • Automation
  • Programming Basics
  • beginner programming
  • python-scripting
  • python-tutorial

Related Articles

Related Books - Expand Your Knowledge

Explore these Python books to deepen your understanding:

Browse all IT books

Popular Technical Articles & Tutorials

Explore our comprehensive collection of technical articles, programming tutorials, and IT guides written by industry experts:

Browse all 8+ technical articles | Read our IT blog

Writing Your First Python Script: Complete Beginner&#x27;s Guide