1. Installing Python on Windows:
- Download the Installer:
- Go to the official Python website: python.org/downloads.
- Download the latest version of Python by clicking on the appropriate link for Windows.
- Run the Installer:
- After downloading, run the installer.
- Check the box that says “Add Python to PATH” at the bottom of the installer window. This will allow you to run Python from the command line without specifying its full path.
- Choose “Install Now” for a standard installation, or “Customize Installation” if you want more control over the process (e.g., specifying installation directories, adding optional features).
- Verify the Installation:
- Open the Command Prompt
- (press
Win + R
, typecmd
, and hit Enter). - Type
python --version
orpython -V
and press Enter. You should see the version of Python you installed. - Optionally, type
pip --version
to check ifpip
(Python’s package manager) was installed correctly.
2. Installing Python on macOS:
- Check the Pre-installed Version:
- macOS typically comes with an older version of Python pre-installed. You can check this by opening the Terminal (press
Cmd + Space
, typeTerminal
, and press Enter) and running: python --version
- However, it’s usually better to install the latest version manually.
- macOS typically comes with an older version of Python pre-installed. You can check this by opening the Terminal (press
- Install Homebrew (Optional but Recommended):
- Homebrew is a popular package manager for macOS, which makes it easier to install software.
- To install Homebrew, open Terminal and run:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Install Python Using Homebrew:
- Once Homebrew is installed, you can install Python by running:
brew install python
- This will install the latest version of Python and
pip
.
- Once Homebrew is installed, you can install Python by running:
- Verify the Installation:
- In Terminal, type
python3 --version
and press Enter to check the installed version of Python (Homebrew installs it aspython3
). - You can also check the
pip
installation withpip3 --version
.
- In Terminal, type
3. Installing Python on Linux:
- Check if Python is Already Installed:
- Most Linux distributions come with Python pre-installed. You can check the version by opening the Terminal and running:
python3 --version
- Most Linux distributions come with Python pre-installed. You can check the version by opening the Terminal and running:
- Install Python Using the Package Manager:
- If you need a different version or it’s not installed, you can use your distribution’s package manager.
- For Debian/Ubuntu:
sudo apt update sudo apt install python3
- For Fedora:
sudo dnf install python3
- For Arch Linux:
sudo pacman -S python
- Verify the Installation:
- After installation, check the version with
python3 --version
. pip
should also be installed by default. You can verify it withpip3 --version
.
- After installation, check the version with
Python Quickstart:
Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:C:\Users\Your Name>python helloworld.py
Where “helloworld.py” is the name of your python file.
Let’s write our first Python file, called helloworld.py, which can be done in any text editor.helloworld.py
print("Hello, World!")
Simple as that. Save your file. Open your command line, navigate to the directory where you saved your file, and run:C:\Users\Your Name>python helloworld.py
The output should read:Hello, World!
The Python Command Line
To test a short amount of code in python sometimes it is quickest and easiest not to write the code in a file. This is made possible because Python can be run as a command line itself.
Type the following on the Windows, Mac or Linux command line:C:\Users\Your Name>pythonOr, if the “python” command did not work, you can try “py”:C:\Users\Your Name>py
From there you can write any python, including our hello world example from earlier in the tutorial:C:\Users\Your Name>python
>>> print(“Hello, World!”)
Which will write “Hello, World!” in the command line:C:\Users\Your Name>python
>>> print(“Hello, World!”)
Hello, World!
Whenever you are done in the python command line, you can simply type the following to quit the python command line interface:
exit()
Python syntax refers to the set of rules that define how Python programs are written and interpreted by the Python interpreter. Python’s syntax is designed to be clean, readable, and straightforward, which makes it an excellent choice for beginners. Below are key elements of Python syntax:
1. Indentation:
- Python uses indentation (whitespace) to define the structure of the code, rather than braces
{}
or keywords likebegin
andend
. - Indentation is crucial in Python and determines the grouping of statements.
- Example:
if x > 0: print("x is positive")
- In the example above, the
print
statement is indented and thus is considered part of theif
block.
2. Variables and Data Types:
- Variables in Python are dynamically typed, meaning you don’t need to declare their type explicitly.
- Example:
name = "Alice" # String age = 30 # Integer height = 5.7 # Float is_student = True # Boolean
- Python determines the type of the variable based on the value assigned.
3. Comments:
- Python uses the hash symbol
#
for single-line comments. - Example:
# This is a comment print("Hello, world!")
# This prints a message
- For multi-line comments, triple quotes (
'''
or"""
) can be used, although they are typically reserved for docstrings. """ This is a multi-line comment or a docstring. """
4. Functions:
- Functions are defined using the
def
keyword, followed by the function name, parentheses, and a colon. The function body is indented.
- Example:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
- This function takes a parameter
name
and prints a greeting.
5. Control Flow (if, else, elif):
- Python uses
if
,elif
(else if), andelse
to handle conditional logic. - Example:
x = 10 if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
6. Loops (for, while):
- For Loops: Iterate over a sequence (such as a list, tuple, or string).
for i in range(5):
print(i)
- output: 0 1 2 3 4
- While Loops: Repeat as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
7. Lists, Tuples, and Dictionaries:
- Lists: Ordered, mutable collections of items.
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Access the first item
- Tuples: Ordered, immutable collections of items.
coordinates = (10, 20)
print(coordinates[1]) # Access the second item
- Dictionaries: Unordered collections of key-value pairs.
person = {"name": "Alice", "age": 30} print(person["name"]) # Access value by key
8. Loops with Enumerate and Zip:
- Enumerate: Loop through a list with an index.
for index, value in enumerate(fruits):
print(index, value)
- Zip: Loop through two lists in parallel.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 95] for name,
score in zip(names, scores):
print(f"{name}: {score}")
9. Exception Handling:
- Python uses
try
,except
,else
, andfinally
to handle exceptions (errors that occur during runtime). - Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
finally:
print("This code runs no matter what.")
10. Importing Modules:
- Python has a rich standard library, and you can also install third-party libraries. You can import them using the
import
statement. - Example:
import math
print(math.sqrt(16)) # Output: 4.0
11. List Comprehensions:
- List comprehensions provide a concise way to create lists.
- Example:
squares = [x**2 for x in range(10)]
print(squares)
# Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
12. Classes and Objects:
- Python supports object-oriented programming. You can define classes and create objects.
- Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print(f"{self.name} says woof!")
my_dog = Dog("Buddy", 5)
my_dog.bark() # Output: Buddy says woof!
13. Lambda Functions:
- Lambda functions are small anonymous functions defined using the
lambda
keyword. - Example:
square = lambda x:
x ** 2 print(square(5)) # Output: 25
14. File I/O:
- Python allows you to read from and write to files easily.
- Example:
# Writing to a file with open("example.txt", "w") as file: file.write("Hello, world!")
# Reading from a file
with open("example.txt", "r") as file:
content = file.read()
print(content)
15. Using the __name__ == "__main__"
construct:
- This is a common Python idiom used to ensure that certain code only runs when the script is executed directly, not when it is imported as a module.
- Example:
def main():
print("This code runs only if the script is executed directly.")
if __name__ == "__main__": main()