Learn Python (Full Tutorial)

Python Introduction


What is Python?

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

It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

What can Python do?

  • Python can be used on a server to create web applications.
  • Python can be used alongside software to create workflows.
  • Python can connect to database systems. It can also read and modify files.
  • Python can be used to handle big data and perform complex mathematics.
  • Python can be used for rapid prototyping, or for production-ready software development.

Why Python?

  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.

Good to know

  • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.

Python Syntax compared to other programming languages

  • Python was designed for readability, and has some similarities to the English language with influence from mathematics.
  • Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
  • Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

Example

print(“Hello, World!”)


Python: Getting Started Guide

1. Installing Python

Most modern Windows, Mac, and Linux systems already come with Python pre-installed.
Let’s check if it’s available on your computer.

🔹 Check if Python is Installed

On Windows:

  1. Open the Start Menu and search for Python, or

  2. Open Command Prompt (cmd.exe) and type:

python --version

or, if that doesn’t work:

py --version

On macOS or Linux:

  1. Open the Terminal, then type:

python --version

or, depending on your setup:

python3 --version

If Python is installed, you’ll see an output like:

Python 3.12.1

If you don’t have Python installed, you can download it for free from the official website:
👉 https://www.python.org/downloads/


2. Your First Python Program

Python is an interpreted programming language, meaning you can write and run code directly without compiling.

🔹 Step 1: Create a Python File

Create a new file called helloworld.py using any text editor (e.g., Notepad, VS Code, Sublime, etc.).

Inside the file, write this simple line:

print("Hello, World!")

🔹 Step 2: Run Your Program

Open the Command Prompt (Windows) or Terminal (Mac/Linux), navigate to the folder where you saved the file, and type:

python helloworld.py

Output:

Hello, World!

Congratulations — you just wrote and executed your first Python program! 🎉


3. Using the Python Command Line (Interactive Mode)

Sometimes, you may want to test a few lines of code quickly without creating a file.
Python allows you to do this through its interactive command line (also called the REPL).

🔹 Open the Python REPL

On Windows:

python

or if that doesn’t work:

py

On macOS/Linux:

python3

You’ll see something like this:

Python 3.12.1 (tags/v3.12.1:...) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

Now, you can type Python commands directly:

>>> print("Hello, World!")
Hello, World!

🔹 Exit the Python REPL

When you’re done, type:

exit()

or press Ctrl + Z (Windows) or Ctrl + D (Mac/Linux) and hit Enter.


✅ Summary

Task Command
Check Python version python --version or python3 --version
Run a Python file python filename.py
Open Python interactive mode python or python3
Exit interactive mode exit()

Now you’re ready to start learning Python and writing your own programs. 🚀
Next steps: explore variables, data types, and control structures to build on this foundation.



Python Syntax Guide

1. Executing Python Syntax

As you learned earlier, Python code (called syntax) can be executed in two main ways:

🔹 Option 1: Run Directly in the Command Line

You can type and execute Python commands interactively:

>>> print("Hello, World!")
Hello, World!

This is useful for testing small pieces of code quickly.


🔹 Option 2: Run a Python File

You can also write your code in a file with the .py extension and run it using the command line.

Example:

C:\Users\YourName> python myfile.py

2. Python Indentation

In Python, indentation (the spaces at the beginning of a line) is not optional — it defines the structure of your code.
Unlike many other languages where indentation is just for readability, Python uses indentation to mark code blocks.

✅ Correct Example:

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

❌ Incorrect Example (Missing Indentation):

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

Output:

IndentationError: expected an indented block

🔹 How Many Spaces?

  • You can use any number of spaces, but you must be consistent.

  • The common convention (and the Python standard) is 4 spaces per indentation level.

Example:

if 5 > 2:
print("Five is greater than two!")
print("Still true!")

❌ Inconsistent Indentation Example:

if 5 > 2:
print("Five is greater than two!")
print("Still true!")

Output:

IndentationError: unindent does not match any outer indentation level

3. Python Variables

In Python, you don’t need to declare variables before using them.
A variable is created automatically the moment you assign a value to it.

✅ Example:

x = 5
y = "Hello, World!"

print(x)
print(y)

Output:

5
Hello, World!
  • You can store numbers, text, lists, booleans, and more.

  • Variable names are case-sensitive (myVar, MyVar, and MYVAR are all different).


4. Comments in Python

Comments are used to explain code and improve readability.
Python ignores comments during execution.

🔹 Single-Line Comments

Start a comment with a # symbol.
Everything after # on that line will be ignored.

Example:

# This is a comment
print("Hello, World!") # This comment is on the same line

🔹 Multi-Line Comments (Tip)

Python doesn’t have a specific multi-line comment syntax,
but you can use multiple # lines or a triple-quoted string for documentation-style comments.

Example:

# This is a comment
# written in
# multiple lines

"""
This is another way
to write multi-line comments.
It’s often used for docstrings.
"""


✅ Summary

Concept Description Example
Execute Code Run directly or from a .py file python myfile.py
Indentation Defines code blocks; use 4 spaces if 5 > 2: → indented code
Variables Created when assigned x = 5, y = "Hello"
Comments Explain code; ignored by Python # This is a comment

Tip:
Always keep your indentation consistent and add meaningful comments — it makes your code more readable, maintainable, and professional. 🧠💡



Python Comments

1. What Are Comments?

Comments are lines in your Python code that are ignored by the interpreter.
They are used to:

  • 🧩 Explain what your code does

  • 👀 Make your code more readable

  • 🧪 Temporarily disable (skip) code during testing

Comments do not affect the program’s execution — they’re just there for humans to read.


2. Creating a Comment

A single-line comment starts with the # (hash) symbol.
Everything after # on that line will be ignored by Python.

✅ Example:

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

Output:

Hello, World!

The line starting with # is ignored.


3. Inline Comments

You can also place a comment at the end of a line of code.
Python will ignore everything after the #.

✅ Example:

print("Hello, World!") # This prints a greeting message

Output:

Hello, World!

This is useful for quick explanations beside code statements.


4. Disabling Code with Comments

You can use comments to temporarily prevent a line of code from running,
which is helpful when debugging or testing.

✅ Example:

# print("Hello, World!")
print("Cheers, Mate!")

Output:

Cheers, Mate!

Here, the first print() statement is skipped because it’s commented out.


5. Multi-Line Comments

Python doesn’t have a dedicated syntax for multi-line comments like some other languages.
However, there are two common ways to write multi-line comments:


🔹 Option 1: Multiple # Lines (Preferred)

Simply start each line with a #.

# This is a comment
# written on
# more than one line
print("Hello, World!")

This method is clear and standard practice.


🔹 Option 2: Triple-Quoted Strings (Alternative)

You can also use a multi-line string (triple quotes ''' or """) that isn’t assigned to a variable.
Python will ignore it since it’s not being used.

"""
This is a comment
written in multiple lines
using triple quotes.
"""

print("Hello, World!")

Note:
While this works, triple-quoted strings are technically string literals, not real comments.
They’re often used for docstrings — special documentation strings that describe functions or modules.


✅ Summary

Type Syntax Example
Single-line # followed by text # This is a comment
Inline After code on the same line print("Hi") # Comment
Disabled code Prefix with # # print("Off")
Multi-line # each line or triple quotes """ multi-line """

💡 Tip:
Use comments wisely — write why the code does something, not just what it does.
Good comments make your code easier for others (and your future self!) to understand. 🧠



📦 Python Variables

1. What Are Variables?

In Python, variables are containers used to store data values.
Think of a variable as a label you attach to a piece of data — you can use that label later in your code.


2. Creating Variables

Python does not require explicit variable declarations.
A variable is created automatically as soon as you assign a value to it.

✅ Example:

x = 5
y = "John"

print(x)
print(y)

Output:

5
John

3. Dynamic Typing

Unlike many other programming languages, Python variables don’t need a fixed type.
You can assign a value of one type, then later assign a value of another type — and Python handles it dynamically.

✅ Example:

x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Output:

Sally

Python automatically updates the variable’s data type when the value changes.


4. Casting (Specifying the Type)

Sometimes, you may want to explicitly define the data type of a variable.
You can do this by casting with built-in type functions like str(), int(), or float().

✅ Example:

x = str(3) # x will be '3' (string)
y = int(3) # y will be 3 (integer)
z = float(3) # z will be 3.0 (float)

5. Getting the Type of a Variable

To check the data type of a variable, use the built-in type() function.

✅ Example:

x = 5
y = "John"

print(type(x))
print(type(y))

Output:

<class 'int'>
<class 'str'>

6. Single or Double Quotes for Strings

Python allows you to create string variables using either single (') or double (") quotes.
Both are valid and equivalent.

✅ Example:

x = "John"
y = 'John'

print(x)
print(y)

Output:

John
John

Tip: Use one style consistently throughout your code for readability.
Double quotes are often preferred when your string contains an apostrophe (e.g., "I'm happy").


7. Case Sensitivity

Python variable names are case-sensitive — this means a, A, and myVar are all different variables.

✅ Example:

a = 4
A = "Sally"

print(a)
print(A)

Output:

4
Sally

✅ Summary

Concept Description Example
Variable Creation Automatically created when assigned x = 5
Dynamic Typing Variables can change type x = 5x = "Hi"
Casting Explicitly set type x = float(3)
Check Type Use type() function type(x)
String Quotes Use ' ' or " " 'John' = "John"
Case Sensitivity Aa A = 1, a = 2

💡 Pro Tip:
Use descriptive variable names like age, price, or user_name instead of single letters.
It makes your code easier to understand and maintain. 🧠



🏷️ Python Variable Names

1. What Are Variable Names?

A variable name is the identifier you assign to store a value in Python.
You can use short names like x or y, or descriptive names like age, car_name, or total_volume.

Good variable names make your code easier to read and understand.
Let’s look at the rules and best practices for naming them.


2. Rules for Python Variable Names

When creating variable names in Python, follow these essential rules:

  1. Must start with a letter or underscore (_)

    • Examples: name, _score

  2. Cannot start with a number

    • Example: 2score ❌ (invalid)

  3. Can contain only letters, numbers, and underscores

    • Allowed characters: A–Z, a–z, 0–9, and _

  4. ⚠️ Case-sensitive

    • age, Age, and AGE are three different variables

  5. Cannot be a Python keyword (like if, for, class, True, etc.)


3. Examples of Valid Variable Names

These examples follow all the rules:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

All of these are valid and will work correctly.


4. Examples of Invalid Variable Names

These examples will cause syntax errors because they break naming rules:

2myvar = "John" # ❌ starts with a number
my-var = "John" # ❌ contains a hyphen (-)
my var = "John" # ❌ contains a space

Python will raise an error like:

SyntaxError: invalid syntax

5. 💡 Best Practices for Naming Variables

Follow these simple tips to write clean, readable Python code:

Rule Example Notes
Use descriptive names user_name, total_price Makes your code self-explanatory
Use lowercase_with_underscores car_speed Follows the PEP 8 naming convention
Avoid confusing letters Don’t use l, O, or I They can look like numbers
Be consistent Stick to one style Increases readability
Avoid keywords Don’t use for, if, True, etc. These are reserved by Python

6. 🔍 Checking Python Keywords

You can view all reserved Python keywords using the keyword module:

import keyword
print(keyword.kwlist)

Output (example):

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', ...]

✅ Summary

Rule Valid Example Invalid Example
Starts with letter/underscore _name, user1 1user
No special characters or spaces total_sum total-sum, total sum
Case-sensitive Namename
Not a Python keyword value for, if

💬 Tip:
Choose clear, descriptive variable names that reflect their purpose.
Good naming habits make your code easier to debug, share, and maintain. 🧠✨



🍊 Python Variables – Assign Multiple Values

In Python, you can assign values to multiple variables in a single line.
This makes your code cleaner and more efficient — especially when working with multiple related values.


1. Assign Multiple Values to Multiple Variables

Python allows you to assign different values to multiple variables at once.

✅ Example:

x, y, z = "Orange", "Banana", "Cherry"

print(x)
print(y)
print(z)

Output:

Orange
Banana
Cherry

Each variable on the left (x, y, z) is assigned the corresponding value from the right.

⚠️ Important:
The number of variables must match the number of values.
Otherwise, Python will raise a ValueError.

❌ Example (Mismatch):

x, y = "Apple", "Banana", "Cherry"

Error:

ValueError: too many values to unpack (expected 2)

2. Assign One Value to Multiple Variables

You can also assign the same value to multiple variables in one line.

✅ Example:

x = y = z = "Orange"

print(x)
print(y)
print(z)

Output:

Orange
Orange
Orange

All three variables now refer to the same value ("Orange").


3. Unpack a Collection

If you have a collection (like a list, tuple, or set) containing multiple values,
you can unpack them directly into separate variables.

This is called unpacking in Python.

✅ Example — Unpack a List:

fruits = ["apple", "banana", "cherry"]

x, y, z = fruits

print(x)
print(y)
print(z)

Output:

apple
banana
cherry

Each element in the list is assigned to a variable in the same order.


4. 🧩 Advanced Example — Partial Unpacking (Optional)

You can use * to unpack “the rest” of the collection into a list.

✅ Example:

fruits = ["apple", "banana", "cherry", "orange", "mango"]

x, y, *z = fruits

print(x)
print(y)
print(z)

Output:

apple
banana
['cherry', 'orange', 'mango']

The *z variable collects all remaining items as a list.


✅ Summary

Operation Description Example
Multiple values Assign different values x, y, z = 1, 2, 3
One value to all Assign same value x = y = z = "Hi"
Unpack collection Extract list/tuple values x, y, z = fruits
Partial unpacking Capture remaining items x, *y = fruits

💡 Tip:
Unpacking is especially useful when working with tuples, lists, or function returns.
It keeps your code clean, concise, and Pythonic 🐍✨



🖨️ Python – Output Variables

The print() function in Python is used to display output — including variables, text, and expressions.
Let’s explore how to use it effectively.


1. Printing a Single Variable

The simplest way to show a variable’s value is by passing it to the print() function.

✅ Example:

x = "Python is awesome"
print(x)

Output:

Python is awesome

2. Printing Multiple Variables

You can print multiple variables at once by separating them with commas.

✅ Example:

x = "Python"
y = "is"
z = "awesome"

print(x, y, z)

Output:

Python is awesome

Python automatically adds spaces between each item when using commas.


3. Using the + Operator

You can also concatenate (join) string variables using the + operator.

✅ Example:

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Output:

Python is awesome

💡 Note: Notice the spaces in "Python " and "is ".
Without them, the result would be Pythonisawesome.


4. The + Operator with Numbers

When used with numbers, the + operator performs addition.

✅ Example:

x = 5
y = 10
print(x + y)

Output:

15

5. Mixing Strings and Numbers

If you try to combine a string and a number with +, Python will raise an error because they’re different data types.

❌ Example:

x = 5
y = "John"
print(x + y)

Error:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

6. Best Practice — Use Commas

To print different data types together, separate them with commas.
Python will handle the conversion automatically.

✅ Example:

x = 5
y = "John"
print(x, y)

Output:

5 John

This is the recommended way to print multiple variables safely.


🌍 Python – Global Variables


1. What Are Global Variables?

Variables created outside of any function are called global variables.
They can be accessed from anywhere in your code — both inside and outside functions.

✅ Example:

x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

Output:

Python is awesome

2. Local vs Global Variables

If you create a variable inside a function, it becomes local to that function.
A local variable is separate from a global variable, even if they share the same name.

✅ Example:

x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

Output:

Python is fantastic
Python is awesome

Here:

  • Inside the function → x = "fantastic" (local variable)

  • Outside the function → x = "awesome" (global variable)


3. The global Keyword

By default, variables declared inside a function are local.
If you want to create or modify a global variable from inside a function, use the global keyword.


✅ Example 1: Creating a Global Variable Inside a Function

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Output:

Python is fantastic

✅ Example 2: Modifying a Global Variable Inside a Function

x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Output:

Python is fantastic

Here, the global keyword allows the function to update the global x variable.


🧩 Python – Variable Exercises

You’ve now learned how to create, use, and manage variables in Python.
Let’s test your understanding with a simple exercise!


🧠 Exercise:

👉 Create a variable named carname and assign the value Volvo to it.

# Your code here:
carname = "Volvo"

Expected Output:

Volvo

🎯 You’ve completed the Python Variables chapter!
You now understand how to:

  • Create and name variables

  • Assign multiple values

  • Output variables correctly

  • Work with global and local variables



Python Data Types


Built-in Data Types

In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str
Numeric Types: intfloatcomplex
Sequence Types: listtuplerange
Mapping Type: dict
Set Types: setfrozenset
Boolean Type: bool
Binary Types: bytesbytearraymemoryview
None Type: NoneType

Getting the Data Type

You can get the data type of any object by using the type() function:


Example

Print the data type of the variable x:

x = 5
print(type(x))

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type Num
x = “Hello World” str 1
x = 20 int 2
x = 20.5 float 3
x = 1j complex 4
x = [“apple”, “banana”, “cherry”] list 5
x = (“apple”, “banana”, “cherry”) tuple 6
x = range(6) range 7
x = {“name” : “John”, “age” : 36} dict 8
x = {“apple”, “banana”, “cherry”} set 9
x = frozenset({“apple”, “banana”, “cherry”}) frozenset 10
x = True bool 11
x = b”Hello” bytes 12
x = bytearray(5) bytearray 13
x = memoryview(bytes(5)) memoryview 14
x = None NoneType 15

Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example Data Type Num
x = str(“Hello World”) str 1
x = int(20) int 2
x = float(20.5) float 3
x = complex(1j) complex 4
x = list((“apple”, “banana”, “cherry”)) list 5
x = tuple((“apple”, “banana”, “cherry”)) tuple 6
x = range(6) range 7
x = dict(name=”John”, age=36) dict 8
x = set((“apple”, “banana”, “cherry”)) set 9
x = frozenset((“apple”, “banana”, “cherry”)) frozenset 10
x = bool(5) bool 11
x = bytes(5) bytes 12
x = bytearray(5) bytearray 13
x = memoryview(bytes(5)) memoryview 14

Test Yourself With Exercises


Exercise:

The following code example would print the data type of x, what data type would that be?

x = 5
print(type(x))



🔢 Python Numbers

In Python, there are three main numeric types:

Type Description Example
int Whole numbers (no decimals) 5, -23, 1000000
float Numbers with decimals or in scientific notation 3.14, -0.5, 2e3
complex Numbers with an imaginary part (j) 3+5j, 2j, -7j

🧮 Creating Numeric Variables

Python automatically assigns the correct numeric type when you give a value.

✅ Example:

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

print(type(x))
print(type(y))
print(type(z))

Output:

<class 'int'>
<class 'float'>
<class 'complex'>

🧱 Integers (int)

An integer is a whole number, positive or negative, without decimals.
Python integers have unlimited length.

✅ Example:

x = 1
y = 35656222554887711
z = -3255522

print(type(x))
print(type(y))
print(type(z))


🌊 Floats (float)

A float (floating-point number) is a number that contains a decimal point.

✅ Example:

x = 1.10
y = 1.0
z = -35.59

print(type(x))
print(type(y))
print(type(z))

Floats can also be written in scientific notation, using "e" or "E" to indicate powers of 10.

✅ Example:

x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))


🌀 Complex Numbers (complex)

Complex numbers have a real part and an imaginary part, written with j.

✅ Example:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))


🔄 Type Conversion

You can convert numbers between types using:

  • int() → to integer

  • float() → to float

  • complex() → to complex

✅ Example:

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

# Convert types:
a = float(x) # int → float
b = int(y) # float → int
c = complex(x) # int → complex

print(a)
print(b)
print(c)

print(type(a))
print(type(b))
print(type(c))

Note: You cannot convert a complex number into another numeric type.


🎲 Random Numbers

Python does not have a built-in random() function,
but the random module can generate random numbers.

✅ Example:

import random

print(random.randrange(1, 10))

This prints a random number between 1 and 9 (inclusive of 1, exclusive of 10).


🧠 Exercise:

Fill in the missing code to convert x into a floating point number.

x = 5
x = float(x)

🧱 Python Casting

Sometimes you may want to manually specify the type of a variable.
Python supports casting using constructor functions:

Function Description
int() Converts a number or string to an integer
float() Converts a number or string to a float
str() Converts a number or other data to a string

✅ Integers

x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

✅ Floats

x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2

✅ Strings

x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'

🧵 Python Strings

Strings in Python are sequences of characters, enclosed in single or double quotes.

✅ Example:

print("Hello")
print('Hello')

✍️ Assigning a String to a Variable

a = "Hello"
print(a)

📜 Multiline Strings

You can create multiline strings using triple quotes (""" or ''').

✅ Example 1 (Double Quotes):

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""

print(a)

✅ Example 2 (Single Quotes):

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''

print(a)

💡 The line breaks in the code are preserved in the output.


🔠 Strings Are Arrays

Strings act like arrays of characters —
you can access individual characters using square brackets [].

✅ Example:

a = "Hello, World!"
print(a[1])

Output:

e

🔁 Looping Through a String

You can loop through the characters of a string using a for loop.

✅ Example:

for x in "banana":
print(x)

📏 String Length

Use the len() function to get the number of characters in a string.

✅ Example:

a = "Hello, World!"
print(len(a))

Output:

13

🔍 Check if a Substring Exists

Use the keyword in to check if a substring exists in a string.

✅ Example:

txt = "The best things in life are free!"
print("free" in txt)

Output:

True

You can also use it in an if statement:

txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

🚫 Check if a Substring Does NOT Exist

Use not in to check if a substring is not present.

✅ Example:

txt = "The best things in life are free!"
print("expensive" not in txt)

Output:

True

Or with an if statement:

txt = "The best things in life are free!"
if "expensive" not in txt:
print("No, 'expensive' is NOT present.")


🧵 Python Strings — Deep Dive


✂️ Slicing Strings

You can extract parts of a string using slice syntax.
Specify the start and end indexes separated by a colon : — the slice includes the start index but excludes the end index.

✅ Example:

b = "Hello, World!"
print(b[2:5])

Output:

llo

💡 Indexing starts at 0, so b[2] is the third character.


🏁 Slice From the Start

Omit the start index to slice from the beginning:

b = "Hello, World!"
print(b[:5])

Output: Hello


🎯 Slice To the End

Omit the end index to slice to the end:

b = "Hello, World!"
print(b[2:])

Output: llo, World!


🔢 Negative Indexing

Use negative indexes to slice from the end of the string:

b = "Hello, World!"
print(b[-5:-2])

Output: orl

This selects characters from "o" (position -5) up to but not including "d" (position -2).


Modify Strings

Python provides many built-in string methods for cleaning, formatting, and transforming text.


🔠 Upper Case

a = "Hello, World!"
print(a.upper())

Output: HELLO, WORLD!


🔡 Lower Case

a = "Hello, World!"
print(a.lower())

Output: hello, world!


🚿 Remove Whitespace

Whitespace is the space before or after the text.
Use .strip() to remove it.

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

🔁 Replace Text

a = "Hello, World!"
print(a.replace("H", "J"))

Output: Jello, World!


✂️ Split Text

The .split() method divides a string into a list using a separator (default is space).

a = "Hello, World!"
print(a.split(","))

Output: ['Hello', ' World!']


🔗 String Concatenation

To combine two strings, use the + operator.

✅ Example 1:

a = "Hello"
b = "World"
c = a + b
print(c)

Output: HelloWorld


✅ Example 2 (With Space):

a = "Hello"
b = "World"
c = a + " " + b
print(c)

Output: Hello World


🧩 String Formatting

You can insert variables into strings using the .format() method.
This is the proper way to mix strings and numbers.

⚠️ Incorrect:

age = 36
txt = "My name is John, I am " + age # ❌ TypeError

✅ Correct:

age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

🧮 Multiple Placeholders:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

🔢 Indexed Placeholders:

You can specify the index of each placeholder:

quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

🧍‍♂️ Escape Characters

Some characters can’t appear directly in a string.
Use a backslash (\) to insert special characters.

⚠️ Example (Error):

txt = "We are the so-called "Vikings" from the north." # ❌

✅ Correct with Escape Character:

txt = "We are the so-called \"Vikings\" from the north."

Common Escape Sequences

Code Description
\' Single quote
\\ Backslash
\n New line
\r Carriage return
\t Tab
\b Backspace
\f Form feed
\ooo Octal value
\xhh Hexadecimal value

🧰 String Methods Overview

💡 All string methods return a new value — they do not change the original string.

Method Description
capitalize() Capitalizes the first letter
casefold() Converts string to lowercase
center() Returns a centered string
count() Counts occurrences of a substring
encode() Returns an encoded version
endswith() Checks if string ends with a value
expandtabs() Sets tab size
find() Finds position of substring
format() Formats values into string
index() Finds substring, raises error if not found
isalnum() Checks if all chars are alphanumeric
isalpha() Checks if all chars are letters
isdigit() Checks if all chars are digits
islower() Checks if all chars are lowercase
isspace() Checks if string is whitespace
istitle() Checks if string is titlecased
isupper() Checks if all chars are uppercase
join() Joins iterable into a string
ljust() Left-justifies text
lower() Converts to lowercase
replace() Replaces substring
rfind() Finds substring from right
rjust() Right-justifies text
split() Splits string into list
startswith() Checks prefix
strip() Removes whitespace
swapcase() Swaps case
title() Title-cases string
upper() Converts to uppercase
zfill() Pads with zeros

🧠 Exercise

Use the len() function to print the length of a string.

x = "Hello World"
print(len(x))

⚖️ Python Booleans

Booleans represent True or False values.


✅ Boolean Values

You can evaluate any expression — Python will return either True or False.

Example:

print(10 > 9)
print(10 == 9)
print(10 < 9)

Output:

True
False
False

🧠 Using Booleans in if Statements:

a = 200
b = 33

if b > a:
print("b is greater than a")
else:
print("b is not greater than a")


🧩 Evaluate Values with bool()

You can test any value using the bool() function.

✅ Examples:

print(bool("Hello"))
print(bool(15))

✅ Variables:

x = "Hello"
y = 15
print(bool(x))
print(bool(y))

✅ Most Values Are True

Non-empty values evaluate to True:

bool("abc")
bool(123)
bool(["apple", "banana", "cherry"])

🚫 Some Values Are False

The following evaluate to False:

bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({})

⚙️ Custom Class Example

If a class defines __len__() and returns 0, its objects evaluate to False.

class myclass():
def __len__(self):
return 0

myobj = myclass()
print(bool(myobj))


🔁 Functions Returning Booleans

You can make functions that return True or False.

def myFunction():
return True

print(myFunction())

Use the return value to control logic:

def myFunction():
return True

if myFunction():
print("YES!")
else:
print("NO!")


🧩 Built-in Boolean Function: isinstance()

Use it to check the type of an object:

x = 200
print(isinstance(x, int))


🧮 Python Operators

Operators perform actions on variables/values.

Arithmetic

+ - * / % ** //

Assignment

= += -= *= /= %= //= **= &= |= ^= >>= <<=

Comparison

== != > < >= <=

Logical

and or not

Identity

is is not

Membership

in not in

Bitwise

& | ^ ~ << >>

Precedence (high → low)

() > ** > +x -x ~x > * / // % > + - > << >> > & > ^ > | > comparisons > not > and > or

🧺 Python Lists

  • Ordered, changeable, allows duplicates

  • Create: mylist = ["apple", "banana", "cherry"] or list(("apple","banana"))

  • Length: len(mylist)

  • Access: mylist[0], mylist[-1], ranges mylist[1:3]

  • Check: "apple" in mylist

Modify

mylist[1] = "orange" # change
mylist[1:3] = ["kiwi","melon"] # change range
mylist.insert(2,"grape") # insert
mylist.append("pear") # append
mylist.extend(["mango","papaya"]) # extend

Remove

mylist.remove("apple")
mylist.pop(1) # or pop() last
del mylist[0]
mylist.clear()

Loop

for x in mylist: print(x)
for i in range(len(mylist)): print(mylist[i])
i=0
while i<len(mylist): print(mylist[i]); i+=1
[print(x) for x in mylist] # comprehension

Copy & Join

list2 = mylist.copy()
list3 = list(mylist)
joined = list1 + list2
list1.extend(list2)

🍎 Python Tuples

  • Ordered, unchangeable, allows duplicates

  • Create: mytuple = ("apple","banana","cherry") or tuple(("apple","banana"))

  • One item: ("apple",)

  • Access: mytuple[0], mytuple[-1], ranges mytuple[1:3]

  • Length: len(mytuple)

  • Mixed types allowed: ("abc", 34, True)



🍏 Python Tuples

  • Ordered, immutable, allows duplicates

  • Create: t = ("apple","banana") or tuple(("apple","banana"))

  • Single item: ("apple",)

  • Access: t[0], t[-1], slices: t[1:3], t[:3], t[2:], t[-4:-1]

  • Check: "apple" in t

Modify / Add

# convert to list
t = ("apple","banana","cherry")
l = list(t)
l[1] = "kiwi" # change
l.append("orange") # add
t = tuple(l)

# or add tuple
t += ("orange",)

Remove

l = list(t)
l.remove("apple")
t = tuple(l)
# delete entire tuple
del t

Join / Multiply

t3 = t1 + t2 # join
t2 = t1 * 2 # repeat

🍀 Python Sets

  • Unordered, mutable, no duplicates

  • Create: s = {"apple","banana"} or set(("apple","banana"))

  • Length: len(s)

  • Check: "apple" in s

Add / Update

s.add("orange") # single
s.update({"kiwi","pear"}) # multiple
s.update(["mango","plum"]) # from any iterable

Remove

s.remove("banana") # error if missing
s.discard("banana") # no error if missing
x = s.pop() # removes random
s.clear() # empty
del s # delete set

Set Operations

z = s1.union(s2) # new set with all items
s1.update(s2) # add items to s1
s1.intersection_update(s2) # keep common
z = s1.intersection(s2) # new set common
s1.symmetric_difference_update(s2)# keep non-common
z = s1.symmetric_difference(s2) # new set non-common

📖 Python Dictionaries

  • Ordered, mutable, key:value pairs, no duplicate keys

  • Create:

d = {"brand":"Ford","model":"Mustang","year":1964}
d = dict(name="John", age=36)
  • Access: d["brand"]

  • Modify / Add: d["year"]=2020

  • Length: len(d)

  • Values can be any type: string, int, list, boolean


⚡ Python If … Else

  • Comparison: == != < <= > >=

  • Structure:

if a > b:
print("a>b")
elif a == b:
print("a=b")
else:
print("a<b")
  • Single-line if / else:

print("A") if a > b else print("B")
print("A") if a > b else print("=") if a==b else print("B")
  • Logical operators:

if a>b and c>a: print("both true")
if a>b or a>c: print("one true")
if not a>b: print("a not > b")
  • Nested if:

if x>10:
print(">10")
if x>20: print(">20")
else: print("<=20")
  • Empty if: pass



Python Loops

While Loop

Executes while a condition is True.

i = 1
while i < 6:
print(i)
i += 1

Break: exits loop immediately.

if i == 3:
break

Continue: skips current iteration.

if i == 3:
continue

Else: runs when loop ends normally.

else:
print("Done")

For Loop

Iterates over a sequence (list, tuple, string, etc.).

for x in ["apple","banana","cherry"]:
print(x)

Range: loop specific number of times.

for x in range(2, 6, 2): # 2,4
print(x)

Break / Continue / Else work same as while.

Nested Loops:

for adj in ["red","big"]:
for fruit in ["apple","banana"]:
print(adj, fruit)

Functions

def my_function(name="John"):
print(name)
  • Arguments / Parameters: input values.

  • Default values: def f(x=5): ...

  • Arbitrary args: *args (tuple), **kwargs (dict).

  • Return values: return x*2

  • Pass: placeholder in empty function.

  • Lambda: one-line anonymous function.

x = lambda a, b: a + b

Recursion: function calls itself.

def rec(n):
return n + rec(n-1) if n>0 else 0

Arrays (Lists)

cars = ["Ford","Volvo","BMW"]
cars.append("Honda")
cars.pop(1)
cars.remove("Volvo")
len(cars)

Loop:

for c in cars:
print(c)

Classes & Objects

class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hi, I'm", self.name)

p1 = Person("John", 36)
p1.greet()

  • Modify / Delete properties: p1.age = 40, del p1.age

  • Delete object: del p1

  • Pass: placeholder for empty class


Inheritance

class Student(Person):
def __init__(self, name, age, year):
super().__init__(name, age)
self.year = year
def welcome(self):
print(f"Welcome {self.name}, class of {self.year}")

Iterators

mytuple = ("apple","banana")
myit = iter(mytuple)
print(next(myit)) # apple

Custom iterator:

class MyNumbers:
def __iter__(self):
self.a = 1
return self
def __next__(self):
if self.a <= 5:
x = self.a
self.a += 1
return x
else:
raise StopIteration

for n in MyNumbers():
print(n)


Scope

  • Local: inside function

  • Global: outside function

x = 300
def f():
global x
x = 200
f()
print(x) # 200


Python Modules

  • Module: A file (.py) with functions, variables, or classes you can reuse.

  • Create: Save code in mymodule.py:

def greeting(name):
print("Hello, " + name)

person1 = {"name":"John","age":36,"country":"Norway"}

  • Use Module:

import mymodule
mymodule.greeting("Jonathan")
print(mymodule.person1["age"])
  • Alias Module:

import mymodule as mx
print(mx.person1["age"])
  • Import Specific:

from mymodule import person1
print(person1["age"])
  • Built-in Module:

import platform
print(platform.system())
print(dir(platform)) # list all names

Datetime

import datetime
now = datetime.datetime.now()
print(now)
print(now.year, now.strftime("%A"))

d = datetime.datetime(2020,5,17)
print(d.strftime("%B"))


Math

import math
print(min(5,10,25), max(5,10,25))
print(abs(-7.25), pow(4,3))
print(math.sqrt(64), math.ceil(1.4), math.floor(1.4))
print(math.pi)

JSON

import json
# Python → JSON
x = {"name":"John","age":30}
y = json.dumps(x)
# JSON → Python
y = '{"name":"John","age":30}'
x = json.loads(y)
  • Formatting:

print(json.dumps(x, indent=4, sort_keys=True))

RegEx (re)

import re
txt = "The rain in Spain"
print(re.findall("ai", txt))
print(re.search(r"\bS\w+", txt).group())
print(re.split("\s", txt))
print(re.sub("\s","9", txt, 2))

PIP (Package Manager)

pip install camelcase # Install
pip uninstall camelcase # Remove
pip list # List packages
import camelcase
c = camelcase.CamelCase()
print(c.hump("hello world"))

Try / Except

try:
print(x)
except NameError:
print("x not defined")
else:
print("No error")
finally:
print("Done")
  • Raise Exception:

x = -1
if x < 0:
raise Exception("No numbers below zero")

User Input

username = input("Enter username: ")
print("Username is:", username)

String Formatting

price = 49
print("Price is {:.2f} dollars".format(price))

quantity, itemno = 3, 567
print("I want {0} pieces of item {1} for {2:.2f} dollars.".format(quantity, itemno, price))

print("I have a {car}, it is a {model}".format(car="Ford", model="Mustang"))