Python is a versatile and beginner-friendly programming language, making it a great choice for macOS users. This guide will help you get started with Python in just 10 minutes.
Step 1: Check Python Installation
Open Terminal (search for "Terminal" in Spotlight or find it in Applications > Utilities).
Check if Python is installed by typing:
python3 --version
If Python is installed, you’ll see a version number like
Python 3.x.x
.If not, download Python or install it via Homebrew:
brew install python
Step 2: Write Your First Python Script
Create a new file for your script by typing:
nano hello.py
In the editor, type the following code:
print("Hello, World!")
Save and exit:
Press
Ctrl + X
, thenY
, and hitEnter
.
Run your script:
python3 hello.py
You should see this output:
Hello, World!
Step 3: Use Python Interactively
Open the Python interactive shell:
python3
You’ll see a prompt like this:
>>>
Try typing Python commands directly:
print("Welcome to Python!")
Press
Enter
to see the output:Welcome to Python!
Exit the shell by typing:
exit()
Step 4: Explore Python Basics
Experiment with Python basics by running commands in the interactive shell or writing scripts:
Variables:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
Loops:
for i in range(5):
print(f"Number: {i}")
Functions:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Lists:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
Step 5: Use Python Modules
Python includes powerful built-in modules. Try these examples:
Math Module:
import math
print(math.sqrt(16))
Datetime Module:
from datetime import datetime
print(datetime.now())
Step 6: Install Python Packages
Use pip
to install additional libraries.
Install the
requests
library:pip3 install requests
Write a script to fetch data from a website:
import requests response = requests.get("https://api.github.com") print(response.json())
Step 7: Virtual Environment (Optional)
Set up an isolated Python environment for your projects:
Create a virtual environment:
python3 -m venv myenv
Activate the environment:
source myenv/bin/activate
Install Python packages within the virtual environment.
When done, deactivate the environment:
deactivate
Step 8: Use a Code Editor
For a better coding experience, use a code editor like Visual Studio Code:
Install VS Code.
Add the Python extension:
Open VS Code.
Go to Extensions (
Cmd + Shift + X
).Search for "Python" and install it.
Summary
Write Python scripts using
nano
or a text editor.Run scripts with
python3 <script_name.py>
.Experiment with basic Python commands in the interactive shell.
Install additional libraries using
pip3
.Use a code editor like VS Code for enhanced productivity.
With this quick introduction, you’re ready to start exploring Python on your Mac. Happy coding!
Comments
Post a Comment