Learn Python in Less Than a Week

Your comprehensive guide to learn Python from scratch to proficiency, build real programs and applications that can change your life, and unlock meaningful income and job opportunities.

If you’re looking for a fast and enjoyable way to learn programming with Python, this book is your gateway to mastering the essentials with ease. It includes real examples and applied diagrams to help you become a confident programmer. It features four powerful blueprints: from game development, to data analysis, task automation, and building web applications. Start your journey now and be part of the future of technology.

Book cover: Learn Python in Less Than a Week, authored by Ahmad Al Khatib

A quick look at the table of contents

  1. Introduction
  2. Download and install the book’s prerequisites
  3. Chapter 1: A guided tour of Python
  4. Chapter 2: Numbers and strings, with some basic operations
  5. Chapter 3: Lists and the for loop
  6. Preface for readers: Downloadable resources
  7. Chapter 4: The if conditional
  8. Chapter 5: Dictionaries, tuples, and sets
  9. Chapter 6: The conditional while loop
  10. Chapter 7: Functions
  11. Chapter 8: Classes
  12. Chapter 9: File handling and imports

View the full table of contents

  1. Introduction
  2. Download and install the book’s prerequisites
    1. 1- Download and install Python
    2. 2- Download and install PyCharm
      1. 2.1- A quick tour of PyCharm
        1. 2.1.i- What is PyCharm?
        2. 2.1.ii- The PyCharm interface
      2. 2.2- Download and install the packages/libraries required for the book’s blueprints
  3. Chapter -1- A guided tour of Python
    1. 1- The print() function
    2. 2- Variables and values
    3. 3- Methods: .title(), .lower(), and .upper()
    4. Chapter one exercise
  4. Chapter -2- Numbers and strings with some basic operations
    1. 1- The number type
    2. 2- Using the addition operator (+) between numbers and between strings
    3. 3- The int() and str() functions
    4. 4- Number types in Python and some basic arithmetic
    5. 5- Commands for working with strings
      1. 5.1- Using the comma ( , ) inside print() to combine strings and separate them with a space
      2. 5.2- Tab (\t) and newline (\n)
      3. 5.3- Defining a string with triple quotes """ """
      4. 5.4- Trimming whitespace at string edges: .strip(), .rstrip(), .lstrip()
      5. 5.5- Using the backslash (\) to escape special characters or split long code lines across multiple lines
    6. 6- Adding comments to code (#)
    7. Chapter two exercise
    8. Did you know about Minecraft?
    9. (Untitled)
  5. Chapter -3- Lists and the for loop
    1. 1- Introduction to lists
      1. 1.1- List element order and the element index
      2. 1.2- Editing lists
        1. 1.2.i- Adding items to a list
        2. 1.2.ii- Removing items from a list
      3. 1.3- Modifying a specific list item by index
      4. 1.4- Reordering list items
        1. 1.4.i- Sort a list ascending or descending using the .sort() method
        2. 1.4.ii- Create a copy of a list and sort it ascending or descending using the sorted() function
        3. 1.4.iii- Reverse the order of list items using the .reverse() method
        4. 1.4.iv- Sorting considerations
    2. 2- The for loop
    3. 3- The range() and list() functions
    4. 4- List dynamics in Python
    5. 5- Counting functions: len(), min(), max(), and sum()
    6. Did you know about WhatsApp?
    7. 6- Slicing a list
      1. 6.1- Slice notation
      2. 6.2- Copying lists using slice notation or the .copy() method
    8. 7- List comprehensions
    9. Chapter three exercise
  6. BONUS Preface for dear readers
    1. Installing and opening Jupyter
    2. Downloading and opening the book’s interactive file in Jupyter
  7. Chapter -4- The if conditional
    1. Did you know about the crafty employee “A.B.”?
    2. 1- if equals (==), and if not equals (!=)
    3. 1.1- Case-insensitive comparisons
    4. 2- if in, and if not in
    5. 3- if greater than (>) and if less than (<)
    6. 4- Building compound conditions with the and and or keywords
    7. 5- The if-elif-elif…-else chain
      1. 5.1- The if-else chain
      2. 5.2- The if-elif-else chain
    8. Chapter four exercise
    9. Did you know the Irish DPC’s fines on “Meta” exceeded 900 million euros?
  8. Chapter -5- Dictionaries, tuples, and sets
    1. 1- Tuple
    2. 2- Dictionary
      1. 2.1- Dictionary keys and values
      2. 2.2- Editing a dictionary
        1. 2.2.i- Adding key-value pairs to a dictionary
        2. 2.2.ii- Removing pairs from a dictionary with the del keyword
        3. 2.2.iii- Modifying a specific dictionary value by its key
      3. 2.3- The .keys(), .values(), and .items() methods
      4. 2.4- Looping over a dictionary with for
        1. 2.4.i- Loop over dictionary keys
        2. 2.4.ii- Loop over dictionary values
        3. 2.4.iii- Loop over dictionary items (key-value pairs)
    3. 3- Set
      1. 3.1- The tuple() and set() functions and the .add() and .update() methods
    4. Chapter five exercise
  9. Chapter -6- The conditional while loop
    1. 1- The input() function
      1. 1.1- Handling numeric input from input()
    2. 2- The while loop
      1. 2.1- Stopping a while loop
        1. 2.1.i- Stop a while loop using a sentinel condition (!=)
        2. 2.1.ii- Stop a while loop using a flag
        3. 2.1.iii- Stop a while loop using the break keyword
      2. 2.2- Skip a particular iteration using the continue keyword
      3. 2.3- Practical patterns for while
        1. 2.3.i- Using while to move items from one data container to another
        2. 2.3.ii- Using while to remove duplicate items from a list
    3. Chapter six exercise
  10. Chapter -7- Functions
    1. 1- Code for defining a function
      1. 1.1- Defining a function that accepts an argument
      2. 1.2- Defining a function that accepts multiple arguments
      3. 1.3- Setting a default value for a parameter
      4. 1.4- The return keyword
      5. 1.5- Putting a loop inside a function
      6. 1.6- Defining a function that accepts a variable number of positional arguments *args
      7. 1.7- Defining a function that accepts a variable number of keyword arguments **kwargs
    2. Chapter seven exercise
  11. Chapter -8- Classes
    1. 1- Code for defining a class
      1. 1.1- Class attributes and ways to modify them
        1. 1.1.i- Modify an attribute directly via dot notation
        2. 1.1.ii- Modify an attribute via a method
      2. 1.2- Setting default values for attributes
      3. 1.3- Defining a subclass from a parent class
    2. Chapter eight exercise
  12. Chapter -9- and the last in Part I: File handling and imports
    1. 1- File management in PyCharm
    2. 2- Import (import)
      1. 2.1- Importing a module
      2. 2.2- Importing a single element or a group of elements from a module
        1. 2.2.i- Importing an element under an alias
    3. 3- File handling in Python
      1. 3.1- Opening a file via the module
        1. 3.1.i- Open a file with open() and read its content with .read()
        2. 3.1.ii - Read the file line by line with .readlines()
      2. 3.2- Modifying a file via the module
        1. 3.2.i- Open a file in write mode open("name", "w") to clear it and add new content with .write()
        2. 3.2.ii- Open a file in append mode open("name", "a") to add new content with .write() without erasing previous content
      3. 3.3- Opening files stored outside the module’s folder
    4. 4- float(), .count(), .split(), .replace(), and the % operator
    5. Chapter nine exercise
  13. Conclusion

Read the introduction

The age of technology and artificial intelligence

Since the dawn of the 21st century, we’ve witnessed a massive digital surge ushering in a new technological era—an extension of the digital revolution that began in the mid-20th century with the first appearance of computers. This new era is defined by advanced intelligent applications that permeate and take root in our lives, in parallel with major advances in smart mobile devices that have become widely accessible, spreading across the globe like wildfire.

This new technological era—the era of smart devices and applications—has left a profound impact on our modern lifestyle, making it easier on many levels. Who among us doesn’t use WhatsApp and rely on it for many day-to-day tasks—whether chatting with family and friends, or for work and communicating with clients? The same goes for countless other apps that have become deeply embedded in our lives: from Google and the ease of accessing information, to Facebook and Twitter and the social networking revolution, to ChatGPT and ChatSonic and the AI boom—among many others that have grown in role and influence, becoming a daily necessity and a way of life that’s hard to let go of.

The importance of programming

The deep impact this era has had on our lives is evidence of the immense importance of the sciences that enabled these technologies—namely computer science. In this book, we’ll explore a primary—and enjoyable—branch of it: programming. To illustrate the broader importance and central role of programming today, consider this scenario: what would happen if—for some reason—all software systems in a given country suddenly failed?

Such a grim scenario would likely lead to government offices grinding to a halt, citizens being unable to process transactions, internet and wireless communications going down, banking operations stopping, as well as factories, companies, airplanes, and high-speed trains ceasing to operate, and so on. In short, it would be a catastrophic scenario akin to life coming to a standstill. In the digital age we live in, most operations fundamentally rely on computing and programming; programming has become a vital, essential need of our time.

The growing demand for programming

Because programming plays such a critical role, demand for it has surged. Programming-related jobs now top the list in the labor market. Learning this skill has become a golden ticket to employment—often with generous pay—whether in full-time roles at companies or as freelance work you can do from home.

If you want to seize this opportunity, multiply your income by learning an enjoyable, non-exhausting skill, and you’re wondering where and how to begin, this book will show you the way through the wonderful Python programming language.

What is Python?

So what is Python, and why did I choose it as the gateway to programming in this book?

Python is a widely popular programming language developed by the brilliant Dutch programmer Guido van Rossum, who named it after the famous comedy series “Monty Python’s Flying Circus.” The first version was released in 1991, and it grew rapidly to become one of the most popular and widely used programming languages in the world.

Why Python?

With hundreds of programming languages available, beginners often ask: “Which language should I choose?” My answer: “Choose Python without hesitation,” for many reasons, including:

  • Easy to learn, powerful in practice: Python is clean and beginner-friendly, yet also highly capable for complex, advanced domains. It’s used in cutting-edge research at organizations like NASA, for example.
  • High demand and strong pay: Python is among the most in-demand and widely used languages at major companies such as Google, Facebook, Instagram, YouTube, Amazon, and Uber. It also ranks among the highest-paying languages; for instance, according to Glassdoor, the average annual salary for a Python developer in the United States ranges from 80,000 to 120,000 USD.
  • Cross-platform and multi-domain: Python works across iOS, Android, Linux, macOS, Windows, and more. Its use cases span automation, statistics and data science, artificial intelligence, web development, game development, and beyond—among many other reasons to choose this remarkable language.

About this book

I present to you a comprehensive book covering most of Python’s essentials, written in a simple, approachable way for all ages, laid out in a semi-interactive style with code samples and their outputs, and enriched with detailed, student-like notes so you can learn on your own without needing extra lessons or courses. I structured it methodically into two parts:

  • A first part on the fundamentals: distributed over nine core chapters, each with practice exercises.
  • A second, applied part featuring four blueprints:
    1. A blueprint to build a video game from scratch with many features.
    2. A blueprint to build an interactive chart for currency price analysis that fetches data via an API.
    3. A blueprint to build an automation program that opens a specific website and executes defined tasks automatically.
    4. A blueprint to build a web app that generates text and images using artificial intelligence via an API.

The book concludes with a detailed index you can use as a reference glossary for this easy, powerful, and wonderful language.

Dedication

As it’s customary to end introductions with dedications, I dedicate this work to my loving, close-knit family in whose warmth I completed it; to my aunts Amal and Sahar; my uncle Dr. Anas Al Khatib, who supervised the linguistic review; my uncle Brigadier General Dr. Hani Al Khatib; my uncle Dr. Mohammad Al Khatib; my aunts and my entire family one by one; to my friend Professor Khaled Hanqir who encouraged me to finish this work; and to His Excellency the Minister Plenipotentiary at the Saudi Ministry of Foreign Affairs, the Ambassador of the Kingdom of Saudi Arabia to Lebanon, my friend Walid Al Bukhari.

I also dedicate this to a remarkable Arab leader—one of those who perhaps appear once every hundred years—combining sound leadership, clear vision, and creativity. He advanced scientific research with his outlook, bringing it to first place regionally and among the top globally, inspiring me to complete this book. I dedicate the book to His Royal Highness, Crown Prince and Prime Minister of Saudi Arabia, Prince Mohammed bin Salman bin Abdulaziz Al Saud—may God preserve him.

And to the one whose qualities I cannot fully describe, my refuge in hardship and ease, in gloom and joy—my loving mother, Samar Al Khatib.

Ahmad Al Khatib

Read chapter one

A guided tour of Python

• Note: To get the most out of this book and understand the material effectively, prepare PyCharm or a similar IDE so you can practice typing every code sample and run it yourself.

1- The function print()

We mentioned in the introduction that Python stands out for its simplicity. In Python, we can print—i.e., display—specific content on the screen, whether text, numbers, or symbols, simply by using one of the commands known as functions, namely print(), where we place the content to be printed between its parentheses.

A simple example: if we enter the following code in the IDE (such as PyCharm) code editor:

print("I wrote my first code!")

Then run this code with the run button we pointed out earlier in PyCharm’s top bar, it will print the content placed between the parentheses of print() to the screen, showing:

I wrote my first code!

What this code means is that we’re instructing Python to print specific content on the screen using print(). We put that content between its parentheses and wrapped it in double quotes "" to indicate it’s a text value—strings in Python are delimited by quotes and are known as strings.

  • Note 1: We can also use single quotes ' ' instead of double quotes to define a string in Python, and this becomes necessary in some cases to avoid an error.

Here are some examples:

  • Example 1: Using single quotes in the following code:
    Print('I started programming!')
    plays the same role as double quotes, defining the string between them—that is, telling Python the content between those single quotes is textual.

Running this code prints the following on the screen:

I started programming!
  • Example 2: If the string you want to use already contains double quotes, like:
    He says: "Hello mom!"

then it becomes necessary to define the string with single quotes to avoid an error, as shown in the figure below:

Figure 1.1 — Using single quotes to define a string to avoid an error.
  • Example: Likewise, if the string already contains a single quote, do not use single quotes to define the string; use double quotes instead to avoid an error, as shown below:
Figure 1.2 — Using double quotes to define a string to avoid an error.

2- Variables and values

Storing information in programs for various purposes is one of the core foundations of programming.

In Python, we can store specific information under specific names and retrieve it whenever we want using the name under which it was stored.

The stored piece of information is technically called a value, and the name that stores it is called a variable. For example:

country_name = "Egypt"

In the code line above, we stored the value "Egypt" in the variable country_name. If we then print this variable with print(), as in the following line:

print(country_name)

it prints the value stored in the variable country_name—not the variable name itself. The output is: Egypt.

  • Note 2.1: If we print the name "country_name" wrapped in quotes, as in the following line, Python treats it as a string—not a variable—and prints the literal name:
    print("country_name")
    → country_name
Figure 1.3 — Variables and values.
  • Note 2.2: If a variable name consists of two or more words, do not separate them with a space (e.g., country name), but instead use an underscore (_) like country_name, because spaces will cause an error:
    country name = "KSA" → error
    Also, as an extra guideline, you can include numbers in a variable name (e.g., country1_name_1), provided it does not start with a number, as that will cause an error:
    1country_name = "KSA" → error
  • Note 2.3: If a variable name is reused in multiple lines of code to store different values, printing that variable will display the most recent value assigned to it. For example:
    1. name = 'Fahed'
    2. name = 'Hessa'
    3. print(name)

    In line 1: the value 'Fahed' was stored in the variable name.

    In line 2: the value 'Hessa' was stored in another variable also called name.

    As a result, printing name in line 3 outputs the last stored value:

    Hessa
  • Quick review: So far, we’ve learned how to define strings in Python using double or single quotes, print text to the screen using print(), and store a value in a variable.

3- Methods: .title(), .lower(), and .upper()

Python also contains another group of commands known as methods. Don’t worry too much now about the specific difference between functions and methods—we will cover that in detail later.

From now on, for brevity, we’ll show the result of running code in blue highlight:

1. drink = "water"
2. print(drink)
water
3. print(drink.upper())
WATER

In line 1: we stored the value 'water' in the variable drink. Printing it in line 2 displayed the original value.

In line 3: printing drink with the .upper() method converted its letters to uppercase, resulting in WATER.

These intuitively named commands are part of Python’s appeal—upper literally means “to make upper case,” and print means “print.”

Conversely, you can use .lower() to convert text to lowercase—lower means “to make lower case.”

These methods don’t have to be used only inside print(). For example:

1. name_1 = "MOHAMMED"
2. name_2 = name_1.lower()
3. print(name_2)
mohammed

Here, .lower() turned 'MOHAMMED' into lowercase 'mohammed' and stored it in name_2.

Another formatting style, common for names and book titles, is capitalizing the first letter of each word. In Python, .title() does this.

Example:

1. participants = "jOUjoU samiR, SAlma ZahrAni, TaRek BeiRuti"
2. print(participants.title())
Joujou Samir, Salma Zahrani, Tarek Beiruti

As shown, .title() applied to participants in line 2 formatted the names correctly.

• Reminder: if you face issues as a beginner following this book, feel free to contact me through my social accounts listed at the bottom of the page to ask questions.

Chapter one exercise

This first exercise is very simple: unleash your imagination to write a code block of at least ten lines—perhaps printing your name and those of family or friends in different letter cases—using the following elements:

= " " ' ' print() .lower() .upper() .title()

What if you could learn Python programming and start creating your own programs in less than a week?

In this practical book, the author takes you on an enjoyable journey to master Python from scratch, with clear explanations, practical exercises, and real examples. You’ll learn programming fundamentals and how to create diverse applications—games, data analysis tools, task automation, and AI-powered web apps. Whether you’re a complete beginner or a developer expanding your skills, this book is your all‑in‑one guide to mastering Python and opening doors to higher income and standout opportunities in tech.

What does "Learn Python in Less Than a Week" offer to develop your skills and yourself?

  • Build a solid foundation for the future: This book isn’t just about one language—it’s an investment in yourself, giving you the fundamentals of computer science to specialize later in any programming field.
  • Think like a pro: Develop logical thinking and problem‑solving skills, the core traits of a successful programmer.
  • Create real, practical applications: Learn hands‑on how to build your own programs and apps from scratch to improve daily life and boost productivity.
  • Tap into advanced, profitable fields: Discover how to use Python in AI, data analysis, and automation—greatly increasing your career potential.
Author photo: Ahmad Al Khatib

About the author

Ahmad Al Khatib is a Lebanese technologist and programmer passionate about artificial intelligence, dedicating his expertise to making modern technology accessible to everyone—especially beginners. He holds specialized certifications in multiple tech fields and authors books that simplify programming and digital development concepts in a clear, engaging style. In his latest work, “Learn Python in Less Than a Week,” Ahmad lays out a practical, methodical roadmap for mastering Python efficiently. Outside writing and coding, he follows Middle East startup trends, blogs about tech and politics, and stays active in his online community. For exclusive lessons, updates on new releases, and deep insights into the world of technology, you’re invited to join his growing network.

Ready to boost your CV and career by learning Python in less than a week?

Don’t miss the chance to easily master the most in‑demand programming language in the job market. Get this book now to double your earning potential and advance your career.

Get your copy now