0% found this document useful (0 votes)
50 views

Unit 2 - DATA, EXPRESSIONS, STATEMENTS

The document summarizes key concepts in Python including: 1. Python has two modes - interpreter mode which runs .py files and interactive mode which provides immediate feedback. 2. Debugging involves identifying and removing syntax errors, logical errors, and runtime errors. 3. Python breaks code into tokens like keywords, identifiers, literals, delimiters, and operators. Keywords are reserved words and identifiers name variables.

Uploaded by

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

Unit 2 - DATA, EXPRESSIONS, STATEMENTS

The document summarizes key concepts in Python including: 1. Python has two modes - interpreter mode which runs .py files and interactive mode which provides immediate feedback. 2. Debugging involves identifying and removing syntax errors, logical errors, and runtime errors. 3. Python breaks code into tokens like keywords, identifiers, literals, delimiters, and operators. Keywords are reserved words and identifiers name variables.

Uploaded by

Subiksha M
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 71

DATA, EXPRESSIONS,

STATEMENTS

UNIT 2
UNIT 2

Python interpreter and interactive mode, debugging; values and types: int, float,
boolean, string , and list; variables, expressions, statements, tuple assignment,
precedence of operators, comments; Illustrative programs: exchange the values
of two variables, circulate the values of n variables, distance between two points.
PYTHON INTERPRETER AND INTERACTIVE MODE
Python has two basic modes: interpreter and interactive
modes.
The interpreter mode is the mode where the scripted and
finished .py files are run in the Python interpreter.
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 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.
Traditionally, python programs are stored in a file with the
The first three lines contain information
about the interpreter and the operating extension .py . Consider the file sum.py. Once the file is
system it is running on. created, start the python system and give the file name on the
command line, as follows:
The version number is 3.6.0. It begins with 3,  

if the version is Python 3. It begins with 2, if python sum.py


the version is Python 2.  

It will give the output as,


The last line >>>is a prompt (chevron) that  
indicates that the interpreter is ready to enter >>>python sum.py
code. If the user types a line of code and hits Enter 2 numbers
Enter, the interpreter displays the result: 6
3
The sum is 9
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.
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.
DEBUGGING
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”.
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.
>>> 
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.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assort else import pass  
break except in raise  
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
Escape sequence Meaning
\newline Backslash and newline ignored
\\ Backslash( \ )
\’ Single quote (’)
\” Double quote (”)
\a ASCII Bell (BEL)
\b ASCII Backspace (BS)
\f ASCII Formfeed (FF)
\n ASCII Linefeed (LF)
\r ASCII Carriage Return (CR)
\t ASCII Horizontal Tab (TAB)
\v ASCII Vertical Tab (VT)
\000 Character with octal value 000
\xhh Character with hex value hh
LITERALS
A literal is a sequence of one of more characters that stands for itself. There are two important
types of literals. They are,
1. Numeric Literals
2. String Literals
Numeric Literals
 A numeric literal is a literal containing only the digits 0 – 9, an optional sign character ( + or  ),
and a possible decimal point.
Commas are never used in numeric literals. If a numeric literal contains a decimal point, then it
denotes a floating-point (float) value. Example: 12.35.
If a numeric literal does not contain a decimal point, then it denotes an integer (int) value.
Example: 10.
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.
String Literals
 String literals or strings represent a sequence of characters.
 Example:
 'Hello' 'Jovita, Jesvita' "231, Carmel Nagar, 629004"
In Python, string literals may be delimited (surrounded) by a matching pair of either single (') or
double (") quotes.
 Example:
 >>>print('Welcome to Python!')
Welcome to Python!
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.
Delimiters of Python

Delimiters Classification

( ) [ ] { }     Grouping

. , : ; @       Punctuation

= += = *= /= //= %= **= Arithmetic assignment/ binding

&= != ^= <= >>=       Bit wise assignment/ binding


VALUES
Values are the basic units of data, like a number or a string that a program manipulates.
Examples: 2, 42.0 and ‘Hello, World!’.
These values belong to different types: 2 is an integer, 42.0 is a floating point number, and
‘Hello, World!’ is a string.
TYPES
Data type of an object determines what values it can have and what operations can be
performed on it. 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, Boolean and None types.
Numbers
 Number data types store numeric values. Python has three number types: integer numbers, floating point numbers, and complex
numbers.
 a) 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 9, 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
>>>z.real
5.0
>>>z.imag
14.0
>>>print(z)
(5+14j)
>>>print((2+3j)*(4+5j))
(7+22j)
String Type
A string type represents sequence of characters. In Python strings can be created using single
quotes, double quotes and triple quotes.
When using triple quotes, strings can specify multi-line string without using escape character.
Example:
 Using Single Quotes: ‘HELLO’
Using Double Quotes: “HELLO”
Using Triple Quotes: ```Hello Every One.
Welcome to Python Programming.```
List Type
List is a sequence data type. A list represents a sequence of values. In Python, these values are
assigned by placing them within square braces and separating them by commas. 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: >>>bool(1)
 >>>type(2) True
<class ‘int’> >>>bool(0)
>>>type(3.0) False
<class ‘float’> >>>type([1,2,3])
>>>type(“Hello”) <class ‘list’>
<class ‘str’>
>>> 7>8
False
Tuples
 A tuple is another sequence data type similar to list. A tuple consists of a sequence of elements separated by commas.
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 updated.
 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')
Sets
 A set is an unordered collection of items. Every element is unique and cannot be changed. A set
is created by placing all the items (elements) inside curly braces {}, separated by comma.
 Example:
 >>>x=set("PYTHON PROGRAMMING")
>>>print(x)
{'P', 'I', 'M', 'Y', 'G', 'N', 'R', 'H', 'O', 'A', 'T', ' '}
>>>type(x)
<class 'set'>
Illustration of set type (settype.py)
 a = {5,2,3,1,4}
 # printing set variable
print("a = ", a)
 # data type of variable a
print(type(a))
Output:
 a = {1, 2, 3, 4, 5}
<class 'set'>
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
Illustration of Boolean type (booltype.py)  Output:
 x = (1 = = True)  x is True
y = (1 = = False) y is False
a = True + 4 a: 5
b = False + 10 b: 10
print("x is", x) In Python, True represents the value as 1 and
False as 0. The value of x is True because 1 is
print("y is", y) equal to True. And, the value of y is False
print("a:", a) because 1 is not equal to False.

print("b:", b)
None Type
None is a special data type. Basically, the None data type means nonexistent, not known or
empty. This is a unique value that may be used where it is required but there is no obvious
value. This value has its own type and is the only instance of that type.
 Example:
 >>>x=None
>>>x
>>>print x
None
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.
Declaring Variables
Variables are declared according to the Python character sets. A variable is declared to hold some value.
Variables are examples of identifiers.
 
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 name.
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.

variable = expr
 
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
>>>(a,b,c,d)
(10,10,10,10)
EXPRESSIONS
In Python, most of the lines or statements are written in the form of expressions. Expressions
are made up of operators and operands. Expressions are evaluated according to operators.
 An expression is a combination of values, variables, and operators. Expressions combine
variables and constants to produce new values. A value by itself is considered an expression.
 Expressions, most commonly, consist of a combination of operators and operands. Operand is
the value on which operator is applied. These operators use constants and variables to form an
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
 This type of expression just do mathematical operations like +, –, *, / etc.
 Illustration of arithmetic expression (arithmetic.py)
 num1 = 20
num2 = 30
Sum = num1 + num
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
 This expression compares two statements using relational operators like >, <, >=, <=, etc.
Illustration of Relational expression (relational.py)
 a = input('Enter first number')
b = 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
 Here, two values 20 and 31 are compared with a relational operator (>) and stored a result into the variable Flag.
Logical Expression
 The logical expression uses the logical operators like and, or, or not. The logical expression also produces a Boolean result
like either True or False.
Illustration of logical expression (logical.py)
 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
 Here, the logical expression combines two relational expressions with a logical operator and i.e., the result of (a > b) is
False and the result of (c > d) is True. So, the final result is False.
Conditional Expression
 The conditional expression is also called relational expression. This expression is used with branching (if, if-
else, etc.) and looping (while) statement. A conditional expression always produces two results either True
or False depending upon the condition.
Illustration of conditional expression (conditional.py)
 Age = input('Enter your age')
if (Age >= 18):
print "You can vote."
else:
print "You can't vote."
 Output:
 Enter your age 25
You can vote.
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 do 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.
 Example:
  >>>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’.
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
 Escape characters can also be used to embed a quote mark within a quoted string.
 >>>print ‘don\’t do that’
don’t do that
TUPLE
 In Python, a tuple may be defined as a finite, static list of numbers or string. A tuple is similar to a list and it contains
immutable sequence of values separated by commas.
 The values can be of any type, and they are indexed by integers. Unlike lists, tuples are enclosed within parentheses
( ). The built-in functions like max() and min() stores values in the form of tuple.
 Example:
 >>>t = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
>>>max(5,8,9)
9
>>>min(9,99,999)
9
Creating a tuple
 To create a tuple with a single element, finally comma is to be included.
  >>>t1 = ‘a’,
 Another way to create a tuple is the built-in function tuple with no argument that creates an empty tuple.
  >>>t = tuple()
>>>t
()
 If the argument is a sequence (string, list or tuple), the result is a tuple with the elements of the sequence:
  >>>t = tuple(‘Jovita’)
>>>t
(‘J’, ‘o’, ‘v’,’i’, ‘t’, ‘a’)
Operations on tuple
 The bracket operator indexes an element.
 >>>t=(‘a’,‘e’,‘i’,‘o’,‘u’)
>>>t[0]
‘a’
>>>t[3]
‘o’
The slice operator selects a range of elements.
 >>>t[1:3]
(‘e’, ‘i’)
 The elements in tuples cannot be modifiable, because tuples are immutable. If we try to modify one of the elements of the
tuple, it gives an error.
 >>>t[0]=‘A’
Traceback (most recent call last):
File “<pyshell#6>”, line 1, in <module>
t[0]=‘A’
TypeError: ‘tuple’ object does not support item assignment
The elements in tuple can be replaced with one another.
 >>>t=(‘A’,)+t[1:]
>>>t
(‘A’, ‘e’, ‘i’, ‘o’,‘u’)
 The relational operators work with tuples and other sequences. Python starts by comparing the
first element from each sequence. If they are equal, it goes on to the next element, and so on,
until it finds the element that differs. Subsequent elements are not considered (even if they are
really big).
 >>>(0, 1, 2) < (0, 3, 4)
True
>>>(0, 1, 2000000) < (0, 3, 4)
True
Difference between lists and tuples
 
Lists are enclosed in brackets [ ] and their elements and size can be changed, while tuples are
enclosed in ( ) and cannot be updated.
Tuples can be thought of as read only lists. Like list, to initialize a tuple, one can enclose the
values in parentheses and separates them by commas.
TUPLE ASSIGNMENT
Tuple assignment is an assignment with a sequence on the right side and a tuple of variables on
the left. The right side is evaluated and then its elements are assigned to the variables on the
left.
 Example:
 >>>T1=(10,20,30)
>>>T2=(100,200,300,400)
>>>print T1
(10, 20, 30)
>>>print T2
(100, 200, 300, 400)
>>>T1,T2=T2,T1 # swap T1 and T2
>>>print T1
(100, 200, 300, 400)
>>>print T2
(10, 20, 30)
 The left side is a tuple of variables; the right side is a tuple of expressions. Each value is assigned
to its respective variable. All the expressions on the right side are evaluated before any of the
assignments.
 
The number of variables on the left and the number of values on the right have to be the same.
 Example:
 >>>T1=(10,20,30)
>>>T2=(100,200,300)
>>>t3=(1000,2000,3000)
>>>T1,T2=T2,T1,t3
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
T1,T2=T2,T1,t3
ValueError: too many values to unpack
Here, two tuples are in the left side and three tuples are in right side. So it gives errors.
Thus, it is required to have same number of tuples in both sides to get the correct result.
 Example:
 >>>T1,T2,t3=t3,T1,T2
>>>print T1
(1000, 2000, 3000)
>>>print T2
(10, 20, 30)
>>>print t3
(100, 200, 300)
PRECEDENCE OF OPERATORS (ORDER
OF OPERATORS)
When an expression contains more than one operator, the order of evaluation depends on the
order of operations.
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.
PEMDAS
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).
Operator Precedence in Python
COMMENTS
 A comment statement contains information for persons reading the program.
Comments make the program easily readable and understandable by the programmer and non-
programmer who are seeing the code.
Comment statements non-executable statements so they are ignored during program execution.
They have no effect on the program results.
The program lines begin with the hash sign, #.
In Python, this symbol is used to denote a comment statement.
 Example:
 # swap.py
# Swapping the values of a two variable program
# written by G. Sugitha, April 2018
FLOW OF EXECUTION
The order in which statements are executed during a program run is called flow of execution. A
function should be defined before its first use.
 Consider the program
 n1 = input("Enter first number:")
n2 = input("Enter first number:")
Sum = n1 + n2
print "Sum of %d and %d is: %d"% (n1, n2, Sum)
 From the above four lines, the flow of execution will start from line 1 till line 4. If there are any
branching or looping statements used in a program, then the flow of execution may depend on
the condition.
MUTABLE AND IMMUTABLE TYPES
In Python, the data objects hold values in two forms. They are,
1. Mutable type or
2. Immutable type.
 Mutable (changeable) type
 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 string and tuple.
 Immutable (unchangeable) type
 An object whose state or value cannot be changed in place is said to be immutable type. Strings
and Tuples are immutable, that means user cannot del/add/edit any value inside the string and
tuple.
INDENTATION
Whitespace at the beginning of the line is called indentation. These whitespaces or the
indentation are very important in Python.
In a Python program, the leading whitespace including spaces and tabs at the beginning of the
logical line determines the indentation level of that logical line.
The level of indentation groups statements to form a block of statements.
This means that statements in a block must have the same indentation level.
Python very strictly checks the indentation level and gives an error if indentation is not correct.
Illustration of indentation (voting.py)
 age = int(input("Enter age: "))
if (age>18):
print('Eligible for voting')
else:
print('Not Eligible for voting')
 Like other programming languages, Python does not use curly braces ( { . . .} ) to indicate blocks
of code. It uses only indentation to form a block. All statements inside a block should be at the
same indentation level.
INPUT FUNCTION
input() Function
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.
 Syntax:
<variable>= input([prompt])
 
 
Here,
 The prompt is an optional parameter.
The prompt is an expression that serves to prompt the user for input. This is almost always a
string literal which is enclosed within quotes (single or double) with parentheses.
The result of input() function is returned a numeric value, and assigns to a variable.
When the input() function executes, it evaluates the prompt and displays the result of the prompt on
the screen.
Example:
 >>>num1 = input("Enter first number: ")
Enter first number: 20
>>>num2 = input("Enter second number: ")
Enter second number: 40
>>>print "Sum is:", num1+num2
Sum is: 60
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:
<variable> = raw_input(['prompt'])
 
 

Here,
 This function reads a line from input (i.e. the user) and returns a string by stripping a trailing newline.
It always returns a string.
 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.
Illustration of raw_input function
 
Num1 = int(raw_input("Enter first number:"))
Num2 = int(raw_input("Enter second number:"))
print 'The sum of', Num1, ' and', Num2, ' is', Num1+Num2
 
Output:
 
Enter first number: 24
Enter second number: 67
The sum of 24 and 67 is 91
Thank You

You might also like