0% found this document useful (0 votes)
2 views15 pages

Unit 2 Python

The document explains the Python interpreter, which executes Python code in script and interactive modes. It covers debugging techniques, variable types, expressions, statements, tuple assignment, and operator precedence in Python. Each section provides examples and concise summaries of key concepts.

Uploaded by

srinijannat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Unit 2 Python

The document explains the Python interpreter, which executes Python code in script and interactive modes. It covers debugging techniques, variable types, expressions, statements, tuple assignment, and operator precedence in Python. Each section provides examples and concise summaries of key concepts.

Uploaded by

srinijannat
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

python interpreter and interactive mode

Python Interpreter
 The Python interpreter is the program that reads and executes Python code.
 When you write a Python script (.py file) and run it, the interpreter translates your code
into bytecode and executes it line by line.
 It makes Python a high-level, interpreted language (not compiled like C or Java).
There are two main ways to use the Python interpreter:
1. Script mode – running a .py file.
Example:
2. python [Link]
This runs the whole program at once.
3. Interactive mode – running Python commands one by one directly.

Interactive Mode
 Interactive mode lets you type Python commands and see the results immediately.
 It’s useful for quick testing, debugging, or learning Python.
How to enter interactive mode:
 Just open a terminal/command prompt and type:
 python
or in newer versions:
python3
 You’ll see the Python prompt:
 >>>
Example:
>>> 2 + 3
5
>>> print("Hello, World!")
Hello, World!
>>> x = 10
>>> x * 5
50
Each command is executed instantly without needing to write a full program.

✅ Summary:
 Python interpreter = the engine that runs Python code.
 Script mode = runs a full .py program.
 Interactive mode = lets you test code line by line using the >>> prompt.
python interpreter and interactive mode
ChatGPT said:
Let’s break this down step by step 👇

Python Interpreter
 The Python interpreter is the program that reads and executes Python code.
 When you write a Python script (.py file) and run it, the interpreter translates your code
into bytecode and executes it line by line.
 It makes Python a high-level, interpreted language (not compiled like C or Java).
There are two main ways to use the Python interpreter:
1. Script mode – running a .py file.
Example:
2. python [Link]
This runs the whole program at once.
3. Interactive mode – running Python commands one by one directly.

Interactive Mode
 Interactive mode lets you type Python commands and see the results immediately.
 It’s useful for quick testing, debugging, or learning Python.
How to enter interactive mode:
 Just open a terminal/command prompt and type:
 python
or in newer versions:
python3
 You’ll see the Python prompt:
 >>>
Example:
>>> 2 + 3
5
>>> print("Hello, World!")
Hello, World!
>>> x = 10
>>> x * 5
50
Each command is executed instantly without needing to write a full program.

✅ Summary:
 Python interpreter = the engine that runs Python code.
 Script mode = runs a full .py program.
 Interactive mode = lets you test code line by line using the >>> prompt.

debugging in python
🔎 What is Debugging?
Debugging is the process of finding and fixing errors (bugs) in your Python program. Python
provides several tools and techniques to help with this.

🛠 Ways to Debug in Python


1. Using Print Statements (Basic Debugging)
 The simplest way: insert print() statements to check values step by step.
x = 10
y = 0
print("Before division:", x, y)
result = x / y # error: division by zero
print("Result:", result)
Here, the print statement helps you see where the error happens.

2. Using assert
 The assert statement checks conditions while running code.
x = 5
assert x > 0, "x must be positive"
print("x is positive")
If the condition fails, Python raises an AssertionError.

3. Using Exception Handling (try...except)


 Catch and handle errors instead of letting the program crash.
try:
x = 10 / 0
except ZeroDivisionError as e:
print("Error:", e)

4. Using the Built-in Debugger (pdb)


 Python has a built-in debugger called pdb (Python Debugger).
 You can set breakpoints, step through code, and inspect variables.
Example:
import pdb

x = 10
y = 0

pdb.set_trace() # program stops here for debugging


result = x / y
print(result)
In the debugger, you can use commands:
 n → next line
 s → step into function
 c → continue execution
 q → quit debugger
 p variable → print variable value

5. Using IDE/Editor Debuggers


 Most editors (like PyCharm, VS Code, IDLE) have built-in debugging tools.
 Features: breakpoints, variable watch, step-by-step execution, call stack tracking.

✅ Summary
 Print statements → quick checks.
 assert → conditions must hold true.
 try...except → handle errors gracefully.
 pdb → step-by-step command-line debugging.
 IDE debuggers → powerful graphical debugging.
values and types : int,float, boolean, string, and list in
python
🔹 1. Integers (int)
 Whole numbers (positive, negative, or zero).
 No decimal point.
Example:
a = 10
b = -5
c = 0
print(a, type(a)) # 10 <class 'int'>

🔹 2. Floating Point Numbers (float)


 Numbers with decimal points or in scientific notation.
Example:
pi = 3.14
num = -2.5
exp = 1.2e3 # scientific notation (1200.0)
print(pi, type(pi)) # 3.14 <class 'float'>

🔹 3. Boolean (bool)
 Logical values: True or False.
 Often results from comparisons.
Example:
x = True
y = False
z = (10 > 5) # True
print(z, type(z)) # True <class 'bool'>

🔹 4. String (str)
 Sequence of characters inside quotes (' ' or " ").
 Supports indexing and slicing.
Example:
name = "Python"
greeting = 'Hello'
print(name, type(name)) # Python <class 'str'>
print(name[0]) # P (first character)
print(name[1:4]) # yth (slicing)

🔹 5. List (list)
 Ordered, mutable collection of items (can hold mixed types).
 Defined using square brackets [ ].
Example:
my_list = [10, 3.5, "hello", True]
print(my_list, type(my_list)) # [10, 3.5, 'hello', True] <class 'list'>

# Accessing elements
print(my_list[0]) # 10
print(my_list[2]) # hello

# Modifying list
my_list[1] = 7.2
print(my_list) # [10, 7.2, 'hello', True]
✅ Summary Table
Type Example Description
int 10, -5, 0 Whole numbers
float 3.14, -2.5, 1.2e3 Decimal numbers
bool True, False Logical values
str "Hello", 'Python' Sequence of characters (text)
list [1, 2.5, "hi"] Ordered, mutable collection of values
variables in python
🔹 What is a Variable?
 A variable is a name that refers to a value stored in memory.
 Think of it like a label attached to a box that holds data.
 In Python, variables are created when you assign a value using the = operator.

🔹 Rules for Variables in Python


1. Must start with a letter or underscore (_), not a number.
✅ name, _value
❌ 1name, @age
2. Can only contain letters, numbers, and underscores (A-Z, a-z, 0-9, _).
3. Case-sensitive → Age and age are different variables.
4. Cannot be a Python keyword (like for, while, class, if).

🔹 Examples
# Assigning values
x = 10 # integer
pi = 3.14 # float
name = "Alice" # string
is_valid = True # boolean
numbers = [1, 2, 3] # list

print(x, pi, name, is_valid, numbers)

🔹 Dynamic Typing
 Python is dynamically typed, meaning you don’t declare the type of variable—it is
decided at runtime.
a = 5 # int
a = "hello" # now a string
print(a) # hello

🔹 Multiple Assignment
Python lets you assign multiple variables at once:
x, y, z = 1, 2, 3
print(x, y, z) # 1 2 3

# Same value to multiple variables


a = b = c = 100
print(a, b, c) # 100 100 100

🔹 Variable Naming Styles


 snake_case → commonly used in Python (user_name, total_sum).
 camelCase → less common, used in other languages.
 UPPER_CASE → usually for constants (PI = 3.1416).

✅ Summary:
 Variables store values in memory.
 No type declaration needed (Python decides at runtime).
 Follow naming rules and use snake_case style.

expression in python
🔹 What is an Expression?
 An expression is a combination of values, variables, operators, and function calls that
Python evaluates to produce a result.
 Example:
 2 + 3 # expression → result is 5
 x * y # expression → depends on values of x and y
 len("Hi") # expression → result is 2
👉 If it produces a value, it’s an expression.

🔹 Types of Expressions in Python


1. Arithmetic Expressions
Use arithmetic operators (+, -, *, /, %, //, **).
a = 10
b = 3
print(a + b) # 13
print(a / b) # 3.333...
print(a // b) # 3 (floor division)
print(a ** b) # 1000 (power)

2. Relational (Comparison) Expressions


Produce a Boolean (True or False).
x = 5
y = 10
print(x > y) # False
print(x <= y) # True
print(x == 5) # True

3. Logical Expressions
Use and, or, not.
p = True
q = False
print(p and q) # False
print(p or q) # True
print(not p) # False
4. String Expressions
You can join or repeat strings.
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
print(s1 * 3) # HelloHelloHello

5. List Expressions
Work with list indexing and operations.
nums = [1, 2, 3]
print(nums[0] + nums[2]) # 4
print(nums * 2) # [1, 2, 3, 1, 2, 3]

🔹 Expression vs Statement
 Expression → produces a value.
 2 + 3 # expression (evaluates to 5)
 Statement → does something (like assignment, loop, function definition).
 x = 2 + 3 # statement (assignment)

✅ Summary:
 Expression = combination of values, variables, and operators → produces a result.
 Can be arithmetic, relational, logical, string, or list-based.
 Every expression has a value and a type.

statements in python
🔹 What is a Statement?
 A statement is an instruction that the Python interpreter can execute.
 It tells Python to do something (assign a value, run a loop, call a function, etc.).
 Unlike an expression (which produces a value), a statement performs an action.
Example:
x = 5 # assignment statement
print(x) # function call statement

🔹 Types of Statements in Python


1. Assignment Statement
Used to assign values to variables.
a = 10
b = 3.5
name = "Python"

2. Conditional Statement
Used for decision making (if, elif, else).
x = 15
if x > 10:
print("Greater than 10")
else:
print("10 or less")
3. Looping Statements
Used for repetition (for, while).
for i in range(3):
print("Hello") # prints 3 times

count = 0
while count < 3:
print("Hi")
count += 1

4. Break, Continue, Pass Statements


Special control flow statements.
for i in range(5):
if i == 2:
continue # skip 2
if i == 4:
break # stop loop
print(i)

def my_function():
pass # placeholder (does nothing)

5. Function Definition Statement


Defines a reusable block of code.
def greet():
print("Hello, World!")

6. Import Statement
Used to include external modules.
import math
print([Link](16)) # 4.0

7. Expression Statement
When an expression is written as a statement, Python evaluates it but doesn’t store the result
unless assigned.
2 + 3 # expression statement (evaluated but result unused)
print(2 + 3) # prints 5

🔹 Statement vs Expression
 Expression → produces a value.
 2 + 3 # result = 5
 Statement → performs an action.
 x = 2 + 3 # assigns 5 to x

✅ Summary:
 A statement is an instruction for Python to execute.
 Types: assignment, conditional, looping, break/continue/pass, function definition, import,
expression statements.
 Expressions → always produce a value, while statements → do something.
tuple assignment in python
🔹 What is Tuple Assignment?
 Tuple assignment means assigning multiple values to multiple variables at once using a
tuple (or tuple-like unpacking).
 Python allows unpacking values from a tuple (or list, or any iterable) directly into
variables.

🔹 Basic Example
# Simple tuple assignment
(x, y) = (10, 20)
print(x) # 10
print(y) # 20
Here, (10, 20) is a tuple, and Python "unpacks" it into x and y.

🔹 Multiple Values
(a, b, c) = (1, 2, 3)
print(a, b, c) # 1 2 3

🔹 Without Parentheses (works the same)


Parentheses are optional.
a, b, c = 4, 5, 6
print(a, b, c) # 4 5 6

🔹 Swapping Values (Pythonic way)


Tuple assignment makes swapping values easy without a temporary variable.
x, y = 10, 20
x, y = y, x
print(x, y) # 20 10

🔹 Nested Tuple Assignment


You can unpack nested tuples.
(a, (b, c)) = (1, (2, 3))
print(a) # 1
print(b) # 2
print(c) # 3

🔹 Using * for Extra Values


Python allows capturing remaining values with *.
a, *b = (1, 2, 3, 4, 5)
print(a) # 1
print(b) # [2, 3, 4, 5]

*a, b = (1, 2, 3, 4, 5)
print(a) # [1, 2, 3, 4]
print(b) # 5
✅ Summary
 Tuple assignment = unpacking values from a tuple into variables.
 Parentheses are optional: a, b = 1, 2.
 Useful for swapping, multiple assignments, and unpacking nested structures.
precedence of operatorsinpython
🔹 What is Operator Precedence?
 When an expression has multiple operators, Python decides the order of evaluation
based on operator precedence.
 Operators with higher precedence are evaluated first.
 If operators have the same precedence, Python uses associativity (left-to-right or right-
to-left).

🔹 Python Operator Precedence (Highest → Lowest)


Precedence Operators Description Associativity
1 () Parentheses (grouping) Left → Right
2 ** Exponentiation Right → Left
Unary plus, unary minus,
3 +x, -x, ~x Right → Left
bitwise NOT
Multiplication, division, floor
4 *, /, //, % Left → Right
division, modulus
5 +, - Addition, subtraction Left → Right
6 <<, >> Bitwise shift operators Left → Right
7 & Bitwise AND Left → Right
8 ^ Bitwise XOR Left → Right
9 | Bitwise OR Left → Right
==, !=, >, >=, <, <=, is, is Comparisons, membership,
10 not, in, not in Left → Right
identity
11 not Logical NOT Right → Left
12 and Logical AND Left → Right
13 or Logical OR Left → Right
=, +=, -=, *=, /=, //=, %=,
14 **=, &=, ^=, |=, >>=, <<= Assignment operators Right → Left

🔹 Examples
1. Parentheses first
result = (2 + 3) * 4
print(result) # 20
2. Exponentiation before multiplication
print(2 * 3 ** 2) # 18 (3**2 = 9, then 2*9)
3. Unary minus before multiplication
print(-3 * 2) # -6
4. Comparison before logical and
print(3 > 2 and 5 > 1) # True
5. Assignment is lowest precedence
x = 2 + 3 * 4
print(x) # 14

✅ Key Takeaways
 Parentheses () override everything.
 Exponentiation ** has higher precedence than multiplication/division.
 Comparison comes before logical operators (and, or, not).
 Assignment is the lowest precedence.
commands in python
🔹 Are there “commands” in Python?
 Strictly speaking, Python doesn’t have commands like SQL (SELECT, INSERT) or shell
(ls, cd).
 In Python, we have statements, functions, and expressions.
 But often people call basic Python statements/functions as “commands,” especially
when working in interactive mode (>>> prompt).

🔹 Commonly Used Python Commands


1. Printing and Input
print("Hello, World!") # display output
name = input("Enter your name: ") # take user input

2. Variable Assignment
x = 10
y = 3.5
msg = "Python"

3. Math Operations
print(5 + 3) # 8
print(10 - 4) # 6
print(2 * 3) # 6
print(10 / 3) # 3.333...
print(10 // 3) # 3 (floor division)
print(10 % 3) # 1 (remainder)
print(2 ** 3) # 8 (power)

4. Conditional Commands
x = 5
if x > 0:
print("Positive")
else:
print("Non-positive")

5. Looping Commands
# For loop
for i in range(3):
print("Hello")

# While loop
count = 0
while count < 3:
print("Hi")
count += 1

6. Function Definition
def greet(name):
print("Hello,", name)

greet("Alice")

7. List Commands
nums = [1, 2, 3]
[Link](4) # add element
[Link](2) # remove element
print(nums) # [1, 3, 4]

8. Importing Modules
import math
print([Link](16)) # 4.0

9. Exit Command
In interactive mode (Python shell), use:
exit()
# or
quit()

✅ Summary
 Python doesn’t have “commands” like shell or SQL — instead, it has statements,
expressions, and functions.
 Commonly used: print(), input(), math operations, conditionals (if), loops (for,
while), list operations, import, and exit().

illustate program exchange the values of two variables in


python
🔹 1. Using a Temporary Variable
# Swap using a temporary variable
a = 10
b = 20

print("Before swapping: a =", a, " b =", b)

temp = a
a = b
b = temp

print("After swapping: a =", a, " b =", b)


✅ Output:
Before swapping: a = 10 b = 20
After swapping: a = 20 b = 10

🔹 2. Without Using a Temporary Variable (Arithmetic)


a = 5
b = 7

print("Before swapping: a =", a, " b =", b)

a = a + b
b = a - b
a = a - b

print("After swapping: a =", a, " b =", b)


✅ Output:
Before swapping: a = 5 b = 7
After swapping: a = 7 b = 5

🔹 3. Pythonic Way (Tuple Assignment)


Python allows multiple assignment in one line.
a = 100
b = 200

print("Before swapping: a =", a, " b =", b)

a, b = b, a # tuple assignment

print("After swapping: a =", a, " b =", b)


✅ Output:
Before swapping: a = 100 b = 200
After swapping: a = 200 b = 100

✅ Summary
 Temporary variable → works in all languages.
 Arithmetic method → avoids extra variable but only works for numbers.
 Tuple assignment → simplest and most Pythonic.

circulate the values of n variables in python


🔹 Concept:
 Suppose you have a list: [a1, a2, a3, ..., an].
 Circulating means moving the first element to the end (or shifting all elements one
position to the left/right).
🔹 Python Program: Circulate Elements to the Left
# Input number of elements
n = int(input("Enter number of values: "))

# Create list
values = []
for i in range(n):
val = int(input("Enter value: "))
[Link](val)

print("Original list:", values)

# Circulate elements (left shift by 1)


first = [Link](0) # remove first element
[Link](first) # add it to the end

print("After circulation:", values)


Example Input/Output:
Enter number of values: 4
Enter value: 1
Enter value: 2
Enter value: 3
Enter value: 4
Original list: [1, 2, 3, 4]
After circulation: [2, 3, 4, 1]

🔹 Circulate Elements Multiple Times


If you want to circulate k times, you can use a loop:
k = int(input("Enter number of rotations: "))

for _ in range(k):
first = [Link](0)
[Link](first)

print("After", k, "circulations:", values)

🔹 Using Python Slicing (More Pythonic)


values = [1, 2, 3, 4, 5]
k = 2 # number of rotations

values = values[k:] + values[:k]


print(values) # [3, 4, 5, 1, 2]

✅ Summary:
 Circulation = moving elements in a list.
 pop + append → left shift by 1.
 Slicing → rotate multiple times efficiently.

If you want, I can also show a version to circulate elements to the right instead of left—it’s just
a small change. Do you want me to do that?
distance between two points in python
🔹 Formula for Distance Between Two Points
If we have two points:
(x1,y1)and(x2,y2)(x_1, y_1) \quad \text{and} \quad (x_2, y_2)(x1,y1)and(x2,y2)
The distance ddd is calculated using the Euclidean distance formula:
d=(x2−x1)2+(y2−y1)2d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}d=(x2−x1)2+(y2−y1)2

🔹 Python Program
import math # import math module for sqrt()

# Input coordinates
x1 = float(input("Enter X1: "))
y1 = float(input("Enter Y1: "))
x2 = float(input("Enter X2: "))
y2 = float(input("Enter Y2: "))

# Calculate distance
distance = [Link]((x2 - x1)**2 + (y2 - y1)**2)

# Display result
print("The distance between the two points is:", distance)

Example Run
Enter X1: 2
Enter Y1: 3
Enter X2: 5
Enter Y2: 7
The distance between the two points is: 5.0

🔹 Step by Step Explanation


1. Import math module → [Link]() is used for square root.
2. Take input for coordinates x1, y1, x2, y2.
3. Apply distance formula → (x2-x1)**2 + (y2-y1)**2, then take square root.
4. Print result.

You might also like