Python First Program
Welcome to the exciting world of Python programming! In this lesson, you'll write your very first Python program. This is a significant milestone in your programming journey, and we'll make sure it's both enjoyable and educational.
Introduction
Writing your first program in any language is a rite of passage. In programming, there's a tradition of creating a simple program that displays "Hello, World!" as your first project. This tradition dates back to the 1970s and serves as a simple way to verify that your programming environment is set up correctly.
In this lesson, you'll learn:
- How to write a simple Python program
- How to run Python code
- Understanding basic Python syntax
- Different ways to execute Python code
Your First Python Program: Hello World
Let's start with the simplest Python program possible:
print("Hello, World!")
When you run this program, it will output:
Hello, World!
That's it! You've written your first Python program. Let's break down what happened:
print()
is a built-in Python function that displays output to the console- The text inside the parentheses is what gets printed
- The quotation marks (either single
'
or double"
) indicate that "Hello, World!" is a string (text data)
Running Your Python Program
There are several ways to run Python code:
Method 1: Interactive Python Shell
- Open your terminal or command prompt
- Type
python
orpython3
and press Enter - You'll see the Python prompt
>>>
- Type your code and press Enter
$ python3
Python 3.9.5 (default, May 11 2021, 08:20:37)
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, World!")
Hello, World!
>>>
This interactive mode is great for testing small pieces of code.
Method 2: Running a Python File
- Create a new file named
hello.py
using any text editor - Add your code:
print("Hello, World!")
- Save the file
- Open terminal/command prompt and navigate to the file's location
- Run
python hello.py
orpython3 hello.py
$ python3 hello.py
Hello, World!
This method is preferred for longer programs.
Method 3: Using an IDE
If you're using an integrated development environment (IDE) like PyCharm, VS Code, or Jupyter Notebook:
- Open the IDE
- Create a new Python file
- Write your code
- Run the program using the IDE's run button or keyboard shortcut
Let's Expand Our First Program
Now that you know the basics, let's create a slightly more complex program:
# This is a comment - Python ignores text after the # symbol
print("Hello, Python Programmer!")
# Variables store data
name = "Learner"
print("Welcome to Python,", name)
# Simple calculation
days_in_year = 365
hours_in_day = 24
hours_in_year = days_in_year * hours_in_day
print(f"There are {hours_in_year} hours in a year.")
Output:
Hello, Python Programmer!
Welcome to Python, Learner
There are 8760 hours in a year.
Let's break down the new concepts:
-
Comments: Lines starting with
#
are comments. Python ignores them, but they help humans understand the code. -
Variables: We created variables like
name
anddays_in_year
to store data. No need to declare variable types - Python figures it out automatically. -
String concatenation: In
print("Welcome to Python,", name)
, Python joins multiple items together with spaces. -
Calculations: Python can perform mathematical operations like multiplication (
*
). -
F-strings: The
f"There are {hours_in_year} hours in a year."
is called an f-string. It's a convenient way to insert variable values into a string.
Understanding Python Syntax Rules
Python has some important syntax rules to remember:
-
Indentation matters: Python uses indentation (spaces at the beginning of lines) to define code blocks. We'll explore this more when we learn about conditional statements and loops.
-
Case sensitivity:
name
,Name
, andNAME
would be three different variables in Python. -
Line endings: Unlike some languages, Python doesn't require semicolons to end statements. Each line is typically one statement.
-
Continuation lines: Long statements can span multiple lines using the
\
character or by ensuring expressions are within parentheses, brackets, or braces.
Real-World Example: Personal Greeting Program
Let's create a slightly more useful program that takes user input and provides a personalized greeting:
# Get the current time
import datetime
current_time = datetime.datetime.now()
hour = current_time.hour
# Get user's name
name = input("What is your name? ")
# Create personalized greeting based on time of day
if hour < 12:
greeting = "Good morning"
elif hour < 18:
greeting = "Good afternoon"
else:
greeting = "Good evening"
# Display the greeting
print(f"{greeting}, {name}! Welcome to Python programming.")
# Add some encouragement
print("You've just run your first interactive Python program!")
print("Keep going - you're doing great!")
Example output (at 3 PM, with input "Alex"):
What is your name? Alex
Good afternoon, Alex! Welcome to Python programming.
You've just run your first interactive Python program!
Keep going - you're doing great!
This example demonstrates:
- Importing modules (datetime)
- Getting user input with
input()
- Conditional logic with
if
,elif
, andelse
- Multiple print statements
- String formatting with f-strings
Common Errors in First Programs
When writing your first programs, you might encounter these common errors:
-
Syntax Error: Missing or mismatched quotes, parentheses, or colons
pythonprint("Hello, World!) # Missing closing quote
-
Indentation Error: Inconsistent spaces at the beginning of lines
pythonif True:
print("This will error") # Should be indented -
Name Error: Using variables before defining them
pythonprint(greeting) # Error if greeting isn't defined yet
-
Type Error: Operations between incompatible types
pythonprint("2" + 2) # Can't add string and integer
Remember: Python's error messages are quite helpful. Read them carefully to understand what went wrong.
Summary
Congratulations! You've written your first Python program and learned about:
- The traditional "Hello, World!" program
- Different ways to run Python code
- Basic Python syntax and structure
- Variables, comments, and string formatting
- Taking user input and providing output
- A simple real-world example program
This is just the beginning of your Python journey. As you continue learning, you'll discover how Python's simplicity and readability make it an excellent language for beginners and professionals alike.
Exercises
To reinforce your learning, try these exercises:
- Modify the "Hello, World!" program to display your name instead.
- Create a program that asks for the user's favorite color and responds with a message using that color.
- Write a program that asks for two numbers and prints their sum, difference, product, and quotient.
- Enhance the greeting program to also display the current date along with the greeting.
- Create a simple calculator that takes two numbers and an operation (+, -, *, /) from the user and shows the result.
Additional Resources
- Official Python Documentation
- Python's PEP 8 Style Guide - Best practices for writing Python code
- Automate the Boring Stuff with Python - A practical introduction to Python
- Python Interactive Shell Tips - Getting more from the Python shell
Now that you've written your first program, you're officially a Python programmer! Continue to the next lesson to dive deeper into Python's data types and variables.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)