CTPS - Module - II Updated

Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

Computational Thinking And Problem-Solving

(B.Tech. 2024-28 CSE All Sections)

Module – II
Data, Expressions, & Statements

10/27/2024 1
Module II
‾ Introduction to Python - Python Interpreter, Modes of Python Interpreter,
‾ Values, and data types; Variables;
‾ Keywords; Identifiers; Statements and Expressions;
‾ Input and Output; Comments; Docstring;
‾ Lines and Indentation; Quotation in Python;
‾ Operators and Types, Operator Precedence.

10/27/2024 2
Why Python

▪ To pursue your career in 21st century


▪ You create your own games and apps
▪ Effortlessly Installed.
▪ It will improve your ‘Critical Thinking Skills’.
▪ You learn ‘Problem Solving Skills’

10/27/2024 3
Why Python

10/27/2024 4
• Python is an interpreted programming language which means
that you run each line of code immediately to get the results.
10/27/2024 5
10/27/2024 6
10/27/2024 7
Where Python is used

10/27/2024 8
10/27/2024 9
Features of Python programming

▪ Simple and Easy to Learn


▪ Freeware and Open Source
▪ Dynamically typed
▪ Object Oriented Programming and Procedure Oriented Programming
▪ Extensive Library
▪ Embedded
▪ Interpreted
▪ Portability
▪ Platform Independent

10/27/2024 10
Features of Python programming
1. Simple and Easy to Learn: Python is known for its readability and
simplicity. Its syntax emphasizes code readability and allows developers to
express concepts in fewer lines of code compared to languages like C++ or
Java. This simplicity makes Python an excellent choice for beginners.

2. Freeware and Open Source: Python is free to use and distribute. It has an
open-source community that continually contributes to its development,
making it accessible to anyone who wants to use or modify it. Python source
code is also available under the GNU General Public License (GPL).

3. Dynamically Typed: In Python, variable types are determined at runtime,


allowing for flexible coding. You don't need to explicitly declare variable
types, making it easier to write and maintain code.
10/27/2024 11
Features of Python programming
4. Object-Oriented Programming (OOP) and Procedure-Oriented
Programming (POP):
▪ Python supports both OOP and POP paradigms.
▪ Developers can choose to write code in an object-oriented or
procedural style, depending on their project requirements.
▪ OOP organizes data and functionality into objects and classes,
enhancing reusability and modularity.
▪ POP structures programs in terms of procedures (functions)
focusing on the sequence of actions that is it emphasizes a step-by-
step sequence of instructions.
10/27/2024 12
Features of Python programming
4. Object-Oriented Programming (OOP) and Procedure-Oriented
Programming (POP):
i) Object-Oriented Programming (OOP) Examples:
▪ Inventory Management System: Classes like Product, Category,
and Warehouse can encapsulate product details, manage stock levels, and
track inventory.
▪ Employee Management System: Create classes like Employee,
Manager, and HR with attributes like name, ID, salary, and
methods to calculate bonuses or leave management.
▪ E-commerce Website: Define classes like Customer, Order, and
Cart to handle user profiles, order processing, and shopping cart
functionalities.
10/27/2024 13
Features of Python programming

4. Object-Oriented Programming (OOP) and Procedure-Oriented


Programming (POP):
ii) Procedural-Oriented Programming (POP) Examples:
▪ Data Processing Script: Write functions to read_data(),
clean_data(), and write_output() for processing CSV or text
files in a sequential manner.
▪ Simple Calculator: Define functions like add(), subtract(),
multiply(), and divide(), which can be called based on user
input for a basic calculator program.
▪ System Monitoring Script: Use procedures to check CPU usage, memory
consumption, and disk space, and log these metrics at regular intervals
without needing classes or objects.
10/27/2024 14
Features of Python programming

5. Extensive Library: Python has a vast standard library that


includes modules and packages for a wide range of tasks, from
web development to data analysis. This extensive library saves
developers time and effort.

6. Embedded: Python can be embedded in other applications,


allowing developers to extend the functionality of existing
software by integrating Python scripts or modules.

10/27/2024 15
Features of Python programming
7. Interpreted: Python is an interpreted language, which means that code is
executed line by line by the Python interpreter. This makes it easier to debug and
test code as we can see results immediately.

8. Portability: Python code can be written and executed on various platforms,


including Windows, macOS, and Linux. This portability ensures that Python
applications can run seamlessly across different operating systems.

9. Platform Independent: Python's platform independence means that Python


code can run on any platform without modification, as long as the Python
interpreter for that platform is available. This attribute makes it an excellent
choice
10/27/2024
for cross-platform development. 16
Software Requirements for the Course

▪ Windows 10/11, MacOS 10.15, Linux VM


▪ Anaconda Framework (Jupyter/Spyder)
▪ Python
▪ Microsoft Office

10/27/2024 17
Software Requirements for the Course

I) Steps to download “Anaconda” Framework


▪ Go to Google and type “Anaconda”
▪ Download Windows /Mac 64 bit

II) For Python


▪ Visit the website “python.org”
▪ Download python 3.12.x (64 bit) for Windows/Mac

10/27/2024 18
Software Requirements for the Course
▪ Integrated Development Environments (IDEs): Many integrated
development environments like PyCharm, Visual Studio Code, and IDLE
come with built-in Python interpreters. These IDEs provide a more user-
friendly and feature-rich environment for writing, debugging, and
executing Python code.

▪ Jupyter Notebooks (Recommended): Jupyter Notebooks provide an


interactive environment for Python code. They allow you to create and
run code cells interactively, making them particularly useful for data
analysis and scientific computing.
▪ Script Execution: We can create Python script files with the ".py"
extension containing your Python code and then run them using the
Python interpreter. This is the typical way to execute larger Python
programs or scripts.
10/27/2024 19
10/27/2024 20
10/27/2024 21
10/27/2024 22
Python Interpreter
▪ The Python interpreter is a crucial component of the Python programming
environment that executes Python code. A Python interpreter is a software
program or tool that allows to execute Python code.

▪ It translates high-level Python code into machine-readable instructions,


enabling
10/27/2024
the computer to perform the specified tasks. 23
How the Python Interpreter Works

10/27/2024 24
Compiler vs Interpreter

10/27/2024 25
Compiler vs Interpreter

Important Note:
Do you need a compiler at the back of the interpreter for Python?
▪ No, Python does not require a separate compiler behind the interpreter
because Python is an interpreted language, not a compiled one in the
traditional sense.
▪ However, Python's process involves a combination of interpretation
and compilation under the hood.

10/27/2024 26
Compiler vs Interpreter
Important Note:
Do you need a compiler at the back of the interpreter for Python?
In simple terms:
How Python Works:
1) Source Code to Bytecode Compilation: When you write Python code (in
.py files), the Python interpreter first compiles the code into an
intermediate form called bytecode (files ending with .pyc for "compiled
Python"). This compilation step is automatic and invisible to the user,
and it happens every time you run a Python script.
10/27/2024 27
Compiler vs Interpreter

Important Note:
Do you need a compiler at the back of the interpreter for Python?
In simple terms:
How Python Works:
2) Execution by the Python Virtual Machine (PVM): The generated
bytecode is then executed by the Python Virtual Machine (PVM).
This is where the interpretation part happens — the PVM reads
the bytecode instructions and executes them one by one.

10/27/2024 28
Compiler vs Interpreter
Important Note:
Do you need a compiler at the back of the interpreter for Python?
Key Points:
▪ You do not need a separate compiler like C or Java to turn Python source
code into machine code. The Python interpreter handles this behind the
scenes.
▪ Python automatically compiles your source code into bytecode (a low-level,
platform-independent representation).
▪ The Python interpreter (PVM) interprets this bytecode to execute the
program.
10/27/2024 29
Compiler vs Interpreter
Important Note:
Do you need a compiler at the back of the interpreter for Python?
Why It's Different From Compiled Languages:
▪ In traditional compiled languages like C or C++, you write code, then
explicitly use a compiler to convert that code into machine code (binary
format). After compilation, the machine code can be directly executed by
the hardware.
▪ In Python, however, the conversion to bytecode and execution happen
dynamically within the Python runtime, so you never directly interact with
a separate compilation step.
10/27/2024 30
Compiler vs Interpreter

Important Note:
Do you need a compiler at the back of the interpreter for Python?
Summary:
▪ Python uses bytecode compilation followed by interpretation.
▪ There is no need for a separate compiler outside of the interpreter
because the Python interpreter handles both the bytecode
compilation and execution.

10/27/2024 31
How the Python Interpreter Works

▪ Source Code: Written in a .py file, following Python syntax.


▪ Compilation: Converts source code into bytecode.
▪ Execution: Bytecode is executed by the Python Virtual Machine (PVM).
▪ Execution Steps:
▪ Lexical Analysis: Breaks down source code into tokens.
▪ Parsing: Creates a parse tree from tokens. Parsing is the process of analyzing a sequence
of tokens (produced by a lexical analyzer) to create a hierarchical structure known as a
parse tree. This tree represents the syntactic structure of the code, based on the grammar
rules of the programming language.
▪ Bytecode Generation: Converts parse tree into bytecode.
▪ Execution: PVM executes bytecode into machine code.
10/27/2024 32
Interactive vs. Script Mode
Interactive Mode:
▪ Description: Users enter commands one at a time for immediate
feedback. . In this mode, we can enter Python code directly, and the
interpreter will execute it immediately, displaying the results.
▪ Usage: Ideal for testing snippets and learning.
▪ Access: Via command line (e.g., python or python3).
Script Mode:
▪ Description: Users write code (larger Python programs) in a file and execute
it all at once.
▪ Usage: Best for complete applications and scripts.
▪ Execution: Run from the command line using python filename.py
10/27/2024 33
Python Interpreters

1. CPython:
Description: Reference implementation
written in C; most widely used.
Features:
▪ Compiles Python code to bytecode for
the Python Virtual Machine (PVM).
▪ Extensive library support and automatic
memory management.
Use Cases: General-purpose
programming, web applications,
scientific computing.
10/27/2024 34
Python Interpreters
2. Jython:
▪ Description: Runs on the Java platform, allowing integration with Java
libraries.
▪ Features:
▪ Compiles Python code to Java bytecode.
▪ Supports dynamic typing.

▪ Use Cases: Enterprise applications, web applications using Java


frameworks.
3. IronPython:
▪ Description: Designed for the .NET framework, enabling use of .NET
libraries.
▪ Features:
▪ Compiles Python code to .NET Intermediate Language (IL).
▪ Direct access to .NET libraries.
▪ Use Cases: Applications within the .NET ecosystem, Windows applications
35
Components of Python Program

10/27/2024 36
Python REPL

▪ The sequence of events in the interactive window can be described


as a loop with three steps:
▪ First, Python reads the code entered at the prompt.
▪ Then the code is evaluated.
▪ Finally, the output is printed in the window and a new prompt is
displayed.
▪ This loop is commonly referred to as a” Read-Evaluate-Print
Loop” or “REPL”. Python programmers sometimes refer the
Python shell as a “Python REPL”, or just “the REPL” for short.
10/27/2024 37
Python Character Set

What is Character Set?


Character set is ” a bunch of identifying elements in the
programming language”.
PYTHON
CHARACTER
SET

• Letters:- A-Z, a-z


• Digits:- 0 to 9
• Special Symbols:- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? &
• White Spaces:- Blank Space , Horizontal Tab, Vertical tab, Carriage Return.
• Other Characters:- Python can process all 256 ASCII and Unicode
Characters.
38
Tokens or Lexical Unit

What is Token? 1. Key


Words
“Individual elements that
are identified by
programming language are 5. Punctuators 2. Identifiers
called tokens or lexical
unit”. TOKENS

4. Operators. 3. Literals
39
Keywords

Definition: Keywords are reserved words in Python with special


meanings that cannot be used as identifiers (variable names,
function names, etc.).
List of Keywords: Examples
include if, else, for, while, def, class, try, exc
ept, import, True, False, and None.
Practical Examples:
▪ Conditional statements using if, elif, and else.
▪ Looping with for and in.
▪ Exception handling with try, except, and finally.
▪ Function definition using def.
10/27/2024 40
Keywords
There are some reserved words:
and, assert, break, class, continue, def, del,
elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass,
print, raise, return, try, while (total: 28
keywords (old version))
# Python code to demonstrate working of iskeyword()
# importing "keyword" for keyword operations
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
10/27/2024 41
Identifiers

Definition: Identifiers are names used to identify variables,


functions, classes, and other objects in Python.

Examples:

▪ Valid
identifiers: student_name, _score, total_marks_2023.

▪ Invalid identifiers: 1st_place, my-variable, class.

▪ Using identifiers in function definitions and calls.

10/27/2024 42
Python Naming Conventions

1. An identifier can be a combination of uppercase letters,


lowercase letters, underscores(_), and digits (0-9).
Hence, the following are valid identifiers:
name, roll_no, var_1, num1, num2 and sum.

2. The first character must be letter or underscore ( _ ). Special characters


such as %, @, and $ are not allowed within identifiers. An identifier
should not begin with a number.
Example:
“2variable” is not valid
“variable2” is acceptable.
10/28/2024 43
Python Naming Conventions

3. Python is a case-sensitive language and this behaviour extends to


identifiers. Thus, Labour and labour are two distinct identifiers in
Python.

4. You cannot use Python keywords as identifiers.

5. You can use underscores(_) to separate multiple words in your identifier.

10/28/2024 44
Python Naming Conventions

Some valid identifiers:

Myfile1 DATE9_7_8 f_name

_xs MYFILE _FXd

Some invalid identifiers:

MY-REC 28dre @rate

elif false del


10/28/2024 45
Values and Variables

Values: The data that can be stored and manipulated in Python.

Definition: Variables are used to store data values. Variable types don’t
need to be declared.
▪ Python figures out the variable types on its own.
Example:
age = 30
name = "Alice"

46
Literals / Constant Values

Literals/Constant Values: Python literals are quantities/ constants whose


value does not change during the execution of a program.

47
String Literals or Constants

A collection of letters is called a string of “string literal”. The string must


be covered with quotes.

Python supports both forms of quotes i.e.


‘Python’
“Python”

48
Input and Output

Input in Python:

▪ Using input() Function: Reads user input as a string.

Example: name = input("What is your name? ").

▪ Type Conversion: Convert input to other types

Example: age = int(input("Enter your age: "))).

10/27/2024 49
Input and Output

Output in Python:

▪ Using print() Function: Outputs data to the console.

Example: print("Hello, World!").

▪ Formatted Output: Use f-strings or format() for displaying variables.


Example 1: with f-strings:
name = "Alice“
score = 95
print(f"Student {name} scored {score} in the exam.")
print("Student {} scored {} in theexam.".format(name, score))
Same Output: Student Alice scored 95 in the exam. 50
Escape Sequence Character

\n New Line

\r Carriage return

\t Horizontal Tab
51
Escape Sequence Character

52
Comments
Types of Comments:
Single-Line Comments: Begin with # and are used for brief notes.
Example: # This is a comment
Multi-Line Comments: Use triple quotes (''' or """) for longer explanations.
Example:
""" This is a multi-line comment. It can span multiple
lines. """
▪ Enhance code clarity and understanding.
▪ Aid in debugging by allowing code to be temporarily disabled.
▪ Provide context for complex logic.
▪ Be concise and avoid obvious comments.
▪ Explain why something is done rather than what is done.
▪ Keep comments updated with code changes.
10/27/2024 53
Docstrings

Definition: Special comments that describe the purpose and usage of


functions, classes, or modules, defined using triple quotes.
Example: def function_name():
"""This function does something."""
▪ Provide documentation that can be accessed via the help() function.
▪ Standardize documentation across codebases.
▪ Be descriptive about the function/class/module's purpose and
parameters.
▪ Use a consistent format (e.g., Google style, NumPy style).
▪ Keep it concise yet informative.
10/27/2024 54
Data Types

10/27/2024 55
Built-in Data Types/Common Data Types

Numeric Types: int, float, complex.


▪ Integers (default for numbers): Whole numbers (e.g., 5, -3).
▪ Floats: Decimal numbers (e.g., 3.14, -0.001).
Sequence Types: str, list, tuple.
▪ Lists: Ordered collections (e.g., [1, 2, 3]).
▪ Tuples: Immutable ordered collections (e.g., (1, 2, 3)).
▪ Strings: Text data (e.g., "Hello, World!"). Can use “” or ‘’ to specify with
“abc” == ‘abc’
▪ Unmatched can occur within the string: “matt’s”

10/27/2024 56
Built-in Data Types/Common Data Types

Mapping Type: dictionary


▪ Dict: Key-value pairs (e.g., {"name": "Alice", "age": 25}).
Set Types: set.
Boolean Type: Boolean- True or False values
Importance:
▪ Ensure data integrity and compatibility for operations.
▪ Affect memory usage and performance.
Practical Examples:
•Numeric: a = 10 (int), b = 3.14 (float).
•String: greeting = "Hello!".
•List: numbers = [1, 2, 3].
•Dictionary: person = {"name": "Alice", "age": 30}.
10/27/2024 57
Built-in Data Types/Common Data Types
Summary
Data Types Classes Description

Numeric int, float, complex holds numeric values

String str holds sequence of characters

Sequence list, tuple, range holds collection of items

Mapping dict holds data in key-value pair form

Boolean bool holds either True or False

Set set, frozeenset hold collection of unique items


10/27/2024 58
Type Conversion

▪ Implicit Conversion: Automatically performed by Python


(e.g., int to float).
Example: result = a + b where a is int and b is float.
▪ Explicit Conversion: Manually performed using built-in
functions.
Example: num_int = int("123").
▪ Built-in Functions:
int(), float(), str(), list(), dict() for converting
10/27/2024
data types. 59
Statements and Expressions

Statement: A line of code that performs an action (assignments, function


calls).
Example: x = 10 (assignment statement).
▪ First assignment to a variable creates it.
▪ Assignment is = and comparison is ==.

Expression: A combination of values and operators that evaluates to a value.

Example: y = x + 5 (expression that evaluates to 15).


10/28/2024 60
Statements and Expressions

Types of Statements:

▪ Assignment Statements: Assign values to variables (e.g., a = 5).

▪ Conditional Statements: Execute code based on conditions


Example: if a > 0:
print("Positive")).

11/1/2024 61
Statements and Expressions

▪ We will also use the following in Statements and Expressions:

▪ For numbers + - * / % are as expected

▪ Special use of + for string concatenation and % for string


formatting (as in C’s printf)

▪ Logical operators are words (and, or, not) not symbols

10/28/2024 62
Lines and Indentation

Lines and indentation in Python are important because they are used to
structure code and to define blocks of code.
▪ Lines
Lines in Python code can be either blank or non-blank. Blank
lines are ignored by the Python interpreter. Non-blank lines
contain code that is executed by the Python interpreter.
▪ Indentation
Indentation is used to group statements together. Statements
that are indented at the same level are considered to be part of
the same group. Statements that are indented at a lower level
are considered to be part of a nested group.
Lines and Indentation

Example
▪ The following code shows how to use lines and indentation to create a
simple Python program:
if 5 > 2:
print("Five is greater than two!")

▪ This code is indented at one level, which means that the print()
statement is part of the same block of code as the if statement.

▪ If the print() statement was not indented, it would be considered


to be outside of the if statement and would always be executed,
regardless of the value of the expression 5 > 2.
Statements and Expressions

Loop Statements: Repeat code blocks


Example: for i in range(5):
print(i).
▪ Indentation matters to code meaning
▪ Block structure indicated by indentation
Function Definition Statements: Define new functions
Example:
def greet(name):
return f"Hello, {name}!").

10/28/2024 65
Control Flow

10/27/2024 66
Control Flow

Types of control statements

10/27/2024 67
Control Flow
Conditional Statements:
if, if-else, and if-elif-else for decision-making.
Example:
if x > 0:
print("Positive")
Looping Statements:
for Loop: Iterates over a sequence.
while Loop: Repeats as long as a condition is true.
Example:
for i in range(5):
print(i)
10/27/2024 68
Control Flow

Control Flow Statements:


break: Exits a loop.
continue: Skips the current iteration.
Example:
for i in range(10):
if i % 2 == 0: continue # Skip even numbers

10/27/2024 69
Operators in Python
Arithmetic Operators:
Perform mathematical operations.
Examples:
▪ + (Addition: 5 + 2 = 7)
▪ - (Subtraction: 4 - 2 = 2)
▪ * (Multiplication: 2 * 3 = 6)
▪ / (Division)
z = 5 / 2 # Answer 2.5,
integer division
▪ // (Floor Division e.g.: 5//2 = 2)
▪ % (Modulus e.g.: 5 % 2 = 1)
▪ ** (Exponentiationeg.: 4 ** 2 = 16) 70
Operator Name Example

= Assignment Operator a = 7

+= Addition Assignment a += 1 # a = a + 1
Assignment
-= Subtraction Assignment a -= 3 # a = a - 3
Operators with
Multiplication
Examples *= a *= 4 # a = a * 4
Assignment

/= Division Assignment a /= 3 # a = a / 3

%= Remainder Assignment a %= 10 # a = a % 10

**= Exponent Assignment a **= 10 # a = a ** 10


10/28/2024 71
Python Comparison Operators

▪ Comparison operators compare two values/variables and return a


Boolean result: True or False.
Example:
a = 5
b = 2
print (a > b) # True
▪ Here, the “ >” comparison operator is used to compare whether
a is greater than b or not.
72
Operator Meaning Example
3 == 5 gives us
== Is Equal To
False

!= Not Equal To 3 != 5 gives us True

> Greater Than 3 > 5 gives us False Python


Comparison
< Less Than 3 < 5 gives us True Operators

Greater Than
>= 3 >= 5 give us False
or Equal To

Less Than or
<= 3 <= 5 gives us True
Equal To 73
Python Logical Operators
OPERATOR EXAMPLE MEANING

▪ Logical operators are used to check


Logical AND:
whether an expression is True or
True only if both
False. They are used in decision- and a and b
the operands are
making. True
Example:
a = 5 Logical OR:
b = 6 True if at least one
or a or b
print((a > 2) and of the operands is
(b >= 6)) #True True

▪ Here, and is the logical Logical NOT:


operator AND. Since both a > True if the operand
not not a
2 and b >= 6 are True, the is False and vice-
result is True. versa. 74
Python Bitwise operators Oper
Meaning Example
ator

▪ Bitwise operators manipulate Bitwise


& x & y = 0 (0000 0000)
AND
operands as though they were
binary digit strings, performing Bitwise
| x | y = 14 (0000 1110)
OR
operations at the individual bit
level, which is why they are called Bitwise
~ ~x = -11 (1111 0101)
"bitwise" operators. NOT

Bitwise
^ x ^ y = 14 (0000 1110)
XOR
▪ For example, 2 is 10 in binary
and 7 is 111. Bitwise
>> right x >> 2 = 2 (0000 0010)
shift
▪ In the table: Let x = 10 (0000
Bitwise
1010 in binary) and y = << left x << 2 = 40 (0010 1000)
4 (0000 0100 in binary) shift 75
Python Special operators
▪ Python language offers some
special types of operators like Operator Meaning Example
the
i. identity operator True if the
ii. membership operator. operands are x is
is
▪ Identity operators: In Python, identical (refer to True
is and is not are used to the same object)
check if two values are located True if the
on the same part of the operands are not x is
memory. is not identical (do not not
▪ Two variables that are equal, refer to the same True
do not imply that they are object)
identical. 76
Identity operators

▪Example:

▪Here, we see that x1 and y1 are integers of the same values, so they are
equal as well as identical. Same is the case with x2 and y2 (strings).
▪But x3 and y3 are lists. They are equal but not identical. It is
because the interpreter locates them separately in memory although
they are equal. 77
Membership Operators

▪ In Python, in and not in are Operator Meaning Example


the membership operators. They
True if
are used to test whether a value value/variab
or variable is found in a in le is found 5 in x
sequence (string, list, in the
tuple, set and sequence
dictionary).
True if
value/variab
▪ In a dictionary we can only
not in le is not 5 not in x
test for the presence of key, not
found in the
the value.
sequence
78
Membership Operators

Example :

▪ Here, 'H' is in x but 'hello' is


not present in x (remember,
Python is case sensitive).

▪ Similarly, 1 is key, and 'a' is


the value in dictionary y.
Hence, 'a' in y returns
False.

79
Other Operator Types and Precedence

Unary Operators: Operate on a single operand (e.g., -x, not x).


Binary Operators: Operate on two operands (e.g., x + y, x > y).
Ternary Operators: Involve three operands (e.g., x if condition else y).

10/27/2024 80
Operator Precedence
Determines the order in which operations are evaluated.
1. Highest Precedence:
▪ Parentheses ()
▪ Exponentiation **
2. Middle Precedence:
▪ Multiplication *, Division /, Modulus %
▪ Addition +, Subtraction -
3. Lowest Precedence:
▪ Comparison ==, !=, >, <
▪ Logical and, or, not
4. Associativity:
▪ Left-to-Right: Most operators (e.g., +, -, *, /)
▪ Right-to-Left: Exponentiation **, assignment =.
10/27/2024 81
Assignment 1
▪ Can we assign multiple names at the same time?
>>> x, y = 2, 3
>>> x # Ouput?
>>> y # Ouput?

▪ Can we swap values?


>>> x, y = y, x # Is this Correct?

▪ Can assignments be chained?


>>> a = b = x = 2 # Is this Correct?

10/27/2024 82
Assignment 2
Evaluate the following code.
x = 34 - 23 # A comment.
y = “Hello” # Another one.
z = 3.45
if z == 3.45 or y == “Hello”:
x = x + 1
y = y + “ World” # String concat.
print x
print y
10/27/2024 83

You might also like