Unit 2 Python Basics
1. The Python Interpreter
The Python interpreter is a program that reads and executes Python code. Unlike compiled
languages (like C++ or Java) which convert the entire code into machine language at once,
Python interprets code line-by-line.
How it works:
1. Source Code: You write instructions in a file (e.g., [Link]) or type them directly.
2. Bytecode Compilation: The interpreter first compiles the source code into an intermediate
form called "bytecode" (low-level, platform-independent).
3. Virtual Machine (PVM): The Python Virtual Machine reads this bytecode and executes the
corresponding machine instructions on the computer's processor.
Key Features:
• Portability: The same Python code can run on Windows, Mac, or Linux because the
interpreter handles the translation for the specific machine.
• Immediate Feedback: Because it processes line-by-line, errors are reported immediately
when encountered.
2. Interactive Mode vs. Script Mode
Python works in two primary modes. Understanding the difference is crucial for beginners.
A. Interactive Mode
In this mode, you type a Python command, and the interpreter immediately executes it and
displays the result. It is also known as the REPL (Read-Eval-Print Loop).
• How to access: Open your terminal or command prompt and type python. You will see the
prompt >>>.
• Use Cases: Testing small snippets of code, doing quick mathematical calculations,
debugging.
• Example:
Python
>>> 5 + 10
15
>>> print("Hello")
Hello
(Note: The result is lost once you close the window. You cannot save code here.)
B. Script Mode
In script mode, you write the entire program in a text file with a .py extension (e.g.,
[Link]) and then ask the interpreter to execute the file.
• How to use: Write code in an editor, save it, and run python [Link].
• Use Cases: Writing actual applications, long programs, and code that needs to be saved and
reused.
Comparison Table:
Feature Interactive Mode Script Mode
Prompt Shows >>> No prompt shown
Execution Line-by-line immediate Executes whole file
Saving Code is lost on exit Code is saved in .py file
Purpose Experimentation Application Development
3. Values and Types
A Value is one of the basic things a program works with, like a letter or a number. A Type
defines a set of values and the operations that can be performed on them.
• Concept: The number 2 is a value. Its type is integer. The text "Hello" is a value. Its type
is string.
• Checking Type: Python provides a built-in function type() to check the category of any
value.
Python
>>> type(10)
<class 'int'>
4. Standard Data Types
Python has several built-in types. The most fundamental ones for this unit are:
A. Integers (int)
Whole numbers without a fractional part. They can be positive, negative, or zero.
• Examples: 10, -5, 0, 9999
• Operations: Supports standard math ($+$, $-$, $*$, $/$).
• Note: In Python 3, integers have unlimited precision (they can be as large as your memory
allows).
B. Floating-Point Numbers (float)
Numbers that have a decimal point or use scientific notation.
• Examples: 3.14, -0.01, 2.0, 1.5e2 (which means $1.5 \times 10^2$).
• Note: Even if a number looks whole (like 2.0), the presence of the decimal point makes it a
float.
C. Boolean (bool)
Represents truth values. There are only two possible boolean values.
• Values: True, False (Note the capitalization).
• Usage: Used extensively in conditional logic (control flow) and loops.
Python
>>> 5 > 3
True
D. Strings (str)
A sequence of characters used to represent text.
• Syntax: Enclosed in single quotes ('...') or double quotes ("...").
• Examples: "Hello World", 'Python', "123" (this is a string, not a number).
• Operations:
o Concatenation (+): Joins strings ("High" + "Five" $\rightarrow$ "HighFive").
o Repetition (*): Repeats string ("Yo" * 2 $\rightarrow$ "YoYo").
E. Lists (list)
A versatile, ordered sequence of items. It is one of the most used data types in Python.
• Syntax: Enclosed in square brackets [], with items separated by commas.
• Characteristics:
o Mutable: You can change items after the list is created.
o Mixed Types: A list can contain integers, strings, and floats all together.
• Example:
Python
my_list = [10, "apple", 3.14]
print(my_list[0]) # Output: 10
Summary Table of Types
Type Name Keyword Example Description
Integer int 42 Whole numbers
Float float 3.14159 Decimal numbers
Boolean bool True Logic values
String str "Hello" Text characters
List list [1, 2, "a"] Ordered collection
What is a Variable?
In Python, a variable is a name that refers to a value. Unlike some other programming
languages (like C or Java) where a variable is thought of as a "container" that holds data, in
Python, a variable is more like a label or a tag attached to a specific object in memory.
• Assignment Operator (=): We use the equal sign to create a variable or assign a
value to it. It does not mean "mathematical equality"; it means "assign the value on
the right to the name on the left."
message = "Hello, World!"
n = 17
pi = 3.14159
• message is a variable referring to a string.
• n is a variable referring to an integer.
• pi is a variable referring to a float.
Rules for naming variables in Python:
• Allowed Characters: Must only contain letters (a-z, A-Z), numbers (0-9), and underscores
( _ ).
• Starting Character: Must start with a letter or an underscore. It cannot start with a
number.
• Case Sensitivity: Names are case-sensitive (age, Age, and AGE are three different variables).
• Reserved Keywords: Cannot use Python's built-in keywords (e.g., if, else, while, def) as
variable names.
• No Special Symbols: Symbols like @, $, %, !, or spaces are strictly prohibited.
• Length: There is no technical limit on the length of a variable name, but it should be
practical.
Quick Reference: Valid vs. Invalid
Valid Invalid Reason
user_1 1_user Starts with a number
_temp user-1 Contains a hyphen
totalSum total sum Contains a space
my_var class Reserved keyword