0% found this document useful (0 votes)
11 views70 pages

Python Basics: Interactive & Script Modes

Uploaded by

spartansheik
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)
11 views70 pages

Python Basics: Interactive & Script Modes

Uploaded by

spartansheik
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

Chapter 1

Introduction to Python

Presenter Name
Syllabus
Problem Solving, Problem Analysis Chart, Developing an Algorithm, Flowchart and
Pseudocode, Interactive and Script Mode, Indentation, Comments, Error
messages, Variables, Reserved Words, Data Types, Arithmetic Operators and
Expressions, Built-in Functions, Importing from Packages.
PYTHON INTERACTIVE AND SCRIPT MODE
Python has two basic modes: interpreter and interactive modes.
The interactive mode is a command line shell, which gives immediate feedback for each statement, fed in the
active memory. As new lines are fed into the interpreter, the fed program is evaluated both in part and in
whole.
The script mode is the mode where the scripted and finished .py files are run in the Python interpreter.
Python Interactive Mode
Python allows the user to work in an interactive mode. It is a way of using the Python interpreter by executing
Python commands from the command line with no script.
This allows the user to type an expression, and immediately the expression is executed and the result is
printed.
To start an interactive mode, we will see that the Python command line window appears as shown in Fig. 2.1.
The “>>>” is the prompt used in the Python interactive mode which indicates that the prompt is waiting for
the Python command and produces the output immediately.
Python Interactive Mode
Example:
>>>5+7
12
>>>print(“Hello world !”)
Hello world !
>>>num=10
>>>num=num/2
>>>print(num)
5.0
Working in the interactive mode is convenient for testing a single line code for instant execution. But in the
interactive mode, we cannot save the statements for future use and we have to retype the statements to run them
again.
Python Interactive Mode
Writing Multiline Code in Python Command Line

To write multiline code in Python interactive mode, hit Enter key for continuation lines, this prompts by default three dots (…). The
continuation lines are needed only in the case of procedures, branching, loop constructs. When it happens, press a tab for indentation.

Example:

>>>flag=1

>>>if flag:

… print(“WELCOME TO PYTHON.”)

WELCOME TO PYTHON.

>>>
Python Interactive Mode
2 Python Script mode
The Python interpreter is a program that reads and executes Python code, in which Python statements can be
stored in a file. The Python system reads and executes the commands from the file, rather than from the
console. Such a file is termed as Python program.
Depending on the environment, start the interpreter by clicking on an icon, or by typing python on a
command line. When it starts, the output will be shown in Fig. 2.2.
Python Interactive Mode
The first three lines contain information about the interpreter and the operating system it is running on.
The version number is 3.6.0. It begins with 3, if the version is Python 3. It begins with 2, if the version is
Python 2.
The last line >>> is a prompt (chevron) that indicates that the interpreter is ready to enter code. If the user
types a line of code and hits Enter, the interpreter displays the result:
In the interpreter or script mode, a Python program (script) is written in a file, where file name has extension
“.py”. The Python script is executed by the Python interpreter. By default, the Python scripts are saved in the
Python installation folder. Once the script is created, it can be executed again and again without retyping. The
Scripts are editable.
To execute a script, Type the file name along with the path at
the prompt. For example, if the name of the file is [Link],
we type

>>>python [Link]
Enter 2 numbers
6
3
The sum is 9
INDENTATION
Indentation in Python refers to the whitespace (spaces or tabs) at the beginning of a line of code. In contrast to many
programming languages that use curly braces or specific keywords to define code blocks, Python uses indentation to mark
the boundaries of its code blocks. This makes indentation a fundamental and mandatory part of Python's syntax.
The key aspects of indentation in Python

Statements with the same level of indentation are considered part of the same code block. For example, the statements
within an if statement, for loop, while loop, or function definition are grouped by their shared indentation level.
Indentation is not merely a stylistic choice for readability. It is a strict requirement of the Python interpreter. Incorrect or
inconsistent indentation will result in an IndentationError.
All lines within a single code block must have the same number of leading spaces or tabs. Mixing spaces and tabs for
indentation within the same file or even the same block is strongly discouraged and can lead to errors.
The Python community widely recommends using four spaces per indentation level. While other amounts (e.g., two
spaces, eight spaces, or tabs) are technically allowed, four spaces is the conventional standard for consistency and
readability.
Example
n = int(input('Enter a number: '))
sum=0
i=1
while i<=n:
sum=sum+i*i
i+=1
print('Sum = ',sum)
COMMENTS
Comments are used to explain the code, making it more readable and understandable for both the programmer and non-
programmers who might work with the code in the future.
Comment statements are non-executable statements so the python interpreter ignores comments during program
execution.

In Python, a comment starts with # (hash sign). Everything following the # till the end of that line is treated as a comment
and the interpreter simply ignores it while executing the statement. They have no effect on the program results.
# [Link]
# Swapping the values of a two variable program

# written by G. Sugitha, April 2018


•Python does not have a dedicated syntax for multi-line comments like some other languages,

multi-line strings enclosed in triple quotes (''' or """) are often used for this purpose.

''' This is a multi-line comment.

[Link]

swapping the values of a two variable program

written by G. Sugitha, April 2025. '''


ERROR MESSAGES
A programmer can make mistakes while writing a program, and hence, the program may
not execute or may generate wrong output. The process of identifying and removing such
mistakes, also known as bugs or errors, from a program is called debugging.
Errors occurring in programs can be categorized as:

i) Syntax errors
ii) Logical errors
iii)Runtime errors
Syntax Errors
Like other programming languages, Python has its own rules that determine its syntax. The interpreter
interprets the statements only if it is syntactically (as per the rules of Python) correct. If any syntax error is
present, the interpreter shows error message(s) and stops the execution there.
Example: Parentheses must be in pairs, so the expression (20 + 22) is syntactically correct, whereas (17 + 35
is not due to absence of right parenthesis.
Such errors need to be removed before the execution of the program.
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. A logical error produces an
undesired output but without abrupt termination of the execution of the program. Since the program interprets
successfully even when logical errors are present in it, it is sometimes difficult to identify these errors.
The only evidence to the existence of logical errors is the wrong output. While working backwards from the
output of the program, one can identify what went wrong.
Example: To find the average of two numbers 10 and 12 and we write the code as 10 + 12/2, it would run
successfully and produce the result 16. Surely, 16 is not the average of 10 and 12. The correct code to find the
average should have been (10 + 12)/2 to give the correct output as 11.
Logical errors are also called semantic errors as they occur when the meaning of the program (its semantics) is
not correct.
Runtime Error
A runtime error causes abnormal termination of program while it is executing. Runtime error is when the

statement is correct syntactically, but the interpreter cannot execute it. Runtime errors do not appear until after

the program starts running or executing.

Example: In a statement having division operation in the program, by mistake, if the denominator entered is

zero then it will give a runtime error like “division by zero”.


TOKENS
Python breaks each logical line into a sequence of elementary lexical components known as
tokens.
A token is the smallest unit of the program. Each token corresponds to a substring of the logical
line.
Python Tokens

Keywords Identifiers Literals Delimiters Operators


or
Variables
KEYWORDS
Keywords are reserved words they have predefined meanings in Python.
They cannot be used as ordinary identifiers and must be spelled exactly as they are written.
Python3 has 33 keywords.
The Table presents all 33 of Python’s keywords. The first three are grouped together because they all start
with uppercase letters.
IDENTIFIERS
A Python identifiers is the name given to a variable, function, class, module or other object.
An identifier can begin with an alphabet (AZ or az), or an underscore (_) and can include any number of letters,
digits, or underscores.
Spaces are not allowed.
Python will not accept @, $ and % as identifiers.
Python is a case-sensitive language. Thus, Hello and hello are different identifiers.
ESCAPE SEQUENCES
Escape sequences are non-printable characters. It consists of backslash followed by a character, both being
enclosed within single quotes. The recognized escape sequences are shown in Table
LITERALS
Literals are constants. They have a fixed value and they do not change during the execution of a program. Python supports
several kinds of literals. They are. They are,
1. Numeric Literals
2. String Literals
3. Boolean Literals
4. Special Literal none
5. Literal Collections
Numeric Literals
Numeric Literals represent numerical values and can be integers, floating-point numbers, or complex numbers.

Integer Literals:

Integer Literals are whole numbers without a fractional part (e.g., 10, -5, 0).

It does not contain any decimal point.

It may have either (+) or (−) sign. A number with no sign is assumed to be positive.

Commas cannot appear in an integer constant.

Python allows three types of integer literals:

Decimal Integer Literals: An integer literal consisting of a sequence of digits is taken to be decimal literal unless it begins with 0. Example: 1238, −
65.

Octal Integer Literals: A sequence of digits starting with 0o is taken to be an octal integer. Example: Decimal integer 8 will be written as 0o10 as octal
integer.

Hexadecimal Integer Literals: A sequence of digits preceded by 0x or 0X is taken to be an hexadecimal integer. Example: Decimal integer 12 will be
written as 0xC as hexadecimal integer.
Float Point Literals
Numbers with a decimal point or in scientific notation. They have Fractional form and Exponent form. Example: 3.14, -
0.5, 2.5e-3
Limits of Range in Floating-Point Representation
There is no limit to the size of an integer that can be represented in Python. But floating-point values have both a limited
range and a limited precision.
Python uses a double-precision standard format (IEEE 754) providing a range of 10-308 to 10+308 with 16 to 17 digits of
precision.
Arithmetic overflow: Arithmetic overflow occurs when a calculated result is too large in magnitude to be represented.

Example:
>>>1.5e200 * 2.0e210
inf

This result in the special value inf (“infinity”) rather than the arithmetically correct result 3.0e410, indicating that
arithmetic overflow has occurred.
Arithmetic underflow: Arithmetic underflow occurs when a calculated result is too small in magnitude to be
represented.
Example:
>>>1.0e2300/1.0e100
0.0
This results in 0.0 rather than the arithmetically correct result 1.0e2400, indicating that arithmetic underflow
has occurred.
Complex Literals: Numbers with a real and an imaginary part (e.g., 2 + 3j, -1 - 4j).
String Literals
String literals or strings represent sequence of characters and are enclosed in single quotes ('...'), double
quotes ("..."), or triple quotes ('''...''' or """...""") for multi-line strings (e.g., 'hello', "Python", '''multi-line
string''').
Example:
'Hello' 'Jovita, Jesvita' "231, Carmel Nagar, 629004"
A character literal is a single character surrounded by single or double quotes. The value with triple-quote "' '"
is used to give multiline string literal.
Example:
>>>print('Welcome to Python!')
Welcome to Python!
Boolean Literals
Boolean literals:
Boolean literals represent one of the two Boolean values: True or False. A Boolean literal can have either of
these values.
Special Literal : None
Python has one special literal, None. It is used to indicate absence of value or end of list.
Literal Collections

Literal Collections are used to represent collections of data.


List Literals: Ordered, mutable collections of items enclosed in square brackets (e.g., [1, 2, 'a']).
Tuple Literals: Ordered, immutable collections of items enclosed in parentheses (e.g., (1, 2, 'a')).
Set Literals: Unordered collections of unique items enclosed in curly braces (e.g., {1, 2, 3}).
Dictionary Literals: Unordered collections of key-value pairs enclosed in curly braces (e.g., {'name': 'Alice',
'age': 30}).
DELIMITERS
Delimiters are symbols that perform three special roles in Python like grouping, punctuation, and assignment/
binding of objects to names. Table presents all 24 of Python’s delimiters.
VARIABLES
A variable is an identifier, which holds a value. In programming, a value is assigned to a variable.

Technically, a variable is the name given to the memory location to store values, so that there is no need to remember the address of the
location. Variables hold different kind of data and the same variable might hold different values during the execution of a program.

A variable can be used to define a name of an identifier. An identifier is a name used to identify a variable, function, class, module or
other object.

Rules for naming variables


• Variable names can be uppercase letters or lower case letters.
• Variable names can be at any length.
• They can contain both letters and numbers, but they can’t begin with a number.
• The underscore ( _) character can appear in a name. It is often used in names with multiple words.
• No blank spaces are allowed between variable names.
• A variable name cannot be any one of the keywords or special characters.
• Variable names are case-sensitive.

Example:

Roll_no, GrossPay, a1, salary


Creating Variables

The assignment statement (=) assigns a value to a variable. The usual assignment operator is =.

Syntax:

Here variable is an identifier and ‘expr’ is an expression. The meaning of the assignment is that, the expression on the right side is
evaluated to produce a value, which is then associated with the variable named on the left side.

Example:

>>>n=10

>>>name=“Jovita”

>>>PI=3.14

>>>7wonders=‘tajmahal’

SyntaxError: invalid syntax // It is illegal because it begins with a number.

>>>student_name=‘Denisha’

>>>a=b=c=d=10
DATA TYPES
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable can hold
and the operations that can be performed on that data. Data type is a category of values. The built in data types are,
Numbers (Integer type, Floating Point type, and Complex type), String, List, Tuple, Set, Dictionary.
Numbers
Number data types store numeric values. Python has three number types: integer numbers, floating point numbers, and
complex numbers.
Integer Type
An integer type (int) represents signed whole numbers. An integer represents both positive and negative numbers. The
range is at least 2,147,483,648 to 2,147,483,647. To write an int constant,
A zero is written as just
To write an integer in decimal (base 10), the first digit must not be zero. Example: 25000
To write an integer in octal (base 8), precede it with “0o” and use the digits 0 to 7, plus A, B, C, D, E, F.
Example: 0o177
To write an integer in hexadecimal (base 16), precede it with ‘0x” or “0X”. Example: 0x77
To write an integer in binary (base 2), precede it with “0b” or “0B”. Example: 0b101
Floating Point Type
A floating point (float) type represents numbers with fractional part. A floating-point number has a decimal
point and a fractional part.
Example: 3.0 or 3.17 or 28.72.
Python cannot represent very large or very small numbers, and the precision is limited to only about 14 digits.
The floating point also represents scientific notation. It is stored with three parts.
A sign + or –
A mantissa
An exponent
Example: 1.6E3 stands for 1.6 ×103, i.e., it is the same as 1600.0
Complex Type
The complex data type is an immutable type that holds a pair of floats, one representing the real part and the other representing the
imaginary part of a complex number. Complex numbers are written with the real and imaginary parts joined by a + or  sign, and with
the imaginary part followed by a j.
Example:
5 + 14j
Python displays complex numbers in parentheses when they have a nonzero real part.
Example:
>>>z=5+14j
>>>[Link]
5.0
>>>[Link]
14.0
>>>print(z)
(5+14j)
>>>print((2+3j)*(4+5j))
(7+22j)
String Type
String is a sequence of characters and each character can be individually accessed using its index. Strings in python are
stored as individual characters in contiguous location, with two-way index for each location. The characters of the strings
are given two- way indices.
0, 1, 2, ----- in the forward direction and

−1, −2, −3 ----- in the backward direction.


Example:

A string can be accessed by the characters one at a time with the bracket operator. Example: subject [0] = C, subject [2] =
m, subject [-3] =t
List Type
List is a sequence data type. List is a sequence of items separated by commas and the items are enclosed in square brackets [ ]. The sequence of
values can be of any type. The values in a list are called elements or items.
Example:
>>>Address= [‘231’, ‘Carmel Nagar’, ‘Nagercoil’, ‘629004’]
>>>print Address
[‘231’, ‘Carmel Nagar’, ‘Nagercoil’, ‘629004’]
The built-in Python function type can be used to find out the type of an object.
Example:
>>>type(2)
<class ‘int’>
>>>type(3.0)
<class ‘float’>
>>>type(“Hello”)
<class ‘str’>
>>> 7>8
False
Tuple Type
A tuple is another sequence data type similar to list. A tuple consists of a sequence of items separated by commas and items are enclosed
in parenthesis ( ).

The main differences between lists and tuples are: Lists are enclosed in brackets [ ] and their elements and size can be changed, while
tuples are enclosed in parentheses ( ) and cannot be changed.

Example:

Tuple with string values

>>>T=('sun','mon','tue')

>>>print T

('sun', 'mon', 'tue')

Tuples with single character

>>>T=('P','Y','T','H','O','N')

>>>print T

('P', 'Y', 'T', 'H', 'O', 'N')


Set Type
Set is an unordered collection of items separated by commas and items are enclosed in curly brackets { }. A set is similar
to list, except that it cannot have duplicate entries (every element is unique). Once created, elements of a set cannot be
changed.

Example:
>>>x=set("PYTHON PROGRAMMING")
>>>print(x)
{'P', 'I', 'M', 'Y', 'G', 'N', 'R', 'H', 'O', 'A', 'T', ' '}
>>>type(x)
<class 'set'>
Dictionary Type
Dictionary is an unordered set of comma separated key : value pairs, within { }, with the
requirement that within a dictionary, no two keys can be the same. Example: {"name":
"Alice", "age": 30}.
>>>vowels = {‘a’:1, ‘e’:2, ‘I’:3, ‘o’:4, ‘u’:5}
>>>vowels[‘a]
1
>>>vowels[‘u’]
5
Complex Type
The complex data type is an immutable type that holds a pair of floats, one representing the real part and the other representing the
imaginary part of a complex number. Complex numbers are written with the real and imaginary parts joined by a + or  sign, and with
the imaginary part followed by a j.
Example:
5 + 14j
Python displays complex numbers in parentheses when they have a nonzero real part.
Example:
>>>z=5+14j
>>>[Link]
5.0
>>>[Link]
14.0
>>>print(z)
(5+14j)
>>>print((2+3j)*(4+5j))
(7+22j)
Boolean Type, None Type
Boolean type
A Boolean type represents special values ‘True’ and ‘False’. They are represented as 1 and 0, and can be used
in numeric expressions as value. The most common way to produce a Boolean value is with a relational
operator.
Example: 2 < 3 is True
None Type
Represents the absence of a value. The only value of this type is None. None is a special data type with a
single value. Basically, the None data type means nonexistent, not known or empty. It is used to signify the
absence of value in a situation. None supports no special operations, and it is neither False nor 0 (zero).
Example:
>>>x=None
>>>x
>>>print x
None
Complex Type
The complex data type is an immutable type that holds a pair of floats, one representing the real part and the other
representing the imaginary part of a complex number. Complex numbers are written with the real and imaginary parts
joined by a + or  sign, and with the imaginary part followed by a j.
Example:
5 + 14j
Python displays complex numbers in parentheses when they have a nonzero real part.
Example:
>>>z=5+14j
>>>[Link]
5.0
>>>z.imag14.0
>>>print(z)
(5+14j)
>>>print((2+3j)*(4+5j))
(7+22j)
OPERATORS
Operator: An operator is a symbol that represents an operation that may be performed on one or more operands.

Operands: The value that the operator operates on is called the operand.

Example: x = a + b; where x, a, b are operands.=, + are an operators.

CLASSIFICATION OF OPERATORS

Unary Operators

The unary operators operate on only one operand. Unary operators usually precede their single operand.

The unary plus and unary minus operators are used to provide sign to the operands. Example: +6, 9.

The bitwise inverse operator changes every bit i.e., 0 becomes 1 and 1 becomes 0.

Since it is the way that negative numbers are stored in the computer, it changes a positive value to negative, and a negative value to
positive.
Example:
>>>~4
5
>>>~7
6
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc. The arithmetic operators in
Python are as follows.

Floor division or Truncating division

It is denoted by a double slash, //, providing a truncated result based on the type of operands applied to.

When both operands are integer values, the result is a truncated integer referred to as integer division. Example: 7 // 5 = 1.

When at least one of the operands is a float type, the result is a truncated floating point. Example: 7 // 5.0 = 1.0 and 7.0 // 5.0 becomes 1.0.
Relational Operators
The operators used to do comparison are called relational operators. These operators always result in a
Boolean value (True or False). The relational operators are also called comparison operators. In Python, the
non-zero value is treated as true and zero value is treated as false. There is no =< or => operators in Python.
The relational operators in Python are as follows.
Logical Operators
The logical operators are used to logically relate the sub expressions. Logical operators are ‘and’,
‘or’ and ‘not’ operators. The logical operators operate according to the truth tables. These are most
often used with if and while keywords. The logical operators in Python are as follows.

x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
Output:
x and y is False
x or y is True
not x is False
Bitwise Operators
Decimal numbers are natural to humans whereas binary numbers are native to computers. Bitwise operators work with bits of a binary number. It operates bit
by bit. For example, 2 is 010 in binary and 7 is 111. The bitwise operators in Python are as follows.
a=8
b = 64
print("Bitwise AND Operator On 8 and 64 is = ", a & b)
print("Bitwise OR Operator On 8 and 64 is = ", a | b)
print("Bitwise EXCLUSIVE OR Operator On 8 and 64 is = ", a ^ b)
print("Bitwise NOT Operator On 8 is = ", ~a)
print("Bitwise LEFT SHIFT Operator On 8 is = ", a << 1)
print("Bitwise RIGHT SHIFT Operator On 64 is = ", b >> 1)
Output:
Bitwise AND Operator On 8 and 64 is = 0
Bitwise OR Operator On 8 and 64 is = 72
Bitwise EXCLUSIVE OR Operator On 8 and 64 is = 72
Bitwise NOT Operator On 8 is = -9
Bitwise LEFT SHIFT Operator On 8 is = 16
Bitwise RIGHT SHIFT Operator On 64 is = 32
Assignment Operators
Assignment operators are used to assign values to variables. a = 15 is a simple assignment operator that assigns the value 15 on the right to
the variable ‘a’on the left.

There are various compound operators in Python, a += 15 that add to the variable and later assigns the same. It is equivalent to a = a + 15.
Special Operators
Python language offers some special types of operators. They are,

a) Identity Operators.

b) Membership Operators.

a) Identity Operators

Identity operators are used to determine whether the value of a variable is of a certain type or not.

is and is not are the identity operators in Python.

They are used to check whether two values of a variables are

located on the same part of the memory or not (referring same object or not).

Two variables that are equal do not imply that they are identical.
a) Membership Operators
Membership operators are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).

in and not in are the membership operators in Python.

In a dictionary, they test for the presence of key, not the value.
OPERATORS
PRECEDENCE OF OPERATORS (ORDER OF OPERATORS)

Evaluation of expression is based on precedence of operators. When an expression contains different kinds of operators, precedence
determines which operator should be applied first. Higher precedence operator is evaluated before the lower precedence operator.

For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order.

Example: 5*(9 − 3) = 30

Since expressions in parentheses are evaluated first.

Exponentiation has the next highest precedence.

Example: 1 + 2**3 = 9, not 27 and

2 * 3**2 = 18, not 36.

Multiplication and Division have higher precedence than Addition and Subtraction.

Example: 2*31 = 5, not 4 and

6+4/2 = 8, not 5.

Operators with the same precedence are evaluated from left to right (except exponentiation).
OPERATORS
EXPRESSIONS
An expression is a combination of values, variables, and operators that evaluates to a result. A single value on its own is also considered an
expression, but an operator by itself does not form a valid expression.

Example:

A*B+C

Where *, + are operators; A, B and C are operands.

Types of expressions

Based on the position of operators in an expression

Based on the position of operators in an expression, Python supports three types of expressions. They are,

Infix expression: The operator is placed in between the operands.

Example: a=b+c

Prefix expression: The operator is placed before the operands.

Example: a=+bc

Postfix expression: The operator is placed after the operands.

Example: a=bc+
Based on the type of the result obtained on evaluating an expression

Based on the type of the result obtained on evaluating an expression, Python supports four types of expressions.

Arithmetic Expression

Arithmetic expressions involve numbers and arithmetic operators like +, –, *, / etc.

Program 2.9: Illustration of arithmetic expression ([Link])

num1 = 20

num2 = 30

Sum = num1 + num2

print 'The value of Sum is:', Sum

Output:

The value of Sum is: 50

Here, Sum = num1 + num2 is an expression which does a mathematical operation using + operator for two operands num1 and num2. Also,
num1 = 20 and num2 = 30, the assignment statements are called as expressions.
Relational/Conditional Expression
An relational expression having literals and/or variables of any valid type and relational operators.

Program 2.10: Illustration of Relational expression ([Link])

a = int(input('Enter first number') )

b =int( input('Enter first number') )

Flag = (a > b)

print ('Is %i greater than %i: %s'% (a, b, Flag) )

Output:

Enter first number 20

Enter first number 31

Is 20 greater than 31: False


Logical Expression
The logical expression having literals and/or variables of any valid type and the logical operators like and, or, or not. The logical
expression also produces a Boolean result like either True or False.

Program 2.11: Illustration of logical expression ([Link])

a = 20

b = 30

c = 23

d = 21

Flag=((a > b) and (c > d))

print ("The logical expression: ((a > b) and (c > d)) returns:", Flag)

Output:

The logical expression: ((a > b) and (c > d)) returns: False
String Expression
Python provides two string operators + and *, when combined with string operands and integers form string expressions.
With operator +, the concatenation operator, the operands should be of string type only.

With * operator, the replication operator, the operands should be one string and one integer.
Example: “and” + “then” this would result into andthen.
“and” * 2 would result into andand.
Evaluation of Expressions

In Python, evaluating an expression means the interpreter processes it and produces a result based on the values, variables, and operators
it contains.

How Python Evaluates Expressions

Parse → Python reads the expression and checks syntax.

Interpret → The expression is converted into Python bytecode.

Execute → Python follows the order of precedence and associativity rules to compute the final value.

Return → The result is produced.


String Expression

Example

x = 10

y=5

result = x + y * 2

print(result)

Evaluation process:

Replace variables with their values → 10 + 5 * 2

Apply operator precedence (multiplication before addition) → 10 + 10

Perform addition → 20

Store in result → Output: 20


STATEMENTS
A statement is an instruction that the Python interpreter can execute. There are two kinds of statements: assignment (=) and print. When a
statement is typed in the command line, Python executes it and displays the result. The assignment (=) statement does not produce a result.
The result of print statement is a value.

Assignment Statement

An assignment statement associates the name to the left of the ‘=’ symbol with the object denoted by the expression to the right of the ‘=’
symbol.

>>>Name = ‘Jovita’

>>>Age = 9

After an assignment, the values stored in the variables ‘Name’ and ‘Age’ are remembered.

>>>Name

‘Jovita’

>>>Age + 2

11
Simultaneous Assignment Statement
Python permits any number of variables to appear on the left side, separated by commas. The same number of expressions must then appear on the right
side, again separated by commas.
Example:
>>>x=10
>>>y=5
>>>sum,diff,prod=x+y,xy,x*y
>>>sum
15
>>>diff
5
>>>prod
50
The expressions are evaluated, and each is assigned to the corresponding variable. In this case, the effect is same as the three statements:
sum = x + y
diff = x – y
prod= x * y
This is termed as a ‘simultaneous assignment statement’.
Input Statement
The input statement gets input from user interactively. The purpose of input() function is to read input from the standard input (the keyboard, by
default). Using this function, we can extract integer or numeric values.

raw_input()

The purpose of raw_input() function is to read input from the standard input stream (the keyboard, by default). Using this function, we can
extract string of characters (both alphanumeric and special).

Syntax:

Example:

Name = raw_input("Enter name:")

Address = raw_input('Enter address:')

To get an integer value using raw_input() function, you have to convert the input string into these values into respective data types using int(),
float(), etc.
Print Statement
The print statement takes a series of values separated by commas. Each value is converted into a string (by implicitly invoking the str function)
and then printed.

Example:

>>>name=input(“Enter your name: “)

Enter your name: Sugitha

>>>print(‘Hello’,name,’!’)

Hello Sugitha !

The print statement recognizes a few commands, used to format input. These are termed ‘escape characters’, and are written as a character
following a backslash. The most common escape character is the newline character, \n. This moves the output to a new line. The tab character,
\t, moves the output to the next tab stop.

>>>print “one\n two\t three”

one

two three
MUTABLE AND IMMUTABLE TYPES
Sometimes we may require changing or updating the values of certain variables used in a program. However, for certain data types, Python
does not allow us to change the values, once a variable of that type has been created and assigned values.

Python data types can be classified into two types. They are,

1. Mutable type or

2. Immutable type.

Mutable (changeable) type

Variables whose values can be changed after they are created and assigned are called mutable or an object whose state or value can be
changed in place is said to be mutable type. Lists and Dictionaries are mutable, that means user can del/add/edit any value inside the lists and
dictionaries.

Immutable (unchangeable) type

Variables whose values cannot be changed after they are created and assigned are called immutable or an object whose state or value cannot
be changed in place is said to be immutable type. When an attempt is made to update the value of an immutable variable, the old value is
destroyed and a new variable is created by the same name in memory. Integers, Float, Boolean, Complex, Strings, Tuples and sets are
immutable data types.
BUILT IN FUNCTIONS

Built-in functions in Python are pre-defined functions that are always available for use without needing to import any
modules. They provide fundamental functionalities for common tasks and operations within the language. They are part of
the core Python interpreter and can be used directly in any Python program. Using built-in functions can make code more
concise and easier to understand, as their purpose is generally self-evident. These functions provide the building blocks for
more complex operations in Python programming.
Advantages of Using Built-in Functions
The following are the advantages of using built-in functions:

• The use of the built-in functions simplifies and reduces the code length and enhances the readability of the code.

• Instead of writing the same logic repeatedly, you can use these functions across different sections of the program. This not only saves time
but also helps in maintaining consistency of code.

• These functions provide a wide range of functionalities including mathematical operations, datatype conversion, and performing operations
on iterators.

• These functions have descriptive names that make the code easier to understand and maintain. Developers need not write additional
complex code for performing certain operations.
IMPORTING FROM PACKAGES
Importing from packages in Python allows the use of code defined in other modules or packages within the current program. This promotes
code organization, reusability, and maintainability.

1. Importing a Module from a Package

To import an entire module from a package, the from and import keywords are used, followed by the package name, a dot, and the module
name.

Example:

Assume a package named my_package contains a module my_module.py with a function greet().

def greet(name):
return f"Hello, {name}!"

To import and use this module:

from my_package import my_module


message = my_module.greet("Alice")
print(message)
Importing Specific Attributes from a Module within
a Package

To import only specific functions, classes, or variables from a module within a package, the from keyword is used, followed by the package and
module path, then import and the specific attribute(s).

Example:

Using the same my_package/my_module.py as above:

from my_package.my_module import greet


message = greet("Bob")
print(message)
Importing with an Alias

Aliases can be used to shorten module or attribute names for convenience, especially with
long names or to avoid name collisions. The as keyword is used for this.
Example:
# [Link]
from my_package.my_module import greet as say_hello

message = say_hello("Charlie")
print(message)
Importing All Attributes (Wildcard Import)
While generally discouraged in professional code due to potential namespace pollution and reduced readability, it's
possible to import all attributes from a module using *.
Example:
# [Link]
from my_package.my_module import *

message = greet("David") # This works directly


print(message)
When importing from a package, Python searches for the package within the directories listed in [Link]. For user-
created packages, ensuring the parent directory of the package is in [Link] or the current working directory is
crucial for successful imports.
Thank You

You might also like