Python Tutorial

Learn Python programming from scratch with our comprehensive tutorial

Python Introduction

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

What is Python?

  • Python is a high-level, interpreted programming language
  • Python is known for its simple syntax and readability
  • Python supports multiple programming paradigms
  • Python has a large standard library

What Can Python Do?

  • Web development (server-side)
  • Software development
  • Mathematics
  • System scripting
  • Data analysis
  • Machine learning
  • Artificial intelligence

Why Python?

  • Works on different platforms (Windows, Mac, Linux, etc.)
  • Simple syntax similar to English
  • Allows developers to write programs with fewer lines
  • Runs on an interpreter system
  • Can be treated in procedural, object-oriented, or functional way

Python Syntax

Python syntax is very clean and easy to understand. Let's look at some basic syntax rules:

Example
# This is a comment
print("Hello, World!")  # This is also a comment

# Variables
x = 5
y = "Hello"

# Functions
def my_function():
    print("Hello from a function")

# Classes
class MyClass:
    def __init__(self):
        self.name = "MyClass"

Basic Syntax Rules

  • Python uses indentation to indicate blocks of code
  • Comments start with #
  • Variables are created when you assign a value to them
  • Python is case-sensitive
  • Python uses new lines to complete commands

Python Indentation

Indentation refers to the spaces at the beginning of a code line. In Python, indentation is very important and is used to indicate a block of code.

Example
if 5 > 2:
    print("Five is greater than two!")  # Correct indentation

if 5 > 2:
print("Five is greater than two!")  # Wrong indentation

Indentation Rules

  • Python uses indentation to indicate a block of code
  • The number of spaces is up to you, but it must be at least one
  • You have to use the same number of spaces in the same block of code
  • Python will give you an error if you skip the indentation

Python Variables

Variables are containers for storing data values. In Python, variables are created when you assign a value to them.

Example
# Variables
x = 5
y = "Hello"
z = 3.14

# Multiple assignment
a, b, c = "Orange", "Banana", "Cherry"

# Global variables
global_var = "I am global"

def myfunc():
    local_var = "I am local"
    print(global_var)
    print(local_var)

Variable Rules

  • A variable name must start with a letter or underscore
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores
  • Variable names are case-sensitive

Python Comments

Comments can be used to explain Python code and make it more readable. Comments start with a #.

Example
# This is a comment
print("Hello, World!")  # This is also a comment

"""
This is a
multiline comment
"""

def my_function():
    # This is a function comment
    print("Hello from a function")

Comment Types

  • Single line comments start with #
  • Multi-line comments can be written using triple quotes
  • Comments can be placed at the end of a line
  • Comments are ignored by Python

Python Data Types

Python has various data types built-in by default. Here are the main categories:

Example
# Text Type
str_var = "Hello World"

# Numeric Types
int_var = 20
float_var = 20.5
complex_var = 1j

# Sequence Types
list_var = ["apple", "banana", "cherry"]
tuple_var = ("apple", "banana", "cherry")
range_var = range(6)

# Mapping Type
dict_var = {"name": "John", "age": 36}

# Set Types
set_var = {"apple", "banana", "cherry"}
frozenset_var = frozenset({"apple", "banana", "cherry"})

# Boolean Type
bool_var = True

# Binary Types
bytes_var = b"Hello"
bytearray_var = bytearray(5)
memoryview_var = memoryview(bytes(5))

Data Type Categories

  • Text Type: str
  • Numeric Types: int, float, complex
  • Sequence Types: list, tuple, range
  • Mapping Type: dict
  • Set Types: set, frozenset
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview

Python Lists

Lists are used to store multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.

Example
# Create a list
thislist = ["apple", "banana", "cherry"]
print(thislist)

# Access list items
print(thislist[1])  # banana

# Change list items
thislist[1] = "blackcurrant"
print(thislist)

# List methods
thislist.append("orange")  # Add item
thislist.remove("banana")  # Remove item
thislist.pop()  # Remove last item
thislist.insert(1, "orange")  # Insert item
thislist.sort()  # Sort list

List Methods

  • append() - Adds an element at the end
  • clear() - Removes all elements
  • copy() - Returns a copy
  • count() - Returns number of elements
  • extend() - Add elements of a list
  • index() - Returns index of first element
  • insert() - Adds element at position
  • pop() - Removes element at position
  • remove() - Removes item with value
  • reverse() - Reverses the order
  • sort() - Sorts the list

Python Tuples

Tuples are used to store multiple items in a single variable. Tuples are ordered and unchangeable.

Example
# Create a tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple)

# Access tuple items
print(thistuple[1])  # banana

# Tuple methods
x = thistuple.count("apple")  # Count occurrences
y = thistuple.index("banana")  # Find index

# Unpacking a tuple
(green, yellow, red) = thistuple
print(green)  # apple
print(yellow)  # banana
print(red)  # cherry

Tuple Methods

  • count() - Returns number of occurrences
  • index() - Returns index of first occurrence

Python Dictionary

Dictionaries are used to store data values in key:value pairs. Dictionaries are ordered, changeable, and do not allow duplicates.

Example
# Create a dictionary
thisdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
print(thisdict)

# Access dictionary items
print(thisdict["model"])  # Mustang

# Dictionary methods
x = thisdict.get("model")  # Get value
thisdict["year"] = 2020  # Change value
thisdict["color"] = "red"  # Add item
thisdict.pop("model")  # Remove item
thisdict.clear()  # Clear dictionary

Dictionary Methods

  • clear() - Removes all elements
  • copy() - Returns a copy
  • fromkeys() - Returns dictionary with keys
  • get() - Returns value of key
  • items() - Returns list of tuples
  • keys() - Returns list of keys
  • pop() - Removes element with key
  • popitem() - Removes last inserted pair
  • setdefault() - Returns value of key
  • update() - Updates dictionary
  • values() - Returns list of values

Python if...else

Python supports the usual logical conditions from mathematics. These conditions can be used in several ways, most commonly in "if statements" and loops.

Example
# If statement
a = 200
b = 33
if b > a:
    print("b is greater than a")
elif a == b:
    print("a and b are equal")
else:
    print("a is greater than b")

# Short hand if
if a > b: print("a is greater than b")

# Short hand if...else
print("A") if a > b else print("B")

# And
if a > b and c > a:
    print("Both conditions are True")

# Or
if a > b or a > c:
    print("At least one condition is True")

Conditional Statements

  • if - Executes code if condition is true
  • elif - Executes code if previous conditions were false
  • else - Executes code if all conditions are false
  • and - Returns True if both statements are true
  • or - Returns True if one of the statements is true
  • not - Reverse the result

Python For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

Example
# Loop through a list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
    print(x)

# Loop through a string
for x in "banana":
    print(x)

# The break statement
for x in fruits:
    print(x)
    if x == "banana":
        break

# The continue statement
for x in fruits:
    if x == "banana":
        continue
    print(x)

# The range() function
for x in range(6):
    print(x)

# Nested loops
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
    for y in fruits:
        print(x, y)

Loop Control Statements

  • break - Stops the loop
  • continue - Skips current iteration
  • pass - Does nothing

Python While Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example
# While loop
i = 1
while i < 6:
    print(i)
    i += 1

# The break statement
i = 1
while i < 6:
    print(i)
    if i == 3:
        break
    i += 1

# The continue statement
i = 0
while i < 6:
    i += 1
    if i == 3:
        continue
    print(i)

# The else statement
i = 1
while i < 6:
    print(i)
    i += 1
else:
    print("i is no longer less than 6")

While Loop Features

  • Executes code while condition is true
  • Can use break to stop the loop
  • Can use continue to skip iteration
  • Can use else to run code when condition is false

Python Functions

A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.

Example
# Create a function
def my_function():
    print("Hello from a function")

# Call a function
my_function()

# Parameters
def my_function(fname):
    print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

# Default parameter value
def my_function(country = "Norway"):
    print("I am from " + country)

my_function("Sweden")
my_function()

# Return values
def my_function(x):
    return 5 * x

print(my_function(3))
print(my_function(5))
print(my_function(9))

Function Features

  • Can take parameters
  • Can return values
  • Can have default parameter values
  • Can be called multiple times
  • Can be recursive