Introduction to Python
Your First Python Program
Writing and running your first Python script
Interview: Foundation for all Python development
Writing your first Python program introduces you to the fundamental workflow: write code in a .py file, then execute it with the Python interpreter. This topic covers script creation, execution, command-line arguments, and the script vs. module pattern.
Creating and Running a Script
Python scripts are plain text files with the .py extension. You can create them with any text editor or IDE.
- Create a file named
hello.pyand write your code. - Run it from the terminal:
python3 hello.py. - On Unix systems, add a shebang line (
#!/usr/bin/env python3) at the top and make it executable withchmod +x hello.py.
The print() Function
print() is the most basic output function. It converts arguments to strings and writes them to stdout.
print("Hello")— print a stringprint("A", "B", "C")— print multiple values separated by spacesprint("A", "B", sep="-")— custom separatorprint("Hello", end="!")— custom line ending instead of newlineprint(f"Name: {name}")— f-string formatting
Command-Line Arguments
Scripts can accept arguments from the command line using the sys.argv list or the more powerful argparse module.
The if __name__ == '__main__' Pattern
This is one of Python's most important patterns. When a Python file is run directly, __name__ is set to '__main__'. When imported as a module, it's set to the module name. This allows a file to serve as both a script and a reusable module.
Interview Tip
Understanding if __name__ == '__main__' is frequently tested. It demonstrates you understand Python's module system and how code execution works.
Common Pitfalls
- Forgetting the file extension: Python files must end with
.pyto be recognized by the interpreter. - Running from wrong directory: Make sure you're in the same directory as your script, or provide the full path.
- Not using if __name__ == '__main__': Code that runs on import can cause unexpected side effects when the module is imported elsewhere.
Use Cases
Scripting and automation tasks
Command-line utilities and tools
Quick prototyping and testing ideas
Learning Python fundamentals interactively
Common Mistakes
Not using if __name__ == "__main__" guard for reusable code
Forgetting to handle command-line arguments gracefully
Hardcoding values instead of using variables and functions
Not adding a shebang line for Unix-executable scripts