Problem Solving Using Python —
Basics
Prepared by: Sophie Angela
Department of Computer Science
and Engineering
Python Operators and Expressions
• • Operators are symbols that perform
operations on variables and values.
• • Examples: +, -, *, /, %, //, **
• • Expressions combine variables and
operators to produce a result.
• Example:
• x=5
• y=2
• print(x + y) # Output: 7
Types of Operators
• 1. Arithmetic Operators: +, -, *, /, %, //, **
• 2. Relational Operators: ==, !=, >, <, >=, <=
• 3. Logical Operators: and, or, not
• 4. Assignment Operators: =, +=, -=, etc.
• 5. Bitwise Operators: &, |, ^, ~, <<, >>
Expressions Example
• Example of expression evaluation:
• x = 10
• y=3
• result = x ** y + 5
• print(result)
• Output:
• 1035 + 5 = 1035
• • Expressions always return a value.
Operator Precedence
• • Determines the order in which operations
are performed.
• • Example:
• result = 10 + 5 * 2 # Multiplication before
addition
• • Output: 20
Operator Precedence Table
(Simplified)
• Highest → Lowest:
• 1. Parentheses: ()
• 2. Exponentiation: **
• 3. Multiplication, Division, Floor Division,
Modulus: *, /, //, %
• 4. Addition, Subtraction: +, -
• 5. Relational, Logical, Assignment
Associativity
• • If operators have the same precedence,
associativity decides the order.
• • Most operators are Left-to-Right associative.
• • Example:
• result = 5 - 2 + 3 # Left to Right → (5 - 2) + 3
=6
• • Exponentiation (**) is Right-to-Left
associative.
Type Conversion
• • Changing the data type of a variable is called
type conversion.
• • Two types:
• 1. Implicit Conversion (Automatic)
• 2. Explicit Conversion (Manual)
Implicit Conversion
• • Python automatically converts smaller data
types to larger ones.
• Example:
• x=5
• y = 2.5
• z=x+y
• print(z) # Output: 7.5
• • int is converted to float automatically.
Explicit Conversion
• • Manual conversion using built-in functions:
• int(), float(), str(), bool()
• Example:
• a = '10'
• b = int(a)
• print(b + 5) # Output: 15
Comments in Python
• • Comments are used to explain code and
make it readable.
• • They are ignored by the Python interpreter.
• • Two types:
• 1. Single-line comment: # This is a comment
• 2. Multi-line comment: ''' or """
Example of Comments
• Example:
• # This program adds two numbers
• x=5
• y=3
• print(x + y) # Output: 8
• '''This is a multi-line comment
• spanning more than one line.'''
Thank You!
• Any Questions?
• — End of Presentation —