foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Write and run your first Python program
  • Understand the print() function and its various uses
  • Learn to use comments in Python code
  • Work with both interactive shell and script files

Writing Your First Python Program

Time to write some actual code. Every programmer starts with a "Hello, World!" program - a tradition dating back to the 1970s. It's simple enough that you won't get lost, but it teaches you the fundamental process of writing and running code.

Let's get started.


Two Ways to Run Python

Before we dive in, know that there are two ways to run Python code:


                    Two Ways to Run Python                        

                                                                  
  1. INTERACTIVE MODE (Python Shell)                             
     • Type code, get immediate results                          
     • Great for testing and learning                            
     • Code is not saved                                          
                                                                  
  2. SCRIPT MODE (.py files)                                     
     • Write code in a file                                       
     • Run the entire file                                        
     • Code is saved and reusable                                 
                                                                  

Method 1: Interactive Mode (Python Shell)

The interactive shell is like a conversation with Python - you type something, Python responds immediately.

Opening the Interactive Shell

Open your terminal/command prompt and type:

python
# or on some systems
python3

You'll see something like this:

Python 3.12.0 (main, Oct 2 2023, 00:00:00)
Type "help", "copyright", "credits" or "license" for more information.
>>>

The >>> is Python's prompt, saying "I'm ready for your input."

Your First Command

Type this and press Enter:

>>> print("Hello, World!")
Hello, World!

You just ran your first Python code.

Playing in the Shell

Try a few more things:

>>> print("My name is Python!")
My name is Python!

>>> print("I can do math:", 2 + 2)
I can do math: 4

>>> print("Python " + "is " + "awesome!")
Python is awesome!

>>> 10 * 5
50

>>> exit()  # To leave the shell

The interactive shell is perfect for quick experiments and testing ideas.


Method 2: Script Mode (Creating a .py File)

For real programs, you write code in files. This saves your work and lets you run complex programs.

Step-by-Step: Creating Your First Script

Step 1: Open Your Code Editor

Open VS Code, PyCharm, or any text editor.

Step 2: Create a New File

Create a new file and save it as hello.py

Python files must end with .py - that's how your computer knows it's Python code.

Step 3: Write Your Code

# My first Python program
# This program prints a greeting to the screen

print("Hello, World!")
print("Welcome to Python programming!")
print("This is my first script!")

Step 4: Save the File

Press Ctrl+S (Windows/Linux) or Cmd+S (Mac)

Step 5: Run Your Script

Open terminal in your code editor (or navigate to the file location) and run:

python hello.py

Output:

Hello, World!
Welcome to Python programming!
This is my first script!

Understanding the print() Function

The print() function is your main tool for displaying output. Let's explore what it can do.

Basic Printing

# Printing text (strings)
print("Hello!")           # Double quotes
print('Hello!')           # Single quotes - both work!

# Printing numbers
print(42)                 # Integer
print(3.14)               # Decimal (float)

# Printing calculations
print(10 + 5)             # Outputs: 15
print(100 / 4)            # Outputs: 25.0

Printing Multiple Items

# Separate items with commas
print("My age is", 25)
# Output: My age is 25

print("Python", "is", "fun!")
# Output: Python is fun!

# By default, print() adds a space between items

Special Characters

Character Meaning Example
\n New line print("Hello\nWorld")
\t Tab print("Name:\tJohn")
\\ Backslash print("C:\\Users")
\' Single quote print('It\'s great!')
\" Double quote print("He said \"Hi\"")
# New line example
print("Line 1\nLine 2\nLine 3")
# Output:
# Line 1
# Line 2
# Line 3

# Tab example
print("Name:\tAlice")
print("Age:\t25")
# Output:
# Name:   Alice
# Age:    25

Customizing print()

# Change the separator
print("A", "B", "C", sep="-")
# Output: A-B-C

print("apple", "banana", "cherry", sep=" | ")
# Output: apple | banana | cherry

# Change the ending (default is newline)
print("Hello", end=" ")
print("World!")
# Output: Hello World!

# Print on the same line
print("Loading", end="")
print(".", end="")
print(".", end="")
print(".")
# Output: Loading...

Comments: Talking to Yourself (and Others)

Comments are notes in your code that Python ignores. They're for humans, not computers.

Why Use Comments?


                 Why Comments Matter                      

                                                          
  • Explain what your code does                          
  • Help others understand your thinking                 
  • Help future-you remember why you did something       
  • Temporarily disable code for testing                 
                                                          

Single-Line Comments

Use # for single-line comments:

# This is a comment - Python ignores this line
print("Hello!")  # This is an inline comment

# Calculate the total price
price = 100
tax = 0.20
# total = price * (1 + tax)  # This line is disabled

Multi-Line Comments

Use triple quotes for longer comments:

"""
This is a multi-line comment.
It can span several lines.
Great for explaining complex code
or providing documentation.
"""

'''
You can also use single quotes
for multi-line comments.
Both work the same way!
'''

print("The program continues here")

Comment Best Practices

# GOOD: Explains WHY
# Calculate tax at 20% as required by new regulations
tax = price * 0.20

# BAD: Explains WHAT (obvious from the code)
# Multiply price by 0.20
tax = price * 0.20

# GOOD: Meaningful explanation
# Convert temperature from Celsius to Fahrenheit
fahrenheit = (celsius * 9/5) + 32

# BAD: Obvious and unnecessary
# Print hello
print("Hello")

Let's Create Something Fun

Now let's put it all together with a more creative program:

# ==========================================
# My First Python Art Project
# Created by: [Your Name]
# Date: [Today's Date]
# ==========================================

# Print a fun ASCII art banner
print("=" * 40)
print("      Welcome to Python!      ")
print("=" * 40)

# Print some information
print("\nFun Facts about Python:")
print("-" * 30)
print("• Named after Monty Python")
print("• Created in 1991")
print("• Used by millions worldwide")

# A little math trick
print("\nLet's do some math:")
print("10 + 20 =", 10 + 20)
print("50 - 15 =", 50 - 15)
print("7 * 8 =", 7 * 8)

# End with a message
print("\n" + "=" * 40)
print("  Thanks for running my program!  ")
print("=" * 40)

Output:

========================================
      Welcome to Python!      
========================================

Fun Facts about Python:
------------------------------
• Named after Monty Python
• Created in 1991
• Used by millions worldwide

Let's do some math:
10 + 20 = 30
50 - 15 = 35
7 * 8 = 56

========================================
  Thanks for running my program!  
========================================

Common Beginner Mistakes

Mistake Problem Solution
print "Hello" Missing parentheses print("Hello")
print("Hello') Mismatched quotes print("Hello") or print('Hello')
Print("Hello") Python is case-sensitive print("Hello")
prnt("Hello") Typo in function name print("Hello")
# Wrong
print "Hello"           # SyntaxError: Missing parentheses
Print("Hello")          # NameError: name 'Print' is not defined
print("Hello')          # SyntaxError: EOL while scanning string

# Correct
print("Hello")
print('Hello')

Key Takeaways


                Remember These Points                     

                                                          
  • print() displays output to the screen                
                                                          
  • Strings use quotes: "text" or 'text'                 
                                                          
  • Comments start with # and are ignored                
                                                          
  • Python files use the .py extension                   
                                                          
  • Run scripts with: python filename.py                 
                                                          
  • Python is case-sensitive                             
                                                          

What's Next

You've written and run your first Python programs. In the next lesson, we'll dive deeper into Python's syntax - understanding the rules and structure that make Python code work.

Keep experimenting with print() - try different messages, calculations, and have fun with it.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service