Python Tutorial

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

  • Used for web development, software development, mathematics, system scripting.
  • Works on multiple platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Syntax is clean and similar to the English language.
Python Example
print("Hello, World!")
Live Editor

Python Intro

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant indentation.

Key Concepts

  • Interpreted Language: Python code is executed line by line, making debugging easier.
  • High-level: Abstracts away complex computer details, focusing on programming logic.
  • Dynamically Typed: You don't need to declare variable types explicitly.
  • Multi-paradigm: Supports object-oriented, imperative, and functional programming styles.

Python is often described as a "batteries included" language due to its comprehensive standard library. This means you can do a lot out-of-the-box without needing to install third-party packages. It is widely used in various domains, ranging from web development (using frameworks like Django and Flask) to data science, artificial intelligence, scientific computing, and simple task automation.

Unlike languages like C++ or Java, Python uses whitespace (indentation) to define code blocks (like functions or loops) instead of curly braces. This enforces a clean, consistent coding style across all Python codebases.

Syntax / Code Snippets


# Basic Python syntax
print("Welcome to Python!") 
# No semicolons required at the end of the line
            
Example: A Simple Python Script

name = "LearnX Student"
print(f"Hello, {name}! Let's learn Python.")
            
Live Editor

Real-World Use Case

A data analyst using Python to load a CSV file and calculate the average sales for a month without complex configuration or compilation steps.

Common Mistakes and Pitfalls

  • Mixing tabs and spaces for indentation, which raises an `IndentationError`.
  • Trying to compile Python code like C or Java (Python is interpreted).
  • Forgetting that Python strings can use either single quotes or double quotes, but they must match.

Best Practices

  • Follow the PEP 8 style guide for formatting your Python code properly.
  • Keep your codebase readable and use informative variable names.
  • Leverage Python's built-in functions instead of writing custom logic for standard operations.

Python Get Started

Python can be easily installed on Windows, macOS, and Linux. Once installed, writing and running Python code is remarkably quick.

Key Concepts

  • Download Python from the official python.org website.
  • Checking the Python version via the command line.
  • Writing code in an IDE (like VS Code, PyCharm) or a text editor.
  • Executing `.py` scripts from the terminal.

Modern Python development usually requires Python 3 (Python 2 is officially deprecated). When you install Python on Windows, make sure to check the box that says "Add Python to PATH". This step is crucial for running Python from any command prompt window.

After installation, you can interact with Python in two main ways: using the interactive shell (REPL) or by saving your code in a file with a .py extension and running it.

Commands to verify installation


# Check python version
python --version

# Run a python script
python myscript.py
            

Common Mistakes and Pitfalls

  • Forgetting to add Python to the system PATH during installation.
  • Having multiple versions of Python installed and using the wrong command (e.g., using `python` instead of `python3`).
  • Saving the python script with an extension like `.txt` instead of `.py`.

Best Practices

  • Always check your Python version before starting a new tutorial to avoid syntax mismatches.
  • Use Virtual Environments (venv) for projects to keep dependencies isolated.
  • Use a dedicated Integrated Development Environment (IDE) like VS Code equipped with Python extensions.

Python Syntax

Python's syntax was uniquely designed to be highly readable. It leverages English keywords where other languages use punctuation, and it uses indentation to define the structure of the code.

Key Concepts

  • Indentation: Python uses whitespace at the beginning of a line to define code blocks (unlike curly brackets `{}` in C++ or Java).
  • Variables: Created the moment you assign a value to it (no declaration commands).
  • Line Endings: A new line indicates the end of a command (no semicolons required).

Indentation is the most critical aspect of Python syntax. Where other programming languages use indentation purely for readability, Python uses it to indicate a block of code (e.g., the body of a loop, function, or conditional statement). You must use the same number of spaces for every line within the same block, though the standard convention is 4 spaces.

You can write multiple statements on one line by separating them with a semicolon, but this is highly discouraged in Python as it hurts readability.

Syntax / Code Snippets


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

# Incorrect indentation (will cause an error)
# if 5 > 2:
# print("Five is greater than two!")
            
Example: Code Blocks

x = 10
if x == 10:
    print("x is 10")
    print("This is inside the 'if' block")
print("This is outside the block")
            
Live Editor

Common Mistakes and Pitfalls

  • IndentationError: Usually caused by an unexpected indent, or missing an indent after a colon `:`.
  • TabError: Mixing tabs and spaces inside the same file. Always stick to spaces.

Best Practices

  • Use 4 spaces per indentation level. Avoid using tabs.
  • Configure your code editor to insert spaces when you press the Tab key.
  • Keep lines to a maximum of 79 characters as per PEP 8 guidelines.

Python Comments

Comments are an essential part of programming. They are used to explain Python code, make the code more readable, and can also be used to prevent execution when testing code blocks.

Key Concepts

  • Single-line Comments: Start with a # symbol.
  • End-of-line Comments: Placed at the end of a line of code.
  • Multi-line Comments: Python doesn't have a specific multi-line comment syntax, but you can insert a # on every line, or use an unassigned multi-line string.

When the Python interpreter encounters a #, it ignores the rest of the line. This means you can write whatever text you want after it, making it perfect for leaving notes for yourself or other developers.

For multi-line comments, you can add a # at the beginning of each line. Alternatively, you can use triple quotes """. Since Python will ignore string literals that are not assigned to a variable, many developers use triple quotes to write extensive documentation or comment out large chunks of code.

Syntax / Code Snippets


# This is a single-line comment
print("Hello, World!") # This is an end-of-line comment

"""
This is a comment
written in
more than just one line
"""
print("Multi-line comments are cool!")
            
Comment Example
# This is an important calculation
x = 5
y = 10
# print(x + y)  <-- This line is commented out and will not run
print("End of program")
Live Editor

Common Mistakes and Pitfalls

  • Forgetting that `#` inside a string literal like `print("# Hello")` does NOT start a comment.
  • Leaving commented-out code (dead code) in production files, leading to clutter.

Best Practices

  • Use comments to explain why you did something, not what the code does (the code itself should be readable enough to explain what it does).
  • Use docstrings (triple quotes) at the start of functions and classes to generate reliable documentation.

Python Variables

Variables are containers for storing data values. Unlike other programming languages, Python has no command for declaring a variable.

Key Concepts

  • A variable is created the moment you first assign a value to it.
  • Variables do not need to be declared with any particular type, and can even change type after they have been set (Dynamically Typed).
  • Case-Sensitive: `Age` and `age` are two different variables.
  • Naming Rules: Must start with a letter or underscore, cannot start with a number.

In Python, you simply assign a value to a variable name using the equals sign =. Under the hood, Python variables act as "labels" pointing to objects in memory rather than fixed buckets. This is why a variable can point to an integer on one line, and a string on the next.

You can also assign multiple variables in one line to keep your code concise (e.g., x, y, z = "Orange", "Banana", "Cherry"). If you want to assign the same value to multiple variables, you can do x = y = z = "Orange".

Syntax / Code Snippets


# Variable assignment
x = 5             # x is an integer
name = "John"     # name is a string
x = "Sally"       # x is now a string!

# Multiple variables in one line
a, b, c = 1, 2, 3
            
Variable Example
x = 5
y = "John"
print(x)
print(y)
Live Editor

Real-World Use Case

Variables are used to hold the state of an application. For example, a variable `score` keeps track of a player's points in a game, while `player_name` holds their username.

Common Mistakes and Pitfalls

  • Starting a variable name with a number (e.g., `2myvar = "John"`) which causes a SyntaxError.
  • Using reserved Python keywords (like `class`, `for`, `if`) as variable names.
  • Naming variables vaguely such as `a`, `b`, `c`, which makes code hard to maintain.

Best Practices

  • Use snake_case for variable names (e.g., `my_variable_name`).
  • Choose descriptive and meaningful names (`user_age` instead of `ua`).
  • Avoid overwriting built-in function names like `min`, `max`, or `list`.

Python Data Types

In programming, data type is an important concept. Variables can store data of different types, and different types allow you to perform different operations.

Built-in Data Types

  • 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
  • None Type: NoneType

Python variables are strongly but dynamically typed. You don't need to specify the type when declaring the variable, but Python tracks the type of the underlying object. To check the data type of any object, you can use Python's built-in type() function.

If you want to enforce a specific data type, you can use constructor functions like str(), int(), or list().

Syntax / Code Snippets


x = "Hello World"    # str
x = 20               # int
x = 20.5             # float
x = ["apple", "ban"] # list
x = {"name" : "Bob"} # dict
x = True             # bool
            
Getting the Data Type
x = 5
y = [1, 2, 3]

print(type(x))
print(type(y))
Live Editor

Common Mistakes and Pitfalls

  • Trying to concatenate strings and integers directly (e.g., `print("Age: " + 25)` throws a TypeError). You must cast the integer to a string first.
  • Confusing Lists `[]` and Tuples `()`. Lists are mutable, Tuples are immutable.

Best Practices

  • Use the `type()` function when debugging variables with unexpected behavior.
  • Use Python's Type Hinting (e.g., `def greet(name: str) -> str:`) to clarify data types in large applications.

Python Numbers

There are three distinct numeric types in Python: int, float, and complex. Variables of numeric types are created when you assign a value to them.

Key Concepts

  • Int (Integer): A whole number, positive or negative, without decimals, of unlimited length.
  • Float (Floating Point Number): A number, positive or negative, containing one or more decimals. It can also be a scientific number with an "e" to indicate the power of 10.
  • Complex: Complex numbers are written with a "j" as the imaginary part.

Python supports large numbers out of the box. Unlike C or Java where you have specific limits for `int` (like 32-bit limits), a Python `int` can be as large as your system's memory allows.

You can convert from one type to another with the int(), float(), and complex() methods. However, you cannot convert complex numbers into another number type.

Number Example
x = 1    # int
y = 2.8  # float
z = 1j   # complex

print(type(x))
print(type(y))
print(type(z))
Live Editor

Random Number Module

Python does not have a `random()` function built-in, but it has a built-in module called `random` that can be used to make random numbers:


import random
print(random.randrange(1, 10))
            

Common Mistakes and Pitfalls

  • Using floating-point numbers expecting perfect precision (e.g., `0.1 + 0.2 == 0.3` is False in Python due to IEEE 754 precision issues). Use the `decimal` module for exact money logic.
  • Attempting to cast a complex number to an `int` or `float` raises a TypeError.

Python Casting

Casting in python is therefore done using constructor functions:

  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number).
  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer).
  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals.
Casting Example
x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Python Strings

Strings in python are surrounded by either single quotation marks, or double quotation marks.

  • 'hello' is the same as "hello".
  • You can display a string literal with the print() function.
  • Quotes Inside Quotes: You can use quotes inside a string, as long as they don't match the quotes surrounding the string.
String Example
a = "Hello"
print(a)

Python Booleans

Booleans represent one of two values: True or False.

  • In programming you often need to know if an expression is True or False.
  • You can evaluate any expression in Python, and get one of two answers, True or False.
  • When you compare two values, the expression is evaluated and Python returns the Boolean answer.
Boolean Example
print(10 > 9)
print(10 == 9)
print(10 < 9)

Python Operators

Operators are used to perform operations on variables and values.

  • Arithmetic operators: Used with numeric values to perform common mathematical operations (+, -, *, /, %, **, //).
  • Assignment operators: Used to assign values to variables (=, +=, -=, *=, /=, etc.).
  • Comparison operators: Used to compare two values (==, !=, >, <,>=, <=).< /li>
  • Logical operators: Used to combine conditional statements (and, or, not).
Operator Example
print(10 + 5)

Python Lists

Lists are used to store multiple items in a single variable.

  • Lists are created using square brackets: [].
  • List items are ordered, changeable, and allow duplicate values.
  • List items are indexed, the first item has index [0].
List Example
thislist = ["apple", "banana", "cherry"]
print(thislist)
Live Editor

Python Tuples

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

  • A tuple is a collection which is ordered and unchangeable.
  • Tuples are written with round brackets: ().
  • Tuple items are indexed, the first item has index [0].
Tuple Example
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Python Sets

Sets are used to store multiple items in a single variable.

  • A set is a collection which is unordered, unchangeable*, and unindexed.
  • Sets are written with curly brackets: {}.
  • Set items are unordered, so you cannot be sure in which order the items will appear.
Set Example
thisset = {"apple", "banana", "cherry"}
print(thisset)

Python Dictionaries

Dictionaries are used to store data values in key:value pairs.

  • A dictionary is a collection which is ordered**, changeable and does not allow duplicates.
  • Dictionaries are written with curly brackets, and have keys and values.
Dictionary Example
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Python If...Else

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
If Example
a = 33
b = 200
if b > a:
  print("b is greater than a")
Live Editor

Python While Loops

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

  • The while loop requires relevant variables to be ready.
  • Remember to increment the iterator, or else the loop will continue forever.
While Example
i = 1
while i < 6:
  print(i)
  i += 1

Python For Loops

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

  • This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
  • Items in a sequence are processed one by one.
For Example
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

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.
  • A function can return data as a result.
  • In Python, a function is defined using the def keyword.
Function Example
def my_function():
  print("Hello from a function")

my_function()
Live Editor

Python Lambda

A lambda function is a small anonymous function.

  • A lambda function can take any number of arguments, but can only have one expression.
  • Syntax: lambda arguments : expression
Lambda Example
x = lambda a : a + 10
print(x(5))

Python Modules

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.

  • To create a module just save the code you want in a file with the file extension .py.
  • Now we can use the module we just created, by using the import statement.
Module Example
import platform
x = platform.system()
print(x)

Python PIP

PIP is a package manager for Python packages, or modules if you like.

  • A package contains all the files you need for a module.
  • Modules are Python code libraries you can include in your project.
PIP Example
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version

Python Dates

A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.

  • The datetime module has many methods to return information about the date object.
Date Example
import datetime
x = datetime.datetime.now()
print(x)

Python Math

Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.

  • Built-in Math Functions: min() and max(), abs(), pow().
  • The math module has a set of methods and constants.
Math Example
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x)
print(y)

Python RegEx

A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.

  • RegEx can be used to check if a string contains the specified search pattern.
  • Python has a built-in package called re, which can be used to work with Regular Expressions.
RegEx Example
import re
txt = "The rain in Spain"
x = re.search("^The.*Spain$", txt)

Python Arrays

Python does not have built-in support for Arrays, but Python Lists can be used instead.

  • Arrays are used to store multiple values in one single variable.
  • To work with arrays in Python you will have to import a library, like the NumPy library.
Array Example
cars = ["Ford", "Volvo", "BMW"]
print(cars[0])

Python Classes and Objects

Python is an object oriented programming language.

  • Almost everything in Python is an object, with its properties and methods.
  • A Class is like an object constructor, or a "blueprint" for creating objects.
  • The __init__() function is always executed when the class is being initiated.
Class Example
class MyClass:
  x = 5

p1 = MyClass()
print(p1.x)
Live Editor

Python Inheritance

Inheritance allows us to define a class that inherits all the methods and properties from another class.

  • Parent class: The class being inherited from, also called base class.
  • Child class: The class that inherits from another class, also called derived class.
Inheritance Example
class Person:
  def __init__(self, fname, lname):
    self.firstname = fname
    self.lastname = lname

class Student(Person):
  pass

Python File Handling

File handling is an important part of any web application.

  • The key function for working with files in Python is the open() function.
  • The open() function takes two parameters; filename, and mode.
  • Modes: "r" (Read), "a" (Append), "w" (Write), "x" (Create).
File Example
f = open("demofile.txt", "r")
print(f.read())

Python Try...Except

When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

  • The try block lets you test a block of code for errors.
  • The except block lets you handle the error.
  • The else block lets you execute code when there is no error.
  • The finally block lets you execute code, regardless of the result of the try- and except blocks.
Exception Example
try:
  print(x)
except:
  print("An exception occurred")

Python User Input

Python allows for user input. That means we are able to ask the user for input.

  • Python 3.6 uses the input() method.
  • Python 2.7 uses the raw_input() method.
Input Example
username = input("Enter username:")
print("Username is: " + username)

Python String Formatting

To make sure a string will display as expected, we can format the result with the format() method or using f-strings.

  • F-strings (Python 3.6+): f"Hello {name}"
  • The format() method allows you to format selected parts of a string.
Formatting Example
price = 49
txt = f"The price is {price} dollars"
print(txt)

🚀 Python Real World Projects

Apply your skills with these project ideas.

  • Beginner: Unit Converter (KM to Miles).
  • Intermediate: Quiz Master (Multiple choice game).
  • Advanced: Web Scraper (Extract headlines from news sites).

🎯 Python Mini Task

Goal: Temperature Converter.

  1. Create a variable celsius = 25.
  2. Convert it to Fahrenheit using formula: (celsius * 9/5) + 32.
  3. Print the result: "25 degrees Celsius is XX degrees Fahrenheit".

Python JSON

JSON is a syntax for storing and exchanging data. JSON is text, written with JavaScript object notation.

  • Python has a built-in package called json, which can be used to work with JSON data.
  • json.loads(): Parse JSON (convert from JSON to Python).
  • json.dumps(): Convert from Python to JSON.
JSON Example
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
print(y["age"])

Python Iterators

An iterator is an object that contains a countable number of values.

  • An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.
  • Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().
Iterator Example
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))

Python Polymorphism

The word "polymorphism" means "many forms", and in programming it refers to methods/functions/operators with the same name that can be executed on many objects or types.

  • Function Polymorphism: An example is the len() function, which can be used on different objects.
  • Class Polymorphism: Classes can have methods with the same name.
Polymorphism Example
class Car:
  def move(self):
    print("Drive!")

class Boat:
  def move(self):
    print("Sail!")

car1 = Car()
boat1 = Boat()
for x in (car1, boat1):
  x.move()

Python Scope

A variable is only available from inside the region it is created. This is called scope.

  • Local Scope: A variable created inside a function belongs to the local scope of that function.
  • Global Scope: A variable created in the main body of the Python code is a global variable and belongs to the global scope.
Scope Example
def myfunc():
  x = 300 # Local scope
  print(x)

myfunc()

Python Read Files

To open a file for reading it is enough to specify the name of the file.

  • By default the open() function returns a file object.
  • Use the read() method to read the content of the file.
  • Use readline() to read one line of the file.
Read Example
f = open("demofile.txt", "r")
print(f.read())

Python Write/Create Files

To write to an existing file, you must add a parameter to the open() function.

  • "a" - Append - will append to the end of the file.
  • "w" - Write - will overwrite any existing content.
Write Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

Python Delete Files

To delete a file, you must import the OS module, and run its os.remove() function.

  • To delete an entire folder, use the os.rmdir() method.
  • It is a good practice to check if the file exists before you try to delete it.
Delete Example
import os
if os.path.exists("demofile.txt"):
  os.remove("demofile.txt")
else:
  print("The file does not exist")

Python Quiz

Test your Python skills with our Quiz!

Python Exercises

We have gathered a variety of Python exercises (with answers) for each Python Chapter.

Python Summary

In this tutorial you have learned a lot about Python.

  • Basic Syntax & Variables
  • Looping & Conditionals
  • Functions & OOP
  • File Handling & RegEx

🎉 Congratulations!

You've completed the Python module.