CS1033 Programming Fundamentals Semester 1 (2024 Intake) [Jan – Jun 2025] Lecture 2 Sanath Jayasena Dept. of Computer Science & Engineering Outline Lecture 2 • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Sanath Jayasena Dept. of Computer Science & Engineering 2 References • CS1033 Notes, Part A – Chapters 2, 3 – Corresponding Jupyter Notebooks • Additional online resources – Python Tutorials and Documentation • https://docs.python.org/3.11/tutorial/ • https://www.tutorialspoint.com/python3/ • https://docs.python.org/3.11/ • Visualize Python execution: http://pythontutor.com/visualize.html Sanath Jayasena Dept. of Computer Science & Engineering 3 Outline Lecture 2 PART 1 Sanath Jayasena • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Dept. of Computer Science & Engineering 4 Python Basic Data Types • Three numeric types – Integers → int – Floating-point (real) numbers → float – Complex numbers → complex • Boolean type → bool • String type → str (sub-type of int) … and other (compound) types • → list , tuple , dict , set ,… basic data structures Sanath Jayasena Dept. of Computer Science & Engineering 5 Examples >>> a="abc" + 'xyz' >>> a 'abcxyz' >>> type(a) <class 'str'> >>> b=97 >>> type(b) <class 'int'> >>> type(97.0) <class 'float'> Sanath Jayasena >>> d = 5 > 4 >>> d True >>> type(d) <class 'bool'> >>> e = 3 + 4j >>> type(e) <class 'complex'> Dept. of Computer Science & Engineering 6 Data Formats Data Type int float Sanath Jayasena Examples -96 (decimal) 0x3bfe9 (hexadecimal) -0o3702 (octal) 0b100101 (binary) 9.01 -9. 32.3e+18 -321.54e100 8734.098E-12 Dept. of Computer Science & Engineering 7 Objects • Objects are Python’s abstraction for data – Data in a program represented by objects or as relations between objects • Every object has – Identity : address in memory; never changes; check with id( ) function or “is” operator – Type (class) : check with type( ) function; possible operations, values depend on type – Value : value of some objects can change Sanath Jayasena Dept. of Computer Science & Engineering 8 Object Names (Variables) • Can associate a name with an object • An object may have 0, 1 or more names • A name is also called a reference, an identifier or a variable • Python variable naming rules: – Must begin with a letter (a - z, A - Z) or “_” – Then, can have letters, digits or _ only – Variable names are case sensitive – Keywords (reserved words) cannot be used Sanath Jayasena Dept. of Computer Science & Engineering 9 Outline Lecture 2 PART 2 Sanath Jayasena • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Dept. of Computer Science & Engineering 10 Mutable vs Immutable Objects • Value can change → mutable object • Value cannot change → immutable object • Mutability depends on type – Numbers, strings, tuples, bytes, frozenset, … → immutable – Lists, dictionaries, sets, user-defined classes, …→ mutable – Note: we have seen only numbers and strings; we will cover lists, tuples, dictionaries later. Sanath Jayasena Dept. of Computer Science & Engineering 11 Immutability of Numbers [1]>>> b = 97 [2]>>> c = b [3]>>> c 97 [4]>>> id(b) 1638394498288 [5]>>> id(c) 1638394498288 Sanath Jayasena [6]>>> b = 98 [7]>>> b 98 [8]>>> c 97 [9]>>> id(b) 1638394498320 [10]>>> id(c) 1638394498288 Dept. of Computer Science & Engineering 12 Example explained: >>> b = 97 >>> id(b) 1638394498288 >>> c = b >>> b = 98 >>> id(b) 1638394498320 Sanath Jayasena b Memory contents Memory address 97 1638394498288 c c b Memory contents Memory address 97 1638394498288 98 1638394498320 Dept. of Computer Science & Engineering 13 Immutability of Strings [1]>>> a 'abcxyz' [2]>>> id(a) 1638435666992 [3]>>> s = a [4]>>> id(s) 1638435666992 [5]>>> a[2] 'c' [6]>>> a is s True Sanath Jayasena [7]>>> s = "pqr" [8]>>> s 'pqr' [9]>>> id(s) 1638435653936 [10]>>> a[4] = "W" Traceback (most recent call last): File "<pyshell#159>", line 1, in <module> a[4] = "W" TypeError: 'str' object does not support item assignment Dept. of Computer Science & Engineering 14 Mutability of Lists [1]>>> x = [3,4,'mno'] [7]>>> id(y) [2]>>> x 1638435730752 [3, 4, 'mno'] [8]>>> x[1] = "jk" [3]>>> y = x [9]>>> x is y [4]>>> y True [3, 4, 'mno'] [10]>>> y [5]>>> y is x [3, 'jk', 'mno'] True [11]>>> x [6]>>> id(x) [3, 'jk', 'mno'] 1638435730752 Sanath Jayasena Dept. of Computer Science & Engineering 15 Exercise 1 • Explain the following >>> a = 9 >>> b = 9 >>> a is b True >>> a = 1000 >>> b = 1000 >>> a is b False Try the above with strings, first with a short string (e.g., x = “abcd” and y = “abcd”) and then with a much longer string Sanath Jayasena Dept. of Computer Science & Engineering 16 Exercise 2 • What do the following built-in functions do? int() float() complex() str() chr(), ord() hex(), oct(), bin() Sanath Jayasena Dept. of Computer Science & Engineering 17 Outline Lecture 2 PART 3 Sanath Jayasena • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Dept. of Computer Science & Engineering 18 Input, Output • Output: Use the built-in function print() • “print()” function – Evaluates each argument (comma-separated expression) in turn and writes resulting object to standard output (display) – Object first converted to a string if needed – “\n” (newline) character written at the end • What if you don’t need “\n” at the end? – print(objects, sep=' ', end='\n’) • Prints objects to display, separated by sep and followed by end Sanath Jayasena Dept. of Computer Science & Engineering 19 Input, Output • Input: Use built-in function input()to read input from keyboard (standard input) • input([prompt]) – Reads a line from standard input, converts it to a string (removing trailing newline) and returns it – If the prompt argument is present, it is written to standard output without a trailing newline Sanath Jayasena Dept. of Computer Science & Engineering 20 Example 1 # Program-2.2 s = input("Enter your input: ") print ("Received input is:", s) Here is a sample run of the above program: Enter your input: Hello Python Received input is: Hello Python Sanath Jayasena Dept. of Computer Science & Engineering 21 Example 2 # Program-2.3 s = input("Enter your input: ") print("Received input is:", eval(s)) Here is a sample run of the above program: Enter your input: [x*5 for x in [1,2,3]] Received input is: [5, 10, 15] Sanath Jayasena Dept. of Computer Science & Engineering 22 Outline Lecture 2 PART 4 Sanath Jayasena • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Dept. of Computer Science & Engineering 23 File Read/Write • First create a file object using built-in open() function to access the file Many other file • Then use the following file methods methods available. Python file – file.read([size]) methods are – file.write(str) based on the – file.close() stdio library in C • Many file attributes also available – file.closed , file.name , file.mode , … Sanath Jayasena Dept. of Computer Science & Engineering 24 open() Function • open(name [, mode [,buffering]]) – name : name of file to be opened – mode : a string, how the file to be opened • Example modes – “r” for reading, “w” for writing, “a” for appending (default is “r”) – Add “b” to mode to open in binary mode – Modes “r+”, “w+” and “a+” open file for reading and writing – [See: https://stackoverflow.com/questions/1466000/ for details] Sanath Jayasena Dept. of Computer Science & Engineering 25 Example 1 # Program-2.4 # Open a file fo = open("pythonlearn.txt", "r") s = fo.read() print ("Read String is:", s) # Close opened file fo.close() Sanath Jayasena Dept. of Computer Science & Engineering 26 Example 2 # Program-2.5 # Open a file fo = open("firstwrite.txt", "w") fo.write("Python is fun!!\n") # Close opened file fo.close() Sanath Jayasena Dept. of Computer Science & Engineering 27 Outline Lecture 2 PART 5 Sanath Jayasena • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Dept. of Computer Science & Engineering 28 Expressions, Operations • Here the • Expressions discussion is mainly – Arithmetic (algebraic) on numeric types – Logical (Boolean) • Expressions and • Operations operations on lists – Arithmetic, logical/comparison and strings will be – Assignment covered later (Chapters 6, 8 in – Bit-wise Notes) – Membership, Identity Sanath Jayasena Dept. of Computer Science & Engineering 29 Arithmetic Expressions, Operations Floor (integer) division • Examples [1]>>> 3 + 4.5 7.5 [2]>>> (3 + 2) * 8 40 [3]>>> 5 / 2 2.5 [4]>>> 5.0 / 2 2.5 Sanath Jayasena [5]>>> 5 // 2 2 [6]>>> 5.0 // 2 2.0 Modulo [8]>>> 7 % 3 division 1 [9]>>> 5 ** 3 125 Exponentiation 53 Dept. of Computer Science & Engineering 30 Arithmetic Expressions, Operations • Many built-in functions available >>> abs(-4) 4 >>> abs(-3.2) 3.2 >>> min(2, -4, 6, -2) -4 >>> max(12, 26.5, 3.5) 26.5 Sanath Jayasena Dept. of Computer Science & Engineering 31 Mixed Arithmetic (& Coercion) • When a binary arithmetic operator has operands of different numeric types, the operand with the “narrower” type is “widened” (coerced) to that of the other • Examples: – Integers narrower than floating point – Floating point narrower than complex numbers – If either operand is complex (or floating point), the other is converted to complex (or floating point) Sanath Jayasena Dept. of Computer Science & Engineering 32 Exercise • Do the Practice Problem 2.1 on page 18 in Notes. Sanath Jayasena Dept. of Computer Science & Engineering 33 Boolean (Logical) Expressions [1]>>> 2 < 3 [6]>>> 2 < 3 and 4 > 5 True False [2]>>> 2 == 2 [7]>>> not (5 > 3) True False [3]>>> 2 != 2 [8]>>> b, c False (98, 97) [4]>>> 2 >= 1 [9]>>> b > c or c >= 98 True True [5]>>> 5 - 1 > 2 + 1 See Sections 3.3, 3.6 in Notes True Sanath Jayasena Dept. of Computer Science & Engineering 34 Exercise • Do the Practice Problem 2.2 on page 19 Sanath Jayasena Dept. of Computer Science & Engineering 35 Assignments • General format of assignment statement <variable> = <expression> • Examples >>> b = 4 >>> counter = b * 4 >>> counter 16 >>> 5 = b SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? Sanath Jayasena Dept. of Computer Science & Engineering 36 Assignment Operators Operator = Example c = a + b assigns value of a + b to c += c += a same as c = c + a -= c -= a same as c = c - a *= c *= a same as c = c * a See Section 3.4 in Notes Similar others like: /=, //=, %=, **= Sanath Jayasena Dept. of Computer Science & Engineering 37 Exercise 1. Do the Practice Problem 2.3 on page 20 2. Explain what will be the result if we input the following to the Python interpreter? (i) p = q = r = 5 (ii) a, b, c = 23, 3.4, "ijk" (iii) [x, y, z] = [1,"mn",3] Sanath Jayasena Dept. of Computer Science & Engineering 38 Bit-wise Operators • Assume a = 60 and b = 13 • Their binary representations and bit-wise operations a = 0011 1100 b = 0000 1101 ---------------------a & b = 0000 1100 a | b = 0011 1101 a ^ b = 0011 0001 ~a = 1100 0011 Sanath Jayasena Other operators: << and >> (left and right shift). See Section 3.5 in Notes (AND) (OR) (XOR) (Complement) Dept. of Computer Science & Engineering 39 Membership Operator “in” • Tests membership in a sequence; e.g., strings, lists, tuples Operator Description Evaluates to True if it finds an object in the in specified sequence; False otherwise. Evaluates to True if it not in does not find an object in the specified sequence Sanath Jayasena Example x in y → this results in True if x is a member of y. x not in y → this results in True if x is not a member of y. Dept. of Computer Science & Engineering 40 Identity Operator “is” Operator Description Example is Evaluates to True if the names (vars) on either side of the operator point to the same object and False otherwise. x is y → this results in True if id(x) == id(y). Evaluates to False if the names x is not y → (vars) on either side of the results in True if is not operator point to the same id(x) != id(y). object and True otherwise. Sanath Jayasena Dept. of Computer Science & Engineering 41 Operator Precedence Operator Sanath Jayasena ** ~ , +, *, / , %, // +,>>, << & ^,| <=, < , >, >= ==, != = , %=, /=, //=, -=, +=, *=, **= is, is not in, not in not, or, and Description Exponentiation (raise to the power) Complement, unary plus and minus Multiply; divide, modulo, floor division Addition and subtraction Right and left bitwise shift Bitwise 'AND' Bitwise `XOR' and `OR' Comparison operators Equality operators Precedence HIGH Assignment operators Identity operators Membership operators Logical operators Dept. of Computer Science & Engineering Precedence LOW 42 Outline Lecture 2 PART 6 Sanath Jayasena • Basic Python Data Types • Objects • Mutable vs Immutable Objects • Input and Output • File Read/Write • Expressions & Operators • Python Keywords and Built-ins Dept. of Computer Science & Engineering 43 Python Keywords and continue for lambda try as def from nonlocal while assert del global not with async elif if or yield await else import pass False break except in raise True class finally is return None Sanath Jayasena Dept. of Computer Science & Engineering 44 Python Built-in Functions For complete list, see https://docs.python.org/3/library/functions.html Sanath Jayasena Dept. of Computer Science & Engineering 45 Python Built-in Functions For complete list, see https://docs.python.org/3/library/functions.html Sanath Jayasena Dept. of Computer Science & Engineering 46 Python Built-in Constants • False, True – False and true values of bool type • None – Used to represent the absence of a value >>> d = 5 >>> d 5 >>> d = None >>> d (nothing displayed) Sanath Jayasena >>> if (d == None): print("Hello") Hello >>> Dept. of Computer Science & Engineering 47 Conclusion • We discussed – Data types, Objects, Mutability – Input, Output – File Read/Write – Expressions, Operations – Operators – Python keywords, Built-ins Sanath Jayasena Dept. of Computer Science & Engineering 48
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )