Docsity

Python Fundamentals For Artificial intelligence, Slides of Functional Programming

Toggle sidebar
bg1
🩻
Python
Fundamentals
Topic
1:
Python
Basics
Introduction
Welcome
to
your
very
first
step
toward
becoming
a
Python
Fundamentals
Master
.
Before
you
write
a
single
line
of
code
,
you
need
to
understand
what
programming
actually
is
,
what
Python
is
,
and
why
the
entire
tech
industry
—
from
Google
to
NASA
to
your
favorite
mobile
app
—
relies
on
it
.
This
chapter
assumes
you
have
never
written
a
program
in
your
life
.
That
is
completely
fine
.
We
will
start
from
zero
and
build
your
understanding
brick
by
brick
,
the
same
way
a
house
is
built
—
foundation
first
,
walls
later
,
roof
last
.
By
the
end
of
this
chapter
,
you
will
be
able
to
explain
to
anyone
—
confidently
and
correctly
—
what
programming
is
,
what
Python
is
,
how
Python
code
actually
runs
on
a
computer
,
and
why
Python
is
considered
one
of
the
best
languages
to
learn
first
.
2.
Why
This
Topic
Is
Important
Python Fundamentals
1
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Python Fundamentals For Artificial intelligence and more Slides Functional Programming in PDF only on Docsity!

Python Fundamentals

Topic 1: Python

Basics Introduction

Welcome to your very first step toward becoming a Python Fundamentals Master. Before you write a single line of code, you need to understand what programming actually is, what Python is, and why the entire tech industry — from Google to NASA to your favorite mobile app — relies on it. This chapter assumes you have never written a program in your life. That is completely fine. We will start from zero and build your understanding brick by brick, the same way a house is built — foundation first, walls later, roof last. By the end of this chapter, you will be able to explain to anyone — confidently and correctly — what programming is, what Python is, how Python code actually runs on a computer, and why Python is considered one of the best languages to learn first.

2. Why This Topic Is Important

You might be tempted to skip this chapter and jump straight into "real code." Do not do that. Here's why this chapter matters: Every advanced Python topic (functions, OOP, file handling, etc.) sits on top of these basics. If your foundation is weak, advanced topics will feel confusing later — not because they are hard, but because your basics were shaky. Interviewers — even for senior roles — often ask "What is the difference between a compiler and an interpreter?" or "Why did you choose Python?" to test fundamental understanding, not just coding speed. Understanding how Python executes code helps you debug errors faster, because you'll know exactly what's happening behind the scenes when something goes wrong. Knowing Python's strengths and weaknesses helps you make smart decisions about when to use Python in real projects versus when another language might be better.

3. Real-World Analogy

Think of programming like giving instructions to a chef who has zero common sense but perfect obedience. If you tell the chef "make food," the chef will stare blankly — that instruction is too vague. But if you say: Take 2 eggs. Crack them into a bowl. Whisk for 30 seconds. Heat a pan on medium flame. Pour the eggs into the pan. Cook for 3 minutes. The chef can now follow these precise steps and produce an omelette every single time. A computer is exactly like this chef — extremely powerful, extremely fast, but it does only what you tell it to do, in the exact order you tell it. Programming is the art of writing that exact list of instructions.

Term Meaning High-Level Language Easy for humans to read/write; abstracted from hardware details Low-Level Language Closer to machine code; harder for humans, faster for machines General-Purpose Can be used for web apps, data science, automation, AI, games, etc. — not limited to one domain Interpreted Code is executed line-by-line by an interpreter, not compiled all at once beforehand

4.3 Why Python? (Why Learn Python First?)

Here are the real reasons beginners and professionals alike choose Python: Simple, readable syntax — Python code often reads almost like plain English. Huge community and libraries — Need to do data science? pandas. Need AI? PyTorch / TensorFlow. Need a website? Django / Flask. Almost anything you want to do, someone has already built a library for it. Cross-platform — Python code runs on Windows, macOS, and Linux without changes. In-demand in the job market — Python is consistently ranked among the top 3 most in-demand programming languages worldwide. Versatility — Web development, automation, data science, machine learning, cybersecurity, scripting, game development — Python touches almost every field in tech.

4.4 Features of Python

Feature Explanation Easy to Learn & Read Clean syntax, minimal punctuation, close to English Interpreted No separate compilation step; runs directly Dynamically Typed You don't need to declare variable types explicitly Free and Open Source Anyone can use, modify, and distribute it for free

Feature Explanation Extensive Standard Library Comes with built-in modules for math, file handling, dates, etc. ("batteries included") Portable Write once, run on any OS with a Python interpreter installed Object-Oriented Supports classes and objects (also supports procedural and functional styles) Extensible Can be integrated with C, C, and Java code Large Ecosystem Massive number of third-party packages via PyPI Python Package Index)

4.5 Advantages of Python

Beginner-friendly syntax reduces learning curve. Rapid development — you can build prototypes very quickly. Excellent for automation and scripting (saves hours of manual work). Strong support for data science, AI, and machine learning. Huge, active global community — if you get stuck, someone has likely already solved your problem online. Works well for both small scripts and massive enterprise applications Instagram, YouTube's backend components use Python).

4.6 Disadvantages of Python

Slower execution speed compared to compiled languages like C or Java, because it's interpreted line-by-line. Higher memory consumption due to Python's flexible, dynamic nature. Not ideal for mobile app development — Python is rarely used for building native mobile apps Swift/Kotlin dominate there). Global Interpreter Lock GIL — makes true multi-threaded CPU-bound performance tricky (an advanced topic you'll meet later). Runtime errors — because types aren't checked until the code runs, some errors that other languages would catch before running are only caught by Python while it's executing.

no compilation at all. The correct understanding is: Python compiles source code to bytecode, and then that bytecode is interpreted by the PVM at runtime. This is why Python is sometimes called a "compiled-interpreted hybrid" language.

4.9 What Is an Interpreter?

An interpreter is a program that reads and executes code line by line, converting each line into machine instructions on the fly, without needing to translate the whole program in advance. Real-world analogy: Imagine a live translator at a conference, translating a speaker's words into another language sentence-by-sentence, in real time, as the speaker talks. That's exactly how an interpreter works with code.

4.10 Compiler vs. Interpreter

This is one of the most commonly asked interview questions for beginners, so pay close attention. Aspect Compiler Interpreter Translation Style Translates the entire program at once before execution Translates and executes code line by line Speed of Execution Faster (translation done upfront) Generally slower (translation happens during execution) Error Detection Shows all errors at once, after scanning the whole program Stops at the first error it encounters, then halts Output Produces a separate executable file (e.g., .exe^ ) No separate executable file; runs directly from source Examples of Languages C, C, Rust Python (mostly), JavaScript, Ruby Real-World Analogy Translating an entire book into another language before handing it over Translating a conversation live, sentence by sentence Important Note: Python is often simplified as "an interpreted language," but as explained in section 4.8, it technically does a compilation step (to bytecode) internally. For beginner purposes and most interviews, saying "Python is an interpreted language" is an acceptable and expected answer — just remember the deeper truth for advanced discussions.

4.11 Python Execution Process (Step-by-Step)

Let's trace exactly what happens when you type this command in your terminal: python hello.py Assume hello.py contains: print("Hello, World!") Step-by-step execution: The Python interpreter program starts up. It opens and reads (^) hello.py from top to bottom. It compiles the source code into bytecode instructions (invisible to you, handled automatically). The Python Virtual Machine PVM) reads the bytecode and executes each instruction. When it reaches (^) print("Hello, World!") , the PVM calls the underlying system function to display text on your screen. Output Hello,^ World!^ appears in your terminal. The interpreter reaches the end of the file and the program terminates.

5. Syntax

Python doesn't have "syntax" in the sense of a single formula for this topic (that comes in Chapter 2 , but here is the most basic possible Python program, demonstrating the minimal syntax needed to run something: print("Hello, World!") Explanation: print(...) — a built-in Python function that displays whatever is inside the parentheses on the screen.

Example 2 Doing Simple Math print( 5 + 3 ) Example 3 Combining Text and Numbers print("The sum is:", 5 + 3 ) Example 4 Multiple Print Statements print("Line 1") print("Line 2") print("Line 3") Example 5 Using a Comment Explained fully in Chapter 2

This program prints a greeting

print("Hello, Python learner!")

8. Line-by-Line Explanation

Let's break down Example 3 completely, since it combines two ideas: print("The sum is:", 5 + 3 ) print( — begins a call to Python's built-in print function; everything inside the parentheses will be displayed. "The sum is:" — a string value (text) that will be shown exactly as written. , (^) — a comma inside print() (^) separates multiple items to display; Python automatically adds a space between them in the output. 5 + 3 — Python evaluates this expression before printing, calculating the numeric result 8. ) — closes the function call, telling Python "that's everything I want to print."

Output: (^) The sum is: 8

9. Visual Explanation

print("The sum is:", 5 + 3) │ │ │ └─> Evaluated FIRST by Python: 5 + 3 = 8 │ └─> Displayed literally as text Final Output: The sum is: 8 Think of (^) print() as a megaphone. Whatever you hand it, it announces to the screen. But before announcing, if you hand it a math expression, Python quietly does the math first, then hands the result to the megaphone.

10. Common Mistakes

Forgetting parentheses in print^ (common among people coming from Python 2 tutorials): print "Hello" # āŒ Incorrect in Python 3 — causes Syntax Errorprint("Hello") # āœ… Correct Confusing compiler and interpreter in interviews — many beginners say Python "has no compilation step at all," which is technically inaccurate (see section 4.8. Thinking Python and "the Python snake" are related to the name's origin — it's actually named after Monty Python's Flying Circus, a comedy show. Assuming Python is always the "best" language for everything — Python is excellent for many domains but not ideal for mobile apps or extremely performance-critical systems (e.g., real-time game engines, OS kernels). Not installing Python correctly / not adding it to PATH, leading to 'python' is not recognized errors in the terminal — this is a setup issue, not a coding issue, but it trips up nearly every beginner.

Is Python purely interpreted, or does it involve compilation too? What is bytecode in Python? What is the Python Virtual Machine PVM? Name five real-world applications where Python is commonly used. What are two disadvantages of using Python? Why might you not choose Python for a certain type of project? Explain the Python execution process from writing code to seeing output.

14. Summary

Programming means giving a computer precise, ordered instructions to perform a task. Python is a high-level, general-purpose, interpreted (technically compiled-to- bytecode-then-interpreted) programming language created by Guido van Rossum in 1991. Python is popular due to its readability, huge ecosystem, versatility, and beginner-friendliness. Python has both advantages (easy to learn, huge community) and disadvantages (slower execution, higher memory use). Python code goes through: source code → bytecode → PVM execution → output. A compiler translates the whole program at once; an interpreter translates and runs code line by line.

15. Practice Questions

MCQs Who created Python? a) Dennis Ritchie b) Guido van Rossum c) James Gosling d) Bjarne Stroustrup Python was first released in: a) 1985 b) 1991 c) 2000 d) 2010

Python is named after: a) A snake species b) A comedy show c) Its creator's dog d) A university Python is best described as: a) Low-level language b) High-level language c) Machine language d) Assembly language Which file extension stores Python bytecode? a) .py b) .pyc c) .exe d) .java Which of these is NOT a Python application area? a) Web development b) Data science c) Native iOS app development d) Automation What executes Python bytecode? a) CPU directly b) PVM c) Compiler d) Text editor Which is a disadvantage of Python? a) Hard to read b) Slower than C c) No community support d) Cannot do automation Compilers translate code: a) Line by line b) All at once c) Never d) Randomly Which language type is Python primarily classified as? a) Compiled only b) Interpreted c) Assembly d) Machine code Continue this pattern for remaining MCQs, Short Questions, Fill in the Blanks, True/False, and Output-Based Questions as you progress — a full 20-each bank for this topic is provided in the companion practice file 01_python_basics_practice.md to keep this chapter focused on teaching.)

16. Coding Exercises

Write a program that prints your name. Write a program that prints your name and age on separate lines. Write a program that prints the result of 12 + 8. Write a program that prints a short 3-line poem using three print() statements. Write a program that prints "Python"^ five times using five separate print() statements.

17. Debugging Questions

Find and fix the error in each snippet:

Syntax errors are the #1 source of frustration for absolute beginners. Understanding the rules upfront prevents hours of confusion later. Python's use of indentation instead of curly braces {}^ is unique compared to languages like Java, C, or JavaScript. If you don't understand this deeply, you will keep hitting IndentationError without knowing why. Naming conventions aren't just "style" — professional teams reject code in reviews that doesn't follow them, and interviewers notice sloppy naming immediately. Keywords are reserved — accidentally naming a variable list or class will cause bugs that are hard to spot without knowing this rule.

3. Real-World Analogy

Imagine writing a recipe card. If you write: Step 1: Boil water Add pasta Step 2: Wait 10 minutes A human reader might still understand this despite the odd indentation. But imagine a robot chef that treats indentation as meaning: it might read "Add pasta" as a sub-step belonging to Step 1 , and treat "Step 2" as a completely separate instruction because it's not indented. This is exactly how Python treats your code — indentation isn't decoration, it is the structure.

4. Detailed Explanation

4.1 Syntax Rules (Overview)

Python's syntax rules are famous for being clean and minimal: No semicolons required at the end of lines (though allowed, rarely used). No curly braces {} to define blocks — indentation does that job. No need to declare variable types.

Case-sensitive — (^) Name , (^) name , and (^) NAME are three different identifiers. Statements are typically written one per line.

4.2 Statements

A statement is a single instruction that Python can execute. Examples: x = 5 # Assignment statement print(x) # Expression statement (function call) if x > 0 : # Conditional statement print("Positive") Each line above is a complete instruction Python executes in order, top to bottom.

4.3 Indentation

This is Python's signature feature. Indentation (the whitespace at the start of a line) is used to define blocks of code — grouping statements that belong together, such as the body of a loop, function, or conditional. if True: print("This is inside the if block") # 4 spaces indent print("So is this") print("This is outside the if block") # No indent — not part of the if Rule: All statements within the same block must use the same amount of indentation. Standard convention is 4 spaces per indentation level (never tabs mixed with spaces — this causes errors). Language How Blocks Are Defined Python Indentation (whitespace) Java / C / JavaScript Curly^ braces^ {^ }

4.4 Blocks

A block (also called a "suite") is a group of statements that are treated as a single unit — typically the body of a loop, conditional, function, or class. A block starts

Best Practice: Prefer parentheses over backslashes — they're less error-prone (a stray space after \ breaks the line continuation silently).

4.7 Docstrings

A docstring is a special string used to document what a function, class, or module does. It's written using triple quotes and placed as the first statement inside the function/class. def add(a, b): """This function takes two numbers and returns their su m.""" return a + b Docstrings can be accessed programmatically using add.doc or the built-in help(add) function — this is how Python's own documentation system works.

4.8 Keywords

Keywords are reserved words that have special meaning in Python. You cannot use them as variable names, function names, or any other identifier. Python 3 has 35 keywords: False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield You can always verify the current list in your Python version using:

import keyword print(keyword.kwlist)

4.9 Identifiers

An identifier is the name you give to a variable, function, class, module, or any other object you create. Rules for valid identifiers: Can contain letters (a-z, AZ, digits 0 9 , and underscores ( _^ ). Cannot start with a digit ( 1name is invalid, name1 is valid). Cannot contain spaces or special symbols like @ , , % ,!. Cannot be a Python keyword ( class , def , if , etc.). Case-sensitive ( Total ≠ total ). age = 25 # āœ… valid _score = 90 # āœ… valid (starts with underscore) 2names = [] # āŒ invalid (starts with digit) my-name = "Al" # āŒ invalid (hyphen not allowed) class = "A" # āŒ invalid (keyword)

4.10 Naming Conventions

While Python allows flexible naming (within the rules above), the professional community follows PEP 8 Python's official style guide) conventions: Item Convention Example Variables lowercase_with_underscores (snake_case) total_price Functions lowercase_with_underscores calculate_total() Constants UPPERCASE_WITH_UNDERSCORES MAX_LIMIT Classes PascalCase CapitalizedWords) StudentRecord