Skip to main content

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:

python
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:

  1. print() is a built-in Python function that displays output to the console
  2. The text inside the parentheses is what gets printed
  3. 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

  1. Open your terminal or command prompt
  2. Type python or python3 and press Enter
  3. You'll see the Python prompt >>>
  4. 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

  1. Create a new file named hello.py using any text editor
  2. Add your code: print("Hello, World!")
  3. Save the file
  4. Open terminal/command prompt and navigate to the file's location
  5. Run python hello.py or python3 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:

  1. Open the IDE
  2. Create a new Python file
  3. Write your code
  4. 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:

python
# 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:

  1. Comments: Lines starting with # are comments. Python ignores them, but they help humans understand the code.

  2. Variables: We created variables like name and days_in_year to store data. No need to declare variable types - Python figures it out automatically.

  3. String concatenation: In print("Welcome to Python,", name), Python joins multiple items together with spaces.

  4. Calculations: Python can perform mathematical operations like multiplication (*).

  5. 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:

  1. 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.

  2. Case sensitivity: name, Name, and NAME would be three different variables in Python.

  3. Line endings: Unlike some languages, Python doesn't require semicolons to end statements. Each line is typically one statement.

  4. 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:

python
# 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, and else
  • Multiple print statements
  • String formatting with f-strings

Common Errors in First Programs

When writing your first programs, you might encounter these common errors:

  1. Syntax Error: Missing or mismatched quotes, parentheses, or colons

    python
    print("Hello, World!)  # Missing closing quote
  2. Indentation Error: Inconsistent spaces at the beginning of lines

    python
    if True:
    print("This will error") # Should be indented
  3. Name Error: Using variables before defining them

    python
    print(greeting)  # Error if greeting isn't defined yet
  4. Type Error: Operations between incompatible types

    python
    print("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:

  1. Modify the "Hello, World!" program to display your name instead.
  2. Create a program that asks for the user's favorite color and responds with a message using that color.
  3. Write a program that asks for two numbers and prints their sum, difference, product, and quotient.
  4. Enhance the greeting program to also display the current date along with the greeting.
  5. Create a simple calculator that takes two numbers and an operation (+, -, *, /) from the user and shows the result.

Additional Resources

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! :)