
Writing Your First Python Script
So you want to write your first Python script? Fantastic! Python is an excellent choice for beginners and experts alike, thanks to its readability and versatility. In this guide, I'll walk you through every step of creating, running, and understanding your very first Python program. Let's dive right in!
Getting Set Up
Before you can write your first script, you'll need to have Python installed on your computer. If you haven't done this yet, head over to python.org and download the latest version for your operating system. The installation process is straightforward—just follow the prompts. Once installed, you can verify everything is working by opening your command line (Command Prompt on Windows, Terminal on macOS/Linux) and typing:
python --version
You should see something like "Python 3.x.x" confirming your installation. Now you're ready to start coding!
Don't worry if this feels unfamiliar—every programmer started exactly where you are now. The command line might seem intimidating at first, but you'll get comfortable with it quickly.
Your First Python Program
Let's create the classic "Hello, World!" program. This tradition dates back decades and serves as the simplest introduction to any programming language.
Open any text editor (Notepad, TextEdit, or something more advanced like VS Code) and create a new file called hello.py
. The .py
extension tells your computer this is a Python file.
Type the following line into your file:
print("Hello, World!")
Save the file, then open your command line. Navigate to the directory where you saved hello.py
using the cd
command (change directory). For example:
cd Desktop
Once you're in the right directory, run your script with:
python hello.py
Congratulations! You've just run your first Python program. You should see "Hello, World!" printed to your terminal.
Common First Program Mistakes | Solution |
---|---|
Forgot the .py extension | Name file with .py ending |
Wrong directory in terminal | Use cd command to navigate |
Typo in print function | Check spelling and parentheses |
Understanding What You Just Did
Let's break down that single line of code. The print()
function is one of Python's built-in functions that outputs text to the screen. The text you want to print goes inside the parentheses, surrounded by quotation marks. These can be either single ('
) or double ("
) quotes—Python treats them the same.
What if you want to print multiple things? You can separate them with commas:
print("Hello,", "World!", "How are you?")
Python will automatically add spaces between the items separated by commas. You can also print numbers without quotes:
print("The answer is", 42)
The print function is incredibly versatile and will become one of your most-used tools as you learn Python. Experiment with different inputs to see what happens!
Adding Variables to Your Script
Variables are like labeled containers that store information. Let's modify our hello script to use a variable:
greeting = "Hello, World!"
print(greeting)
When you run this, you'll get the same output, but now you're using a variable called greeting
to store the text before printing it. Variables can store different types of data:
name = "Alice"
age = 30
height = 5.7
print("Name:", name)
print("Age:", age)
print("Height:", height)
Python variable names should be descriptive and can contain letters, numbers, and underscores, but cannot start with a number.
Here are some best practices for naming variables:
- Use descriptive names (like user_age
instead of ua
)
- Separate words with underscores (snake_case)
- Avoid Python keywords like print
or if
- Keep them concise but meaningful
Basic Input and Output
Let's make our script interactive by asking for user input. Python's input()
function lets you prompt the user for information:
name = input("What's your name? ")
print("Hello,", name, "! Nice to meet you!")
When you run this script, it will pause at the input() function and wait for you to type something and press Enter. Whatever you type gets stored in the name
variable, which then gets used in the print statement.
You can combine input with other operations:
birth_year = input("What year were you born? ")
age = 2023 - int(birth_year)
print("You are approximately", age, "years old!")
Notice the int()
function? That converts the text input (which Python treats as a string) into an integer number so we can do math with it.
Common Input Issues | Solutions |
---|---|
Forgetting to convert types | Use int(), float() or str() as needed |
Unclear prompt messages | Write descriptive input questions |
Not handling errors | Learn about try/except later |
Simple Calculations
Python can handle all sorts of mathematical operations. Let's create a simple calculator script:
# Get two numbers from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Perform calculations
sum_result = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
# Display results
print("Sum:", sum_result)
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
The float()
function converts the input to decimal numbers, which allows for more precise calculations than integers. Notice the lines starting with #
—these are comments that Python ignores. Comments are essential for explaining your code to yourself and others.
Python follows standard mathematical order of operations (PEMDAS: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction). You can use parentheses to control the order:
result = (2 + 3) * 4 # Result is 20
another_result = 2 + 3 * 4 # Result is 14
Working with Text Strings
Text manipulation is a common task in programming. Let's explore some basic string operations:
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# Concatenation - joining strings
full_name = first_name + " " + last_name
print("Full name:", full_name)
# String methods
print("Upper case:", full_name.upper())
print("Lower case:", full_name.lower())
print("Title case:", full_name.title())
# String length
name_length = len(full_name)
print("Name contains", name_length, "characters")
Python strings have many built-in methods that make text processing easy. The .upper()
, .lower()
, and .title()
methods return new strings with modified cases without changing the original string.
You can also access individual characters in a string using indexing:
message = "Python"
print("First character:", message[0]) # P
print("Last character:", message[-1]) # n
Making Decisions with Conditionals
Programs become much more powerful when they can make decisions. In Python, we use if
, elif
, and else
statements for this:
age = int(input("How old are you? "))
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
The code after each condition only runs if that condition is True. You can have as many elif
(short for "else if") statements as you need, and the else
catches everything that didn't match previous conditions.
Here's another example with multiple conditions:
temperature = float(input("What's the temperature? "))
is_raining = input("Is it raining? (yes/no) ").lower() == "yes"
if temperature > 30 and not is_raining:
print("Perfect beach weather!")
elif temperature > 30 and is_raining:
print("Stay inside, it's hot and raining!")
elif temperature < 0:
print("Brrr, it's freezing!")
else:
print("Average day weather-wise.")
Conditional logic is fundamental to programming—it's how programs respond differently to different situations.
Repeating Actions with Loops
Loops let you repeat code without writing it multiple times. The for
loop is great for iterating a specific number of times:
# Count from 1 to 5
for number in range(1, 6):
print(number)
# Print a message multiple times
for i in range(3):
print("Hello again!")
The range()
function generates a sequence of numbers. range(1, 6)
gives you numbers 1 through 5 (the end number is exclusive).
You can also loop through strings and lists:
word = "Python"
for letter in word:
print(letter)
names = ["Alice", "Bob", "Charlie"]
for name in names:
print("Hello,", name)
Sometimes you don't know how many times you need to loop in advance. For those situations, use a while
loop:
counter = 0
while counter < 5:
print("Counter is at:", counter)
counter = counter + 1 # Important: don't forget to update the condition!
Be careful with while loops—if you forget to update the condition, you'll create an infinite loop that never stops!
Loop Type | Best For | Example |
---|---|---|
for | Known number of iterations | Processing items in a list |
while | Unknown iterations until condition met | User input validation |
nested loops | Multi-dimensional data | Grids, matrices |
Creating Your Own Functions
Functions let you package code into reusable blocks. Let's create a simple function:
def greet_user(name):
"""Display a simple greeting.""" # This is a docstring - it documents your function
print("Hello,", name, "! Welcome!")
# Call the function
greet_user("Alice")
greet_user("Bob")
Functions can take parameters (like name
above) and return values:
def square(number):
"""Return the square of a number."""
return number * number
result = square(5)
print("5 squared is", result)
Functions make your code organized and reusable. Instead of writing the same code multiple places, you write it once in a function and call that function wherever you need it.
Here's a more practical example:
def calculate_tip(bill_amount, tip_percentage):
"""Calculate tip amount and total bill."""
tip_amount = bill_amount * (tip_percentage / 100)
total_bill = bill_amount + tip_amount
return tip_amount, total_bill
tip, total = calculate_tip(50, 15)
print("Tip: $", tip)
print("Total: $", total)
Putting It All Together
Let's create a more complete script that uses several concepts we've covered:
def main():
"""Main function that runs our program."""
print("=== Simple Python Calculator ===")
while True:
# Get operation choice
print("\nOperations: +, -, *, /, or 'quit' to exit")
operation = input("Choose operation: ")
if operation.lower() == 'quit':
print("Goodbye!")
break
if operation not in ['+', '-', '*', '/']:
print("Invalid operation. Please try again.")
continue
# Get numbers
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
except ValueError:
print("Please enter valid numbers.")
continue
# Perform calculation
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 == 0:
print("Error: Cannot divide by zero!")
continue
result = num1 / num2
print("Result:", result)
# Run the program
if __name__ == "__main__":
main()
This script demonstrates several important concepts: functions, loops, conditionals, error handling with try/except, and user input. The if __name__ == "__main__":
line is a common Python pattern that means "run this code only if this file is executed directly, not imported as a module."
Next Steps
You've written your first Python script and learned fundamental programming concepts. The best way to improve is through practice. Try modifying the examples, break them to see what errors occur, then fix them.
Consider these ideas for your next projects: - A number guessing game - A simple text-based adventure - A personal budget calculator - A temperature converter - A password generator
Remember that programming is a skill developed over time. Don't get discouraged by errors—they're learning opportunities. Every programmer, regardless of experience, encounters bugs and spends time debugging.
Python has an incredibly supportive community and extensive documentation. When you get stuck, search for solutions online—chances are someone has faced the same issue and shared their solution.
Most importantly, have fun with it! Programming is creative problem-solving, and Python is a wonderful language for bringing your ideas to life. Happy coding!