0% found this document useful (0 votes)
13 views8 pages

Python Basics: Operators and Data Types

The document discusses operator precedence and associativity in Python. It explains that operator precedence follows PEMDAS rules, with parentheses having the highest precedence, followed by exponentiation, multiplication/division, and finally addition/subtraction. When two operators have the same precedence, associativity determines the order of operations from left to right, except for exponentiation which is right to left associative. Examples are provided to illustrate precedence between operators like or and and, as well as associativity for multiplication/division and exponentiation.

Uploaded by

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

Python Basics: Operators and Data Types

The document discusses operator precedence and associativity in Python. It explains that operator precedence follows PEMDAS rules, with parentheses having the highest precedence, followed by exponentiation, multiplication/division, and finally addition/subtraction. When two operators have the same precedence, associativity determines the order of operations from left to right, except for exponentiation which is right to left associative. Examples are provided to illustrate precedence between operators like or and and, as well as associativity for multiplication/division and exponentiation.

Uploaded by

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

2 marks :

[Link] the logic to swap the values of two identifies without using third variable ?

Python Progam for swapping: OUTPUT:


Before Swapping x and y: 10 20
x=10 After Swapping x and y: 20 10
y=20
print("Before Swapping x and y:",x,y)
x,y=y,x
print("After Swapping x and y:",x,y)

[Link] are keywords?Give examples.

 Keywords are the reserved words in Python.


• They are used defining the syntax and structure of the Python language.
• In Python, keywords are case sensitive.

Examples

• True, False, and, or, not, if, elif, else, for

[Link] four types of scalar objects in Python.

Scalar objects: Scalar objects are indivisible object that do not have internal structure.

The 4 types of scalar objects in Python are:

SCALAR OBJECTS EXAMPLE


bool x=True
y=False
int x=5

float (floating-point number) x=5.5

string name=”python”
name=’python’
[Link] about logical operators available in python with examples.

• Logical Operators are used to perform logical operations like and, or and not.

16 marks :

1. Illustrate the various data types in Python with examples.

Data types of Python. They are

• Number (integer,complex number,float)


• Dictionary
• Boolean
• Set
• Sequence Data type. (String ,List , Tuple)

Number
• Numbers are created by numeric literals.
• Numeric objects are immutable, which means when an object is created its value cannot be
changed.
• Python will automatically convert a number from one type to another if it needs.
Python has three distinct numeric types:
1. Integers
• Boolean
2. Floating point numbers
3. Complex numbers.

Integers
• Integers represent negative and positive integers without fractional parts.

>>> type(2)
<class 'int'>

Boolean
• Boolean type is a subtype of plain integers.
• The simplest built-in type in Python is the bool type, it represents the truth
values,(True or False)

>>> type(True)
<class 'bool'>

>>> type(False)
<class 'bool'>

Floating point numbers

• Floating point numbers represents negative and positive numbers with fractional
Parts

>>> type(42.0)
<class 'float'>

Complex numbers

• A complex number is a number of the form A+Bi where i is the imaginary number.
Complex numbers have a real and imaginary part.
• Python supports complex numbers either by specifying the number in (real + imagj)
or (real + imagJ) form or using a built-in method complex(x, y).

>>> type(1+2j)
<class ‘complex’>
String
• A string type object is a sequence of characters.
• Strings start and end with single or double quotes.
• Python strings are immutable ie., once a string is generated, character within the string
cannot be modified.

>>> type('Python language')


31
<class 'str'>

List
• A list is a container which holds comma-separated values (items or elements)
between square brackets where all the items or elements need not to have the same type.
• A list without any element is called an empty list.
• Python lists are mutable.

>>>list1= [ 'computer', 2018 , 8.25, 'python' ]


>>> type(list1)
<class 'list'>

Tuple

• Tuple is an ordered sequence of elements same as list.


• The only difference is that tuples are immutable.
• Tuples once created cannot be modified.

>>>a=(1,'python')
>>>type(a)
<class 'tuple'>

Dictionary
• Dictionary is an unordered collection of items with key: value pairs.
• In a dictionary,elements can be of any type.

>>>d = {1: 'apple', 2: 'ball'}


>>>type(d)
<class 'dict'>
2. Explain in detail about operator precedence and associativity of operator precedence in
Python with relevant examples.

Precedence of Operators in Python: – PEMDAS

What is Operator Precedence???

• Operator Precedence in Python programming is a rule that describe which


operator is solved first in an expression.
• When an expression contains more than one operator, the order of evaluation
depends on the precedence of operators.

Python Operators Precedence Rule – PEMDAS:


• Operator precedence in python follows the PEMDAS rule for arithmetic

expressions.

• Firstly, parantheses will be evaluated, then exponentiation and so on.

◦ P – Parentheses

• Parentheses have the highest precedence and parentheses are evaluated first.
• Examples:
o 2 * (3-1) = 4
o (1+1)**(5-2) = 8.

◦ E – Exponentiation

• Exponentiation(**) has the next highest precedence.


• Example :
o 1 + 2**3 = 9
o 2 *3**2 =18

◦ M – Multiplication and D – Division

• Multiplication and Division have higher precedence than Addition and Subtraction.
• Examples:
o 2*3-1 = 5
o 6+4/2 = 8.

◦ For example, multiplication has higher precedence than subtraction.

◦ A – Addition and S – Subtraction

• Addition and Subtraction have lower precedence than Multiplication and Division

Operator Precedence Table:

• The following table shows the precedence of Python operators.

• The upper operator holds higher precedence than the lower operator.
Example Program for operator precedence:

# Precedence of and & or operators

colour = "red"

quantity = 0

if colour == "red" or colour == "green" and quantity >= 5:

print("Your parcel is dispatched")

else:

print("your parcel cannot be dispatched")

Output:

Your parcel is dispatched

ASSOCIATIVITY IN OPERATOR PRECEDENCE

• When two operators have the same precedence, associativity helps to determine the
order of operations.

• Associativity is the order in which an expression is evaluated, that has multiple

operator of same precedence.

• Almost all the operators have left to right associativity except exponentiation.

Example:

(i)Left to Right Associativity

• Mulitplication and Floor Division share the same precedence.

• Hence if both the operators were present in an expression the left one will be evaluated first.

print(10*2//3)

10*2 will be evaluated first.


ii) Right to Left Associativity

• Exponent operator ** has right-to-left associativity in Python.

Common questions

Powered by AI

Logical operators in Python are used to perform boolean operations on values, determining the logic of expressions. The primary logical operators are `and`, `or`, and `not`. - The `and` operator returns True if both operands are true. For example, `True and False` returns `False`. - The `or` operator returns True if at least one of the operands is true. For example, `True or False` returns `True`. - The `not` operator inverts the boolean value of operand. For example, `not True` returns `False`. These operators help in making decisions in conditional statements .

In Python, both lists and dictionaries can store heterogeneous data types, yet they differ fundamentally in their structure and use cases. Lists are ordered collections indexed by integers, allowing storage of items like `['computer', 2018, 8.25, 'python']`, mixed without type constraints and accessed via index positions. They facilitate sequential data manipulation and iteration. Dictionaries, on the other hand, store data as key-value pairs in an unordered structure, allowing retrieval based on unique keys, not positions. For example, `d = {1: 'apple', 2: 'ball'}`. Each key must be unique, and keys are usually immutable types (like strings or numbers). The dichotomy of ordered lists and pair-wise unordered dictionaries supports flexible storage and retrieval use cases across varying programming scenarios .

The immutability of Python strings means once a string is created, its characters cannot be altered. This behavior is significant for programming as it ensures string constants remain unchanged and aids in optimizing memory usage and performance. For instance, if you have a string `s = 'hello'`, attempting to modify it with `s[0] = 'y'` will result in an error. Instead, any modification would create a new string, e.g., `s = 'y' + s[1:]` resulting in `'yello'`. Immutability leads to reliable references in code, which facilitates clearer data flow and reduces bugs related to unintended changes .

In Python, to swap the values of two variables without a third variable, the tuple unpacking feature is used. This involves grouping the two variables in a tuple on the right-hand side of the assignment (`x, y = y, x`), which internally creates a temporary tuple object to hold the original values. The values are then swapped as they are simultaneously assigned back to the respective variables on the left-hand side, resulting in swapped values. For example, if `x=10` and `y=20`, after executing `x, y = y, x`, `x` will be `20` and `y` will be `10` .

Lists and tuples in Python are both used to store ordered collections of items, but they have distinct differences. Lists are mutable, meaning their contents can be changed after creation (e.g., adding, removing, or modifying elements). They are created using square brackets, e.g., `list1 = ['computer', 2018, 8.25, 'python']`. Due to their mutability, lists are often used when data collection needs alteration or frequent updates. In contrast, tuples are immutable, meaning once created, their contents cannot be changed. This immutability ensures the integrity of data that should not be modified, making tuples useful for fixed collections like constants or configuration settings. Tuples are created with parentheses, e.g., `a=(1,'python')`. Both lists and tuples can store items of mixed data types .

Operator precedence in Python defines the order in which parts of an expression are evaluated in the presence of multiple operators. This precedence determines which operations are performed first when there is more than one operator, thus affecting the result of expressions. Python follows a hierarchy derived from PEMDAS rules: - Parentheses are evaluated first, - Exponentiation (`**`) follows, - Multiplication (`*`), Division (`/`), and Floor Division (`//`) are next, - Addition (`+`) and Subtraction (`-`) have the lowest precedence. Expressions are evaluated in this order unless overridden by parentheses, ensuring predictable and accurate computation of complex expressions .

Operator associativity in Python determines the order of evaluation for operators with the same precedence within an expression. Most Python operators have left-to-right associativity, meaning operations are grouped and evaluated from the left side first. For instance, in the expression `10 * 2 // 3`, multiplication and floor division operators are of equal precedence, so evaluation proceeds first with `10 * 2`, and then the result is divided using `//`. The exponentiation operator `**` is an exception, as it has right-to-left associativity. For example, in the expression `2 ** 3 ** 2`, the computation occurs starting from the rightmost `**`, resulting in `2 ** (3 ** 2)`, hence `2 ** 9`, not `(2 ** 3) ** 2` .

Keywords in Python are reserved words that hold specific meanings and constitute part of the language's syntax and structure. These words are case-sensitive, meaning their capitalization matters (e.g., `True`, `False`, `if`, `elif`, etc.), and they cannot be used as identifiers such as variable names. This sensitivity ensures clarity and prevents conflicts within the code, as keywords serve as essential building blocks that define operations, control structures, and data management within the language. Misuse of keywords (e.g., using `if` in place of a variable name) would lead to syntax errors, highlighting their crucial role in maintaining programming language integrity and functionality .

The four scalar object types in Python are `bool`, `int`, `float`, and `string`. - `bool`: Represents truth values, True and False, and is a subtype of integer. E.g., `x=True`. - `int`: Represents whole numbers without fractions. E.g., `x=5`. - `float`: Represents real numbers with fractional parts. E.g., `x=5.5`. - `string`: A sequence of characters enclosed in quotes. E.g., `name='python'` .

In Python, parentheses have the highest precedence among all operators in expressions, meaning they are evaluated first regardless of the operations they enclose. This allows for the explicit dictation of order in which expressions are evaluated. For instance, in the expression `2 * (3 - 1)`, the subtraction within the parentheses is computed first, resulting in multiplication with 2 being applied to the result. Thus, parentheses can override the default operator precedence to evaluate expressions in a desired order, ensuring clarity and correct results based on precedence requirements .

You might also like