the document covers python programming language, Study notes of Computer Science

the document covers python programming language it covers units such as INTRODUCTION DATA, EXPRESSIONS, STATEMENTS ,CONTROL FLOW, LOOPS ,FUNCTIONS, ARRAYS and many others

Typology: Study notes

2022/2023

Uploaded on 01/17/2023

johnthiongo
johnthiongo 🇰🇪

5

(1)

4 documents

1 / 135

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
PYTHON PROGRAMMING III YEAR/II SEM MRCET
John thiongo
PYTHON PROGRAMMING
[R17A0554]
LECTURE NOTES
B.TECH III YEAR – II SEM (R17)
(2019-20)
DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING
MALLA REDDY COLLEGE OF ENGINEERING &
TECHNOLOGY
(Autonomous Institution – UGC, Govt. of India)
Recognized under 2(f) and 12 (B) of UGC ACT 1956
(Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified)
Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India
SYLLABUS
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download the document covers python programming language and more Study notes Computer Science in PDF only on Docsity!

John thiongo

PYTHON PROGRAMMING

[R17A0554]

LECTURE NOTES

B.TECH III YEAR – II SEM (R17)

DEPARTMENT OF

COMPUTER SCIENCE AND ENGINEERING

MALLA REDDY COLLEGE OF ENGINEERING &

TECHNOLOGY

(Autonomous Institution – UGC, Govt. of India) Recognized under 2(f) and 12 (B) of UGC ACT 1956 (Affiliated to JNTUH, Hyderabad, Approved by AICTE - Accredited by NBA & NAAC – ‘A’ Grade - ISO 9001:2015 Certified) Maisammaguda, Dhulapally (Post Via. Hakimpet), Secunderabad – 500100, Telangana State, India

SYLLABUS

MALLA REDDY COLLEGE OF ENGINEERING AND TECHNOLOGY III Year B. Tech CSE -II SEM L T/P/D C 3 - / - / - 3 OPEN ELECTIVE III (R17A0554) PYTHON PROGRAMMING OBJECTIVES:

  • To read and write simple Python programs.
  • To develop Python programs with conditionals and loops.
  • To define Python functions and call them.
  • To use Python data structures –- lists, tuples, dictionaries.
  • To do input/output with files in Python. UNIT I INTRODUCTION DATA, EXPRESSIONS, STATEMENTS Introduction to Python and installation , data types: Int, float, Boolean, string, and list; variables, expressions, statements, precedence of operators, comments; modules, functions--- function and its use, flow of execution, parameters and arguments. UNIT II CONTROL FLOW, LOOPS Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-else); Iteration: while, for, break, continue. UNIT III FUNCTIONS, ARRAYS Fruitful functions: return values, parameters, local and global scope, function composition, recursion; Strings: string slices, immutability, string functions and methods, string module; Python arrays, Access the Elements of an Array, array methods. UNIT IV LISTS, TUPLES, DICTIONARIES Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple comprehension; Dictionaries: operations and methods, comprehension; UNIT V FILES, EXCEPTIONS, MODULES, PACKAGES Files and exception: text files, reading and writing files, command line arguments, errors and exceptions, handling exceptions, modules (datetime, time, OS , calendar, math module), Explore packages. OUTCOMES: Upon completion of the course, students will be able to  Read, write, execute by hand simple Python programs.
  • Structure simple Python programs for solving problems.

INDEX

UNIT TOPIC PAGE NO I INTRODUCTION DATA, EXPRESSIONS, STATEMENTS

Introduction to Python and installation (^) 1 data types: Int (^6) float (^7) Boolean (^8) string (^8) List (^10) variables (^11) expressions (^13) statements (^16) precedence of operators (^17) comments (^18) modules (^19) functions ---- function and its use (^20) flow of execution (^21) parameters and arguments (^26) II

CONTROL FLOW, LOOPS 35

Conditionals : Boolean values and operators,

conditional (if) (^36) alternative (if-else) (^37) chained conditional (if-elif-else) (^39) Iteration: while, for, break, continue. (^41) III

FUNCTIONS, ARRAYS 55

Fruitful functions: return values (^55) parameters (^57) local and global scope (^59) function composition (^62) recursion (^63) Strings: string slices (^64) immutability (^66) string functions and methods (^67)

IV

V FILES, EXCEPTIONS, MODULES,

PACKAGES modules (datetime, time, OS , calendar, math module)

- string module - Python arrays - Access the Elements of an Array - Array methods
  • LISTS, TUPLES, DICTIONARIES
  • Lists
  • list operations
  • list slices
  • list methods
  • list loop
  • mutability
  • aliasing
  • cloning lists
  • list parameters
  • list comprehension
  • Tuples
  • tuple assignment
  • tuple as return value
  • tuple comprehension
  • Dictionaries
  • operations and methods
  • comprehension
  • Files and exception: text files
  • reading and writing files
  • command line arguments
  • errors and exceptions
  • handling exceptions
  • Explore packages

Statement

Script Ends

Differences between scripting language and programming language: Why to use Python: The following are the primary factors to use python in day-to-day life:

1. Python is object-oriented Structure supports such concepts as polymorphism, operation overloading and multiple inheritance. 2. Indentation Indentation is one of the greatest feature in python 3. It’s free (open source) Downloading python and installing python is free and easy

4. It’s Powerful - Dynamic typing - Built-in types and tools - Library utilities - Third party utilities (e.g. Numeric, NumPy, sciPy) - Automatic memory management 5. It’s Portable - Python runs virtually every major platform used today - As long as you have a compaitable python interpreter installed, python programs will run in exactly the same manner, irrespective of platform. 6. It’s easy to use and learn - No intermediate compile - Python Programs are compiled automatically to an intermediate form called byte code, which the interpreter then reads. - This gives python the development speed of an interpreter without the performance loss inherent in purely interpreted languages.  Structure and syntax are pretty intuitive and easy to grasp. 7. Interpreted Language Python is processed at runtime by python Interpreter 8. Interactive Programming Language Users can interact with the python interpreter directly for writing the programs 9. Straight forward syntax The formation of python syntax is simple and straight forward which also makes it popular. Installation: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) which is installed when you install the python software from http://python.org/downloads/ Steps to be followed and remembered: Step 1: Select Version of Python to Install. Step 2: Download Python Executable Installer. Step 3: Run Executable Installer. Step 4: Verify Python Was Installed On Windows. Step 5: Verify Pip Was Installed. Step 6: Add Python Path to Environment Variables (Optional)

Without passing python script file to the interpreter, directly execute code to Python prompt. Once you’re inside the python interpreter, then you can start. >>> print("hello world") hello world

Relevant output is displayed on subsequent lines without the >>> symbol

>>> x=[0,1,2]

Quantities stored in memory are not displayed by default. >>>

x #If a quantity is stored in memory, typing its name will display it. [0, 1, 2] >>> 2+ 5 The chevron at the beginning of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to indicate that it is ready. If the programmer types 2+6, the interpreter replies 8. Running Python in script mode: Alternatively, programmers can store Python script source code in a file with the .py extension, and use the interpreter to execute the contents of the file. To execute the script by the interpreter, you have to tell the interpreter the name of the file. For example, if you have a script name MyFile.py and you're working on Unix, to run the script you have to type:

python MyFile.py Working with the interactive mode is better when Python programmers deal with small pieces of code as you can type and execute them immediately, but when the code is more than 2-4 lines, using the script for coding can help to modify and use the code in future. Example: Data types: The data stored in memory can be of many types. For example, a student roll number is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Int: Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. >>> print(24656354687654+2) 24656354687656 >>> print(20) 20 >>> print(0b10) 2 >>> print(0B10) 2 >>> print(0X20) 32 >>> 20

print(type(z)) Output:

Boolean: Objects of Boolean type may have one of two values, True or False: >>> type(True)

>>> type(False) String:

  1. Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python allows for either pairs of single or double quotes.
  • 'hello' is the same as "hello".
  • Strings can be output to screen using the print function. For example: print("hello"). >>> print("mrcet college") mrcet college >>> type("mrcet college")

>>> print('mrcet college') mrcet college >>> " " ' ' If you want to include either type of quote character within the string, the simplest way is to delimit the string with the other type. If a string is to contain a single quote, delimit it with double quotes and vice versa: >>> print("mrcet is an autonomous (') college") mrcet is an autonomous (') college

>>> print('mrcet is an autonomous (") college') mrcet is an autonomous (") college Suppressing Special Character: Specifying a backslash () in front of the quote character in a string “escapes” it and causes Python to suppress its usual special meaning. It is then interpreted simply as a literal single quote character: >>> print("mrcet is an autonomous (') college") mrcet is an autonomous (') college >>> print('mrcet is an autonomous (") college') mrcet is an autonomous (") college The following is a table of escape sequences which cause Python to suppress the usual special interpretation of a character in a string: >>> print('a ....b') a....b >>> print('a b\ c') abc >>> print('a \n b') a b >>> print("mrcet \n college") mrcet college Escape Sequence Usual Interpretation of Character(s) After Backslash “Escaped” Interpretation ' Terminates string with single quote opening delimiter^ Literal single quote (') character " Terminates string with double quote opening delimiter Literal double quote (") character \newline Terminates input line^ Newline is ignored \ Introduces escape sequence Literal backslash () character

Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals or characters in these variables. Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables) Assigning Values to Variables: Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example − a= 100 # An integer assignment b = 1000.0 # A floating point c = "John" # A string print (a) print (b) print (c) This produces the following result − 100

John Multiple Assignment: Python allows you to assign a single value to several variables simultaneously.

For example : a = b = c = 1 Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example − a,b,c = 1,2,"mrcet“ Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c. Output Variables: The Python print statement is often used to output variables. Variables do not need to be declared with any particular type and can even change type after they have been set. x = 5 # x is of type int x = "mrcet " # x is now of type str print(x) Output: mrcet To combine both text and a variable, Python uses the “+” character: Example x = "awesome" print("Python is " + x) Output Python is awesome You can also use the + character to add a variable to another variable: Example x = "Python is " y = "awesome" z = x + y print(z) Output: Python is awesome Expressions: An expression is a combination of values, variables, and operators. An expression is evaluated using assignment operator.

add + subtract - multiply * Integer Division / remainder % Binary left shift << Binary right shift >> and & or Less than < Greater than > Less than or equal to <= Greater than or equal to >= Check equality == Check not equal != Some of the python expressions are: Generator expression: Syntax: ( compute(var) for var in iterable )

>>> x = (i for i in 'abc') #tuple comprehension >>> x at 0x033EEC30> >>> print(x) at 0x033EEC30> You might expect this to print as ('a', 'b', 'c') but it prints as at 0x02AAD710> The result of a tuple comprehension is not a tuple: it is actually a generator. The only thing that you need to know now about a generator now is that you can iterate over it, but ONLY ONCE. Conditional expression: Syntax: true_value if Condition else false_value >>> x = "1" if True else "2" >>> x '1' Statements: A statement is an instruction that the Python interpreter can execute. We have normally two basic statements, the assignment statement and the print statement. Some other kinds of statements that are if statements, while statements, and for statements generally called as control flows. Examples: An assignment statement creates new variables and gives them values: >>> x= >>> college="mrcet" An print statement is something which is an input from the user, to be printed / displayed on to the screen (or ) monitor. >>> print("mrcet colege") mrcet college Precedence of Operators: