Learn Python programming from scratch with our comprehensive tutorial
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
Python syntax is very clean and easy to understand. Let's look at some basic syntax rules:
# 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"
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.
if 5 > 2:
print("Five is greater than two!") # Correct indentation
if 5 > 2:
print("Five is greater than two!") # Wrong indentation
Variables are containers for storing data values. In Python, variables are created when you assign a value to them.
# 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)
Python has various data types built-in by default. Here are the main categories:
# 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))
Lists are used to store multiple items in a single variable. Lists are ordered, changeable, and allow duplicate values.
# 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
Tuples are used to store multiple items in a single variable. Tuples are ordered and unchangeable.
# 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
Dictionaries are used to store data values in key:value pairs. Dictionaries are ordered, changeable, and do not allow duplicates.
# 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
Python supports the usual logical conditions from mathematics. These conditions can be used in several ways, most commonly in "if statements" and loops.
# 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")
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
# 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)
With the while loop we can execute a set of statements as long as a condition is true.
# 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")
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.
# 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))
Python Comments
Comments can be used to explain Python code and make it more readable. Comments start with a #.
Comment Types