Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

PythonPart I

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

PythonPart I

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

1

CONTENTS
Unit II: Computational Thinking and Programming -1 .................................................................................. 3
PART B: PROGRAMMING IN PYTHON ................................................................................................... 3
1.EXECUTION MODES OF PYTHON ........................................................................................................ 4
Mode 1 - Interactive Mode ........................................................................................................................... 4
Mode 2 - Script Mode ................................................................................................................................... 5
2.PYTHON CHARACTER SET .................................................................................................................... 6
3.TOKENS ........................................................................................................................................................ 6
3.1. Keywords ............................................................................................................................................ 6
3.2. Identifiers (Names) ............................................................................................................................ 7
3.3. Literals ................................................................................................................................................ 8
3.4. Operators .......................................................................................................................................... 10
3.4.1. Unary Operators ............................................................................................................................... 10
3.4.2 Binary Operators ............................................................................................................................... 11
3.4.2.1 Arithmetic Operators ............................................................................................................... 12
Evaluating Arithmetic Expressions (Type Conversions) ......................................... 12
Negative Number Arithmetic [Dealing with % and // in python] ........................... 16
3.4.2.2 Relational Operators ................................................................................................................ 17
3.4.2.3 Logical Operators ..................................................................................................................... 19
1. or Operator ............................................................................................................... 20
2. and Operator ............................................................................................................. 21
3. not Operator ............................................................................................................... 22
3.4.2.4 Assignment Operators ............................................................................................................... 24
3.4.2.5 Augmented Assignment Operators ......................................................................................... 24
3.4.2.6 Identity Operators .................................................................................................................... 24
Equality (==) vs Identity (is) operators ...................................................................... 25
3.4.2.7 Bitwise Operators ..................................................................................................................... 27
3.4.2.8 Membership Operators............................................................................................................ 29
3.4.3 Operator Precedence ................................................................................................................ 29
3.4.4 Operator Associativity ............................................................................................................. 30
3.5. Punctuators ................................................................................................................................ 30
4.VARIABLES ............................................................................................................................................... 31
4.1 Memory allocation in traditional programming languages .............................................................. 31

1
2

4.2 Memory allocation in Python .............................................................................................................. 31


4.3 Multiple Assignment of Variables ....................................................................................................... 32
4.4 Dynamic Typing .................................................................................................................................... 33
5.CONCEPT OF L VALUE R VALUE ....................................................................................................... 34
5.SIMPLE INPUT AND OUTPUT ............................................................................................................... 34
6.PYTHON ESCAPE CHARACTERS ........................................................................................................ 38
7.USE OF COMMENTS ............................................................................................................................... 39
8.DATA TYPES IN PYTHON ...................................................................................................................... 40
8.1 Numbers ................................................................................................................................................ 40
8.2 Strings .................................................................................................................................................... 42
8.3 Lists ........................................................................................................................................................ 44
8.4 Sets ......................................................................................................................................................... 44
8.5 Dictionary .............................................................................................................................................. 44
8.6 None Type.............................................................................................................................................. 45
9.MUTABLE & IMMUTABLE TYPES ...................................................................................................... 45
Exception in mutability .............................................................................................................................. 46
9.Errors in Python .......................................................................................................................................... 47
9.1. Compile-Time Errors : i)Syntax Error ii)Semantics Error........................................................... 47
9.2.Logical Errors ....................................................................................................................................... 47
9.3.Run-Time Errors .................................................................................................................................. 48

2
3

Unit II: Computational Thinking and Programming -1


PART A: THEORY (PPT in GC and flow charts to be learnt from text)

PART B: PROGRAMMING IN PYTHON

3
4

1.EXECUTION MODES OF PYTHON


Mode 1 - Interactive Mode

Problems with interactive mode of python

4
5

Mode 2 - Script Mode

Steps to open a python file in Script Mode


1. Open Python Shell
2. Click on ‘File’ option on the left menu.
3. An untitled python file opens up to type the code into it.
4. Type the code and save the file with a proper file name.

5
6

2.PYTHON CHARACTER SET


A valid set of characters recognized by the Python language. These are the characters we can use during
writing a script in Python. Python supports all ASCII / Unicode characters that includes letters,digits,special
symbols, white spaces, other characters.

3.TOKENS
• A token is the smallest individual unit in a python program. All statements and instructions in a program
are built with tokens.
• Python has following tokens:
1. Keywords
2. Identifiers (Names)
3. Literals
4. Operators
5. Punctuators

3.1. Keywords
Keywords are words that have some special meaning or significance in a programming language. They can’t
be used as variable names, function names, or any other random purpose. They are used for their special
features. In Python we have 33 keywords.

6
7

3.2. Identifiers (Names)


Identifiers are the names given to any variable, function, class, list, methods, etc. for their identification. Python
is a case-sensitive language and it has some rules and regulations to name an identifier. Identifier starts with a
capital letter (A-Z), a small letter (a-z) or an underscore ( _ ). It can’t start with any other character. Digits can
also be a part of identifier but can’t be the first character of it. Any other special characters or whitespaces are
strictly prohibited in an identifier. An identifier can’t be a keyword.

7
8

3.3. Literals
Literals are the fixed values or data items used in a source code. Python supports different types of literals such
as:
(i) String Literals: The text written in single, double, or triple quotes represents the string literals in Python.
For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to write multi-line strings.

(ii) Character Literals:


Character literal is also a string literal type in which the character is enclosed in single or double-quote

(iii) Numeric Literals: These are the literals written in form of numbers.

Python supports the following numerical literals:

a) Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t include
fractional parts. It can also include binary, decimal, octal, hexadecimal literal.

8
9

b) Float Literal: It includes both positive and negative real numbers. It also includes fractional parts.

c) Complex Literal: It includes a+bi numeral, here a represents the real part and b represents the complex
part.

d) Boolen Literals: Boolean literals have only two values in Python. These are True and False.

(e) Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no values, or the absence
of value.

(f) Literals Collections: Literals collections in python includes list, tuple, dictionary, and sets.

9
10

List: It is a list of elements represented in square brackets with commas in between. These variables can be of
any data type and can be changed as well.
Tuple: It is also a list of comma-separated elements or values in round brackets. The values can be of any data
type but can’t be changed.
Dictionary: It is the unordered set of key-value pairs.
Set: It is the unordered collection of elements in curly braces ‘{}’.

3.4. Operators
Operators are tokens that triggers some computation or action when applied to variables and other objects in an
expression.
They are classified into two as follows:

3.4.1. Unary Operators


Operators that act on one operand are called unary operators.

a. Unary + b. Unary –

10
11

c. ~ bitwise complement

d. not (logical negation)

not operator in Python performs logical negation to Boolean expression. You have to mention an expression or
a variable that has a boolean value associated with it. If the check is True, not will evaluate it as False and vice
versa. The not in Python is considered one of the basic operators used in Python, along
with AND and OR operators. Its function is similar to the inverter gate used in Digital Electronics.

3.4.2 Binary Operators


i. Arithmetic Operators

ii. Relational Operators

iii. Logical Operators

iv. Assignment Operators

v. Augmented Assignment Operators

vi. Identity Operators

vii. Bitwise Operators

viii. Membership Operators

11
12

3.4.2.1 Arithmetic Operators

• Booleans such as True/False internally takes 1 and 0 as the values. True+1 =2


• + is used as concatenation operator when used in string, tuple, list
• * as replication operator in strings
• / operators return float result

Evaluating Arithmetic Expressions (Type Conversions)

The act of changing an object’s data type is known as type conversion. The Python interpreter automatically
performs Implicit Type Conversion. Python prevents Implicit Type Conversion from losing data.
The user converts the data types of objects using specified functions in explicit type conversion, sometimes
referred to as type casting. When type casting, data loss could happen if the object is forced to conform to a
particular data type.
Implicit conversion (Coercion) : Compiler does it without programmer’s involvement
If both operands are standard numeric types, the following coercions are applied.
1. If one operand is complex number, the other one is also converted to complex number.
2. If one operand is float number, the other one is also converted to float number.

12
13

3. No conversion if both the operands are integers.

Example: (Sumita Arora Page 235-36)

Find the output and data type of the two expressions given below:

Expression 1 :

13
14

Expression 2:

Typecasting: Explicit conversion of an operand to specific type is called typecasting.

S.A Page 240

14
15

15
16

Negative Number Arithmetic [Dealing with % and // in python]

1.FLOOR DIVISION
Note: a//b <= a/b

Example 1: -7//4

Example 2: 7//-4

Normal division gives answer as -1.75 [ -7/4 and also for 7/-4]

So floor division’s answer should look for an integer lesser than it on a number line.

Hence answer is -2 for both examples. [ -2 is less than -1.75 ]

2.MODULO DIVISION

16
17

3.4.2.2 Relational Operators


Works with all data types. Returns boolean True or False based on the result.

1. Numeric Types - When value is a float


• values are compared after removing trailing zeros after decimal point.
• Example : 4 and 4.0 are treated equal.
2. Strings are compared based on lexicographical ordering (ascending/dictionary order) based on
ASCII value.
Example : a is greater than A (ASCII for a is 97 and for A it is 65)
print(ord(‘A’)) gives the ASCII value
3.Non-printing characters such as space also has ASCII values associated with it.
print (‘Apple’ > ‘ Apple’ ) : Gives True as the output
< Space in the beginning of Apple in RHS has ASCII of 32 >
4.Two lists/tuples are equal if they have same elements in same order.
print ([1,2,3,4] == [4,3,2,1])
Output: False
5.Boolean True and False takes numeric 1 and 0.
6.== should not be used for floating point values as due to precision limit, internal rounding off takes place.

17
18

Precision defines how many bits will be occupied in memory to store the number. The more bits are made
available, the more digits after the decimal point can be stored before rounding occurs.

They have lower precedence than all the arithmetic operators.

18
19

Y+X>Y*2 will be evaluated as : (Y+X)>(Y*2)

3.4.2.3 Logical Operators


Logical operators are the Boolean logical operators (or,and,not) that refer to the ways the relationships among
the values can be connected.

19
20

1. or Operator

It combines two expressions which make its operands in the following ways:
i)Relational Expressions as operands.

ii)Numbers/Strings/Lists as operands

20
21

2. and Operator

It combines two expressions which make its operands in the following ways:
i)Relational Expressions as operands.

21
22

ii)Numbers/Lists/String as operands.

3. not Operator

22
23

Chained Comparison Operators (incorporating and during evaluation)

23
24

3.4.2.4 Assignment Operators

Assignment operators are used to assign values to variables.


Assign value of right side of expression to left side operand.
Example: x = y + z

3.4.2.5 Augmented Assignment Operators

An augmented assignment is generally used to replace a statement where an operator takes a variable as one of
its arguments and then assigns the result back to the same variable. This can be used only for numbers and not
for mutable datatypes.
A simple example is x += 1 which is expanded to x = x + 1 .

3.4.2.6 Identity Operators


Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object,
with the same memory location:

24
25

Equality (==) vs Identity (is) operators

When 2 variables are referring to the same value, the is operator returns True. Then the == operator also
returns True.

25
26

Opposite (if equal need not be in same memory location) hold true in some cases. Even though they are equal
they need not be in same memory location.

Few cases where python create two different objects even though they store same value:
1. Input of string from console.

2. Input of float from console.

4.Complex numbers < not in all cases> page 224

3. When integers are very big.

26
27

3.4.2.7 Bitwise Operators

Bitwise and

Biwise or

27
28

Biwise xor

>> operator (read as Right Shift / Bit wise Right Shift)

<< operator (read as Left Shift / Bit wise Left Shift)

28
29

3.4.2.8 Membership Operators

There are two membership operators in Python i.e., "in" and "not in". The "in" operator is used to test whether
a value is a member of a sequence.

3.4.3 Operator Precedence

29
30

3.4.4 Operator Associativity

Refer the below links for few examples.


https://www.geeksforgeeks.org/precedence-and-associativity-of-operators-in-python/
https://www.tutorialspoint.com/python/operators_precedence_example.htm
https://www.w3schools.com/python/python_operators.asp

3.5. Punctuators

30
31

4.VARIABLES
4.1 Memory allocation in traditional programming languages

4.2 Memory allocation in Python

31
32

Example :When age=15 is changed to age=20

4.3 Multiple Assignment of Variables

1)Assigning same value to multiple variables.


a=b=c=10 [ all 3 labels will refer to same memory location]
2)Assigning multiple values to multiple variables.[In a single line]
y,z=10,20 [values are assigned order wise.y gets 10 and z gets 20]
Swapping of values given above can be done as below:
y,z=z,y [Now y=20 and z=10]

32
33

Output Prediction Questions


Q1) p,q=3,5
q,r=p-2,p+2
print(p,q,r)
==================================================================
NOTE: Expressions separated by commas are evaluated from left to right and assigned in same order.
Q2) x=10
y,y=x+2,x+5
print(x,y)
Q3)x,x=20,30
y,y=x+10,x+20
print(x,y)

4.4 Dynamic Typing


A variable pointing to a value of certain type(data type) can be made to point to a value/object of different type
as follows:
A=10
Print(A)
A=“PYTHON”
Print(A)
33
34

Output:
10
PYTHON

5.CONCEPT OF L VALUE R VALUE


Lvalue and Rvalue refer to the left and right side of the assignment operator.
age = 39
The value 39 is pulled or fetched (Rvalue) and stored into the variable named age (Lvalue); destroying the
value previously stored in that variable.
voting_age = 18
age = voting_age
If the expression has a variable or named constant on the right side of the assignment operator, it would pull or
fetch the value stored in the variable or constant.
The value 18 is pulled or fetched from the variable named voting_age and stored into the variable named age.
age < 17
If the expression is a test expression or Boolean expression, the concept is still an Rvalue one. The value in the
identifier named age is pulled or fetched and used in the relational comparison of less than.

5.SIMPLE INPUT AND OUTPUT

5.1Input using the function input()


Built-in function input() can be used to get the input from the user interactively as follows:

34
35

• input() always returns value of string data type hence below error occurs.Even though the age entered is a
number,input() returns it as a string value.

• Reading numbers(int or float) using input()

35
36

• Possible errors while reading numbers (int or float) using input()

36
37

5.2 Output using the function print()

Syntax: print(object(s), sep, end)


• Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get
converted into strings.
• sep: It is an optional parameter used to define the separation among different objects to be printed. By
default an empty string(“”) is used as a separator.
• end: It is an optional parameter used to set the string that is to be printed at the end. The default value
for this is set as line feed(“\n”).
➢ It auto converts the items to string.
➢ Return type of print function is “None”

37
38

6.PYTHON ESCAPE CHARACTERS

Video Links to understand how carriage return and backspace (\r,\b) works.
[ Few python versions/systems donot support them]
• What is \r in python?
• What is \b in python?

38
39

7.USE OF COMMENTS
Comments can be used to :
1. explain Python code.
2. make the code more readable.
3. prevent execution when testing code.
Types :
1. Single Line Comment

2. Multiline Comment

3. Inline Comment
39
40

8.DATA TYPES IN PYTHON

8.1 Numbers

8.1.1) Integers:
Positive or Negative numbers without fractional part.
Types of integers
a) Signed : Used to represent positive and negative numbers.
b) Boolean: Represents truth values True (1) or False(0).
Printing boolean equivalents of 0 and 1 is as follows:
• print(bool(0)) #Output is False
• print(bool(1)) #Output is True
Conversion of the boolean values to string is as follows:
• str(False) # Output is ‘False’
• str(True) # Output is ‘True’

40
41

8.1.2) Floating Point Numbers:

8.1.3) Complex Numbers

41
42

8.2 Strings
• A String is a data structure in Python that represents a sequence of characters.
• It is an immutable data type, meaning that once you have created a string, you cannot change the
components in it.
• Strings are used widely in many different applications, such as storing and manipulating text data,
representing names, addresses, and other types of data that can be represented as text.
• Creating a String in Python: Strings in Python can be created using single quotes or double quotes or
even triple quotes.

42
43

The index value of the first element in a string in negative indexing is –(lengthofthestring) : -6
The index value of the second element in a string in negative indexing is –(lengthofthestring-1): -(6-1)
Eg: B’s index value in negative indexing is -6. 6 is the length of the string(no of elements in the string)

43
44

8.3 Lists
• Lists are used to store multiple items in a single variable.
• Lists are created using square brackets.
• thislist = ["apple", "banana", "cherry"]
print(thislist)
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item has index [1] etc.
• When we say that lists are ordered, it means that the items have a defined order, and that order will not
change.
• If you add new items to a list, the new items will be placed at the end of the list.
• The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
• Since lists are indexed, lists can have items with the same value.
• To determine how many items a list has, use the len() function:
• A list can contain different data types:
• list1 = ["abc", 34, True, 40, "male"]

8.4 Sets
myset = {"apple", "banana", "cherry"}
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data.
A set is a collection which is unordered, unchangeable*, and unindexed.
* Note: Set items are unchangeable, but you can remove items and add new items.
Sets are written with curly brackets.

8.5 Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values.

44
45

8.6 None Type


The None keyword is used to define a null value, or no value at all.
None is not the same as 0, False, or an empty string.
None is a data type of its own (NoneType) and only None can be None.

9.MUTABLE & IMMUTABLE TYPES


IMMUTABLE TYPES: int,float,boolean,string,tuple
They can never change a value in place.

45
46

MUTABLE TYPES: list,dictonary,sets

Exception in mutability
We know that a tuple in Python is immutable. But the tuple consists of a sequence of names with unchangeable
bindings to objects.
Consider a tuple
tup = ([3, 4, 5], 'myname') # this tuple has list as first element and string as second.
Strings are immutable so we can’t change their value. But the contents of the list can change. The tuple itself
isn’t mutable but contains items that are mutable.

46
47

9.Errors in Python
Error (bug)
Anything in the code that prevents the program from compiling and running correctly.
Debugging
The process of identifying and removing errors from computer hardware or software:
Types of Errors:

9.1. Compile-Time Errors : i)Syntax Error ii)Semantics Error

9.2.Logical Errors
The program to behave incorrectly, but they do not usually crash the program. Unlike a program with syntax
errors, a program with logic errors can be run, but it does not operate as intended.

47
48

9.3.Run-Time Errors
Errors that are thrown once the code is run are under the class of runtime errors. These errors will always
include an error message printed to the interpreter.

48

You might also like