Step-by-Step Python Environment Setup in VS Code
This guide will walk you through setting up your Python development environment using Visual Studio Code
(VS Code), a popular and powerful code editor.
Prerequisites
Before you start, make sure you have:
1. Python Installed: Download and install Python from the official website: python.org/downloads.
During installation, make sure to check "Add Python to PATH".
2. Visual Studio Code Installed: Download and install VS Code from the official website:
code.visualstudio.com.
Step 1: Install the Python Extension in VS Code
The Python extension provides rich language support, including IntelliSense, linting, debugging, and more.
1. Open VS Code.
2. Go to the Extensions View: Click on the Extensions icon in the Activity Bar on the side of VS Code (it
looks like four squares, one of which is detached). Alternatively, press Ctrl+Shift+X
(Windows/Linux) or Cmd+Shift+X (macOS).
3. Search for "Python": In the search bar at the top of the Extensions view, type "Python".
4. Install the Official Python Extension: Look for the extension published by "Microsoft" and click the
"Install" button.
Step 2: Create a New Project Folder
It's good practice to organize your Python projects in dedicated folders.
1. Open the Command Palette: Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS).
2. Select "File: Open Folder...": Type "Open Folder" and select the corresponding option.
3. Navigate and Create/Select a Folder: Choose a location on your computer, create a new folder (e.g.,
my_python_project), and click "Select Folder".
Step 3: Create a Python File
Now, let's create your first Python script.
1. Open the Explorer View: Click on the Explorer icon in the Activity Bar (the top icon, resembling two
overlapping sheets of paper). Alternatively, press Ctrl+Shift+E (Windows/Linux) or Cmd+Shift+E
(macOS).
2. Create a New File: In the Explorer view, hover over your project folder name and click the "New File"
icon (a small file icon with a plus sign).
3. Name Your File: Type a name for your file, ending with .py (e.g., hello.py), and press Enter.
Step 4: Write and Run Your First Python Code
Let's write the classic "Hello, World!" program.
1. Write Code: In the hello.py file, type the following:
print("Hello, HARVARD Computer Science!")
2. Run the Code:
o Option A (Run Button): Click the green "Run" button in the top-right corner of the editor
window.
o Option B (Right-Click): Right-click anywhere in the editor and select "Run Python File in
Terminal".
o Option C (Terminal): Open the integrated terminal (Ctrl+ backtick or Cmd+ backtick) and type:
o python hello.py
3. View Output: The output "Hello, HARVARD Computer Science!" will appear in the integrated
terminal at the bottom of VS Code.
Step 5: (Optional but Recommended) Using Virtual Environments
Virtual environments are crucial for managing project dependencies and avoiding conflicts between different
projects.
1. Open the Command Palette: Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS).
2. Create Virtual Environment: Type "Python: Create Virtual Environment" and select the option.
3. Choose Interpreter and Environment Type:
o Select the Python interpreter you want to use (e.g., Python 3.x.x).
o Choose venv (recommended for most cases).
o VS Code will create a .venv folder in your project directory and automatically activate it for
your workspace.
4. Verify Activation: You'll see (.venv) or a similar indicator in your terminal prompt, confirming the
virtual environment is active.
The Python interpreter is like a translator that reads and executes your Python code line by line. When you write
a Python program, you save it as a .py file. The interpreter then takes this file and turns your human-readable
code into instructions that the computer can understand and run.
Here's a breakdown of the Python interpreter and basic syntax:
The Python Interpreter
1. What it does: It executes Python code directly. You can run Python scripts (files ending in .py) or type
commands interactively.
2. Interactive Mode (REPL - Read-Eval-Print Loop):
o You can open your terminal or command prompt and type python (or python3).
o This will launch the interactive interpreter, where you'll see a >>> prompt.
o You can type Python code directly here, and the interpreter will execute it immediately and show
the result. This is great for testing small snippets of code.
o Example:
Python
>>> print("Hello, HARVARD!")
Hello, HARVARD!
>>> 5 + 3
8
3. Script Mode:
o You write your Python code in a text file (e.g., my_program.py).
o You then run this file using the interpreter from your terminal: python my_program.py.
o The interpreter reads the entire file and executes the code.
Basic Python Syntax
Python is known for its readability and simple syntax, which often resembles plain English.
1. Comments:
o Used to explain your code. The interpreter ignores them.
o Start with a # symbol.
o Example:
Python
# This is a single-line comment
print("Hello") # This comment explains the print statement
2. Variables:
o Used to store data. You don't need to declare their type explicitly; Python infers it.
o Assignment uses the = operator.
o Variable names are case-sensitive and typically use snake_case (all lowercase, words separated
by underscores).
o Example:
Python
name = "Alice"
age = 30
is_student = True
3. Data Types:
o Integers (int): Whole numbers (e.g., 10, -5, 0).
o Floating-point numbers (float): Numbers with decimal points (e.g., 3.14, -0.5, 2.0).
o Strings (str): Sequences of characters, enclosed in single (' ') or double (" ") quotes.
o Booleans (bool): Represent truth values: True or False.
o Example:
Python
my_integer = 10
my_float = 2.5
my_string = "Python is fun!"
my_boolean = False
4. Basic Input/Output:
o print() function: Displays output to the console.
Python
print("Welcome to 6.0001!")
print("The sum of 2 and 3 is:", 2 + 3)
o input() function: Gets input from the user. The input is always read as a string.
Python
user_name = input("What is your name? ")
print("Hello,", user_name)
# To use numerical input, you need to convert it
age_str = input("How old are you? ")
age_int = int(age_str) # Convert string to integer
print("You will be", age_int + 1, "next year.")
5. Operators:
Arithmetic:
+ (addition)
- (subtraction)
* (multiplication),
/ (division)
// (floor division)
% (modulo)
** (exponentiation)
Comparison:
== (equal to)
!= (not equal to)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)
These return True or False.
Logical: and, or, not. Used to combine boolean expressions.
Control Flow
Control flow refers to the order in which the program's instructions are executed. Without control flow
statements, a program would simply execute from top to bottom, line by line. Control flow allows your program
to make decisions, repeat actions, and respond dynamically to data.
1. Conditional Statements (if, elif, else)
These statements allow your program to execute different blocks of code based on whether certain conditions
are true or false.
if statement: Executes a block of code if a condition is true.
Python
age = 20
if age >= 18:
print("You are old enough to vote.")
else statement: Executes a block of code if the if condition (and any elif conditions) is false.
Python
temperature = 15
if temperature > 25:
print("It's hot outside!")
else:
print("It's not too hot.")
elif (else if) statement: Allows you to check multiple conditions sequentially.
Python
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
o Important: Python uses indentation (typically 4 spaces) to define code blocks. This is crucial
and not just for readability like in many other languages.
2. Loops (for, while)
Loops allow you to repeatedly execute a block of code.
for loop: Used for iterating over a sequence (like a list, tuple, string, or range).
Python
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range() to loop a specific number of times
# range(5) generates numbers 0, 1, 2, 3, 4
for i in range(5):
print(f"Counting: {i}")
# range(start, stop, step)
for i in range(1, 10, 2): # Prints 1, 3, 5, 7, 9
print(i)
while loop: Executes a block of code as long as a certain condition is true.
Python
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Increment count to eventually stop the loop
3. Loop Control Statements (break, continue)
break: Terminates the loop entirely.
Python
for i in range(10):
if i == 5:
break # Exit the loop when i is 5
print(i) # Prints 0, 1, 2, 3, 4
continue: Skips the rest of the current iteration and moves to the next iteration of the loop.
Python
for i in range(5):
if i == 2:
continue # Skip printing when i is 2
print(i) # Prints 0, 1, 3, 4
Functions
Functions are blocks of organized, reusable code that perform a single, related action. They help break down
your program into smaller, manageable, and modular pieces, making your code easier to understand, debug, and
maintain.
1. Defining a Function
You define a function using the def keyword, followed by the function name, parentheses (), and a colon :.
Python
def greet():
"""This function prints a greeting message."""
print("Hello, world!")
# Calling the function
greet() # Output: Hello, world!
The string immediately after the def line is called a docstring. It's a good practice to include it to
explain what the function does.
2. Parameters and Arguments
Parameters: Variables listed inside the parentheses in the function definition. They act as placeholders
for values that will be passed into the function.
Arguments: The actual values passed to the function when it is called.
Python
def greet_person(name): # 'name' is a parameter
"""This function greets a person by their name."""
print(f"Hello, {name}!")
greet_person("Alice") # "Alice" is an argument
greet_person("Bob") # "Bob" is an argument
3. Return Values
Functions can return a value using the return statement. If a function doesn't explicitly return a value, it
implicitly returns None.
Python
def add(a, b):
"""This function returns the sum of two numbers."""
return a + b
result = add(5, 3)
print(result) # Output: 8
def is_even(number):
"""Checks if a number is even."""
if number % 2 == 0:
return True
else:
return False
print(is_even(4)) # Output: True
print(is_even(7)) # Output: False
4. Scope of Variables (Local vs. Global)
Local Scope: Variables defined inside a function are local to that function. They can only be accessed
from within that function.
Global Scope: Variables defined outside any function are global. They can be accessed from anywhere
in the program, including inside functions. However, it's generally a bad practice to modify global
variables directly from within a function without explicitly declaring them as global.
Python
global_message = "I am global" # Global variable
def my_function():
local_message = "I am local" # Local variable
print(local_message)
print(global_message) # Can access global variable
my_function()
# print(local_message)
# This would cause an error, local_message is not defined outside my_function
print(global_message)
Practice Coding
Problem: Simple Grade Calculator
Objective: Write a Python program that takes a student's numerical score as input and prints their
corresponding letter grade.
Requirements:
1. Input: The program should prompt the user to enter a numerical score (an integer between 0 and 100).
2. Grading Logic (Control Flow):
o 90-100: A
o 80-89: B
o 70-79: C
o 60-69: D
o 0-59: F
3. Function: Encapsulate the grading logic within a function called calculate_grade that takes the score
as an argument and returns the letter grade (a string).
4. Output: The program should print the student's score and their calculated letter grade.
5. Error Handling (Optional but good practice): Consider what happens if the user enters a score
outside the 0-100 range. You could print an "Invalid score" message.
Example Interaction:
Enter the student's score (0-100): 85
Score: 85, Grade: B
Enter the student's score (0-100): 92 Score: 92, Grade: A
Enter the student's score (0-100): 55
Score: 55, Grade: F
This problem will allow you to practice:
Taking user input (input()).
Converting input to the correct data type (int()).
Using conditional statements (if, elif, else) for decision-making.
Defining and calling a function.
Returning values from a function.
Problem: Simple User Authentication System
Objective: Write a Python program that simulates a basic user authentication system by verifying a username
and password.
Requirements:
1. Predefined Credentials:
o Set a valid username (e.g., "student") and a valid password (e.g., "password123") within your
program. These will be the credentials that users need to match.
2. Input: The program should prompt the user to enter their username and then their password.
3. Authentication Logic (Control Flow):
o Compare the entered username with the predefined valid username.
o If the username matches, then compare the entered password with the predefined valid password.
o If both match, the user is authenticated.
o If the username is correct but the password is wrong, indicate a password error.
o If the username is incorrect, indicate a username error.
4. Function: Encapsulate the authentication logic within a function called authenticate_user that takes
entered_username and entered_password as arguments. This function should return True if
authentication is successful, and False otherwise.
5. Output:
o If authentication is successful, print: "Login successful! Welcome, [username]!"
o If the username is correct but the password is wrong, print: "Incorrect password. Please
try again."
o If the username is incorrect, print: "Username not found. Please check your username."
Example Interactions:
Successful Login:
Enter your username: student
Enter your password: password123
Login successful! Welcome, student!
Incorrect Password:
Enter your username: student
Enter your password: wrongpass
Incorrect password. Please try again.
Incorrect Username:
Enter your username: guest
Enter your password: anypassword
Username not found. Please check your username.
This problem will allow you to practice:
Taking multiple user inputs.
Using nested conditional statements (if, else, potentially elif) to handle different scenarios.
Defining a function that takes multiple arguments.
Returning a boolean value from a function to indicate success or failure.
Providing clear feedback to the user based on the program's logic.
Problem: Palindrome Checker
Objective: Write a Python program that determines if a given word is a palindrome. A palindrome is a word,
phrase, number, or other sequence of characters which reads the same backward as forward (e.g., "madam" or
"racecar").
Requirements:
1. Input: The program should prompt the user to enter a single word.
2. Palindrome Logic (Control Flow):
o You'll need to compare the entered word with its reversed version.
o Consider how to reverse a string in Python.
o The comparison should be case-insensitive (e.g., "Madam" should be considered a palindrome).
3. Function: Encapsulate the palindrome checking logic within a function called is_palindrome that
takes the word (string) as an argument and returns True if it's a palindrome, and False otherwise.
4. Output:
o If the word is a palindrome, print: "[word] is a palindrome!"
o If the word is not a palindrome, print: "[word] is NOT a palindrome."
Example Interactions:
Palindrome:
Enter a word: level
level is a palindrome!
Enter a word: Racecar Racecar is a palindrome!
**Not a Palindrome:**
Enter a word: hello hello is NOT a palindrome.
Enter a word: Python
Python is NOT a palindrome.
This problem will help you practice:
Taking user input (input()).
String manipulation (reversing a string, converting case).
Using conditional statements (if, else) for decision-making.
Defining and calling a function with a string argument.
Returning a boolean value from a function.
Problem: Substring Occurrence Counter
Objective: Write a Python program that counts how many times a specific substring appears within a larger
string (a sentence or paragraph).
Requirements:
1. Input:
o Prompt the user to enter a main string (e.g., a sentence).
o Prompt the user to enter the substring they want to count.
2. Counting Logic (Control Flow):
o You'll need to iterate through the main string to find occurrences of the substring.
o Consider using string methods like count() for a simple solution, or implement a manual
counting logic using loops and string slicing/indexing for more practice with control flow.
o The comparison should be case-insensitive (e.g., "The" should match "the").
3. Function: Encapsulate the counting logic within a function called count_substring_occurrences that
takes the main_string and sub_string as arguments. This function should return the total count of
occurrences (an integer).
4. Output: Print the main string, the substring, and the total number of times the substring appears.
Example Interactions:
Example 1:
Enter the main string: The quick brown fox jumps over the lazy dog. The fox is quick.
Enter the substring to count: the
The substring 'the' appears 2 times in the main string.
Example 2:
Enter the main string: Programming is fun. Python programming is even more fun!
Enter the substring to count: fun
The substring 'fun' appears 2 times in the main string.
Example 3 (Case-Insensitive):
Enter the main string: Apple, apple, APPLE pie.
Enter the substring to count: apple
The substring 'apple' appears 3 times in the main string.
This problem will help you practice:
Taking user input (input()).
String manipulation (converting case, potentially slicing).
Using functions with multiple string arguments.
Implementing counting logic, possibly with loops or built-in string methods.
Returning an integer value from a function.
Problem: Leap Year Checker
Objective: Write a Python program that determines if a given year is a leap year.
Leap Year Rules: A year is a leap year if:
1. It is evenly divisible by 4.
2. Except if it is evenly divisible by 100, then it is NOT a leap year.
3. Unless it is also evenly divisible by 400, then it IS a leap year.
Requirements:
1. Input: The program should prompt the user to enter a year (an integer).
2. Leap Year Logic (Control Flow): Implement the rules above using conditional statements.
o Hint: Use the modulo operator (%) to check for divisibility.
3. Function: Encapsulate the leap year checking logic within a function called is_leap_year that takes
the year (integer) as an argument and returns True if it's a leap year, and False otherwise.
4. Output:
o If the year is a leap year, print: "[Year] is a leap year."
o If the year is not a leap year, print: "[Year] is NOT a leap year."
Example Interactions:
Leap Years:
Enter a year: 2000
2000 is a leap year.
Enter a year: 2024 2024 is a leap year.
**Not Leap Years:**
Enter a year: 1900 1900 is NOT a leap year.
Enter a year: 2023
2023 is NOT a leap year.
This problem will help you practice:
Taking user input (input()).
Converting input to the correct data type (int()).
Using complex conditional statements (if, elif, else) to handle multiple conditions.
Defining and calling a function with an integer argument.
Returning a boolean value from a function.