You are on page 1of 33
\ fay NY, PROGRAMMING THROUGH ‘Python’ Reference Notes SHRAVAN KUMAR RTP ACADEMY of Technical Education Contact: 8004300553 Reference notes of Python What is Python? Python is a cross-platform programming | platforms like Windows, Mac OS X, Linux, Ut and .NET virtual machines, Immediate mode Typing python in the command line We can directly type in Pyth Script mode This mode is used to execute Python program written ina file. Such a file is called a script. Scripts can be saved to disk for future use. Python scripts have the extension “PY. meaning that the filename ends with py. Integrated Development Environment (IDE) We can use any text editing software to write a Python seri save it with the .py extension. But using an IDE can make our life a lot easier, IDE is a Piece of software that provides useful features like code hinting, syntax highlighting and checking, file explorers ete. to the programmer for application development. Python Character Set Character set is a set of valid characters that a language can recognize. A character represents any letter, digits or any other symbol Letters: A-Z, a-z Digits: 0-9 Tokens janguage, meaning, it runs on multiple 7 nix and has even been ported to the Java It is free and Open source. will invoke the interpreter in immediate mode. 'on expressions and press enter to get the output. file. We just need to The smallest individual unit in a program is known as a Token or lexi has following tokens: Keywords Identifiers (Names) Literals Operators 5. Punctuators Keywords Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords are case sensitive. There are 33 keywords in Python. Python Identifiers ; 7 ti Identifiers are fundamental building blocks of a program. Identifier is the name ven to entities like class, functions, variables etc. in Python. It helps differentiating one entity from another. | les for writing identifiers . ; ae | eee can be a combination of letters in lowercase (a to z) or uppercase (A to 2» or digits (0 to 9) or an underscore (). Names like myClass, var 1 an i are valid example. rint_this to. screen, all are valid examp! | . Bo 2 fan identifier cannot start with a digit, Ivariable is invalid, but variablel is perfectly fine. a 3. Keywords cannot be used as identifiers. ical unit. Python Beye 4. The first character must be a letter, the underscore (_ ) counts as a letter. Literals Literals are data items that have a fixed value. Literal is a raw data given ina variable or constant. In Python, there are various types of literals they are as follows: 1. String literals 2. Numeric Literals 3. Boolean Literals 4. Special Literal None 5. Literal Collections Python Comments Comments are very important while writing a program. It describes what's going on inside a program so that a person looking at the source code does not have a hard time figuring it out. In Python, we use the hash (#) symbol to start writing a comment. Python Interpreter ignores comment. Multi-line comments If we have comments that extend multiple lines, one way of doing it is to use hash () in the beginning of each line. Another way of doing this is to use triple quotes, either " or". These triple quotes are generally used for multi-line strings. But they can be used as multi-line comment as well. Expression An expression is any legal combination of symbols that represents a value and it is hot necessary that a statement results in a value. A statement executes and may or may not yield a value. Functions ‘A function is a code that has a name and it can be reused (executed again) by specifying its name in the program where needed, Blocks and Indentation Sometimes a group of statements is part of another statement or function, Such a group of one or more statements is called block or code-block or suite. Most of the Programming languages like C, C++, Java use braces { } to define a block of code. Python uses indentation. A code block (body of a function, loop etc.) starts with indentation and ends with the first unindented line. Variables A variable in Python represents named location that refers to a value and whose values can be used and processed during program run. The variables are called symbolic variables because these are named labels. Data Types Python provides a predefined set of data types for handling the data it uses, Data types tell which type of data should be stored in a variable. There are following built-in core data types in Python: i) Number ii) String iii) List iv) Tuple vy) Dictionary Numbers Number data types are used to store numeric values in Python. The numbers in Python have following built-in core data types: i) Integers: Integers(Signed) and Boolean ii) Floating Point Numbers iii) Complex Numbers Integers (Signed) {tis the normal integer representation of whole numbers. Integers in Python can be of any length, it is only limited by the memory available. Python provides single data type(int) to store any integer, whether small or big. Boolean The Boolean type is a subtype of plain integers and Boolean values False and True behave like the values 0 and 1, respectively. To get the Boolean equivalent of 0 or 1, we can type bool(0) or boo(1), Python will return False or True respectively. Floating Point Numbers A number having fractional part is a floating point number, The fractional numbers can be written in the two forms i) Fractional form (Normal Decimal Notation): 352.02523, 145.362 ii) Exponent Notation: 3.622E03, 7.6668E-02 etc. {n Python, the floating point numbers have precision of 15 digits (double precision). Complex Numbers A complex number is made up of both real and imaginary components. Python represents complex numbers in the form A+Bj, i.e. to represent imaginary number, Python uses j (or J) in place of traditional i. So in Python, j=V-1. Python displays ‘numbers in parentheses when they have a non-zero real part © Var.real gives the real value * Var.imag gives the imaginary part as a float, not as a complex value Python St A string data type lets us hold string data i.e. any number of valid characters into a set of quotation marks. String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, " or """. Python has no separate character data type, which most other programming languages have that can hold a single character. In Python, a character is a string type only, with single character. Strings are immutable and hence item assignment is not supported. Lists A list in Python represents a list of comma-separated values of any datatype between square brackets. Lists can be changed/ modified (i.e, mutable). Tuples . Tuples are represented as group of comma-separated values of any data type within parentheses, Tuples cannot be changed or modified (i.e. immutable). Dictionary ‘The 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 ie. they are unique keys within a dictionary. — Immutable Types The immutable types are those that can nes ‘ver change their Value jn : enn Plage | Sta Python, the following are Immutable: integers, floating point numbers, Booleans. 7 tuples. " Mutable Types The mutable types are those whose values can be changed in place, Only the lypes are mutable in Python: lists, dictionaries and sets. Operators The symbols that trigger the operation/action on d; data on which operation is being cartied out, Le. the objec as operands, Expressions ta are ealled operators and i, 'S of operation(s) ate refered, the expression’s type. An expression can Python can be of any type: Arithmetic, ‘ompound expressions, accordingly. Errors in a program An error, sometimes called a ‘bug’, from compiling and Tunning correctly, There are broadly three ty time errors, run-time errors and logical errors, Compile-Time Errors Errors that occur during compile-time, are com Compiles, its source code is checked for Tule or not. Two types of err (i) Syntax Errors is anything in the code r pile-time errors. When Whether it follows u rors fall into category: @ program he programming language's valid statements ina Pregramming language are misused thon is violated, (ii) Semantics Errors Semantics refers to the set of rules wl Semantics Errors occur when statements e.g, X*Y, Logical Errors Sometimes, even if we don’t encounter an; time, our program does not provide the correct resu Run-Time errors : Errors that occur during the execution of a program are run-time harder to detect errors. Some run-time errors stop the execution then called program ‘crashed’ or ‘abnormally terminated ee, value ete. hich give the me aning of a statement, are not meaningful Y error during compile-time and run- lt. Such error 8 are logical errors, errors. These are of the program whieh is an intinite loop of wrong Atements Statements are the ; Instructions given to the computer to be it data movements and be it making form the smallest executable unit within to one of the following three lypes: > Empty > perform any Kind of action, it repeating actions, Statements jam. Python statements can belong dccisions or be Python progr awtements Simple Statements (Single st > Compound Statement Empty Statement (NULL statement) The simplest statement is the empty statement ie. a st Python, an empty statement is pass Statement, Simple Statement Any single executable statement is 2. name="Adarsh Compound Statement A compound statement repre: Compound statements of Python ~Compound statement header fatement) atement which does nothing, In a simple statement in Python, ‘Senls a group of statements executed are written in a specific pattem is a unit. The as shown below: Sindented body containing multiple Statement flow control In a program, statements may be executed Sequentially, selectively or iteratively, Every programming language provides constructs. to support sequence, selection of iteration. simple and/or compound statements Sequence ‘The sequence construct means the stateme nts are being executed sequentially. This represents the default flow of statement. Statement? | Selection a ; The selection construct means the execution of statements depending upon a condition-test. Ifa condition evaluates to True, a course-of-action (a set of statements ) is followed otherwise a different set of statements is followed. This con uct is also called decision construct because it helps in making decision about which set-of-statements is to d be executed. Repetition Iteration (Looping) The iteration constructs mean repetition of a set of statements depending upon a condition-test. Till the time a condition is True (or False depending upon the loop), a set of statements are repeated again and again. As soon as the condition becomes False (op True), the repetition stops. The iteration construct is also called looping construct. The set of statements that are repeated again and again is called the body of the loop. The condition on which the execution or exit of the loop depends is called the exit condition or test-condition. | True Statement 1 | Ls if Statements The if statements are the conditional statements in Python and these implement selection constructs (decision constructs). An if statement tests a particular condition; if the condition evaluates to true, a course of action is followed i.e. a statement or a set of statements is executed. Otherwise (if the condition evaluates to false, the course of action is ignored. There are following if statements > Simple if statements > if-else statements » else-if ladder > nested if The if statement The simplest form of if statement tests a condition and if the condition evaluates to True, it carries out some instructions and does nothing in case condition evaluates to false. Syntax: If : Statement [Statements] Where a statement may consists of a single statement, a compound statement, or just the pass statement. The if-else statement ‘This form of if statement tests a condition and if the condition evaluates to true, it carries out statements below if and in case condition evaluates to false, it carries out statement indented below else. Syntax: | if : Statements else: statements The else-if ladder statement Sometimes, we need to check another condition in case the test-condition of if evaluates to false i.e. we want to check a condition when control reaches else part i. condition test in the form of else-if. To serve conditions as above i.e. in else if form (or if inside an else), Python provides if elif and if-elif-else statements. Syntax: if : Statements elif conditional expression> Statements else: Statements The nested if statements A nested if is an if that has another if in its if’s body or in elif’s body or in its else's body, Syntax: if : if : Statements else: Statements elif , , step) Default value of lower limit is 0 and step is +1. The in and not in operators The in operator tests if'a given value is contained in a sequence or not and returns True or False accordingly. The not in does opposite of in operator. These are also called membership operators. These operators work with all sequence types ice. strings, tuples and lists etc. Iteration/Looping statements The iteration statements or repetition statements allow a set of instructions to be performed repeatedly until a certain condition is fulfilled. The iteration statements are also called loops or looping statements. Python provides two kinds of loops: for loop and while loop to represent two categories of loops, which are: Counting loops: the loops that repeat a certain number of times; Python’s for loop is a counting loop. Conditional loops: the loops that repeat until a certain thing happens i.e. they keep repeating as long as some condition is rue; Python's while loop is conditional loop. The for loop The for loop of Python is designed to process the items of any sequence one by \ one. y Syntax: for in : statements_to_repeat e.g. Write a program to print table of a number num=int(input(“Enter a number: “)) for iin range(1,11): print(num,” x“ The while loop A while loop is a conditional loop that will repeat the instructions within itself as long as conditional remains True, Syntax: “snum*i) While : loop-body ©8. Write a program to print sum of digits of a number num = int(input(“enter a number: *)) sum=0 while num>0: r=num%10. num=nun//10 sum=sum+r else: print(*Sum of digits = sum) The break statement The break statement enables a Program to skip over a part of the code. A break statement terminates the very loop it lies within, Execution resumes at the statement immediately following the body of the terminated statement. e.g, Write a program to check a number is Prime or not. hum=int(input(“Enter a number: “)) for i in range(2,num): is not a Prime number”) else: print(num,” is a Prime number”) Nested loops ; / A loop may contain another loop in its body. This form of a loop is called nested loop. But in a nested loop, the inner loop must terminate before the outer loop. aac strings are characters enclosed in quotes of any type- single, double and triple quotation marks. An empty string is a string that has 0 characters and Python strings are immutable. Strings are sequence of characters, where each character has a unique position-id/index. The indexes of a string begin from 0 to (length-I) in forward direction and -1,-2,-3,.......-length in backward direction. ersing ga String ing the indexes, we refers to iterating through the elements of a string, one character at a time. an waverse a string character by character. Trav ring Operators We have basic operators “+” and “**, membership operators ‘in’ and ‘not in’ and comparison operators for strings. String Concatenation operator (+) The + operator creates a new string by joining the two operand strings. e.g. © “pot” will result into “teapot”. The + operator has to have both operands of the same type of string types. It cannot work with one operand as string and one as a number. e.g. Write a program to concatenate two strings. first_name=input(“enter first name: “) last_name = input(“Enter last name: “) full_name = first_name + last_name print(full_name) String Replication Operator (*) To use a * operator with strings, we need two types of operands — a string and a as number * string or string * number. e.g. Write a program to replicate a string. input(“Enter a string: “) print(st*3) output: Enter a string: I love my India I love my Indial love my Indial love my India Membership operators There are two membership operators for string: im and not in in: return True if a character or a substring exists in the given string; otherwise False ‘not in: return True if a character or a substring does not exists in the given string: otherwise False e.g. ‘a’ in ‘japan’ will give True “q’ not in “japan” will give True “A in ‘japan’ will give False String Slices Slice means ‘a part of”. In Python, the term ‘string slice’ refers to a part of the string containing some contiguous characters from the string, where strings are sliced using a range of indices. e.g. word="amazing” print(word[3:7]) _#lt will give ‘zing’ String Functions/Methods [S. |Funetion/Method Description = Sst—~) 7 It returns a copy of the string with its first 2 ing>.capitalize() _| ee _ character capitali oe 3 {ring>-count(subf start[.end]]) | It returns the number of occurrences of the | ing | substring sub in the string ____ It returns the lowest index in the string | .find( sub] start[.end]]) —T where the substring sub is found witke \ 0° slice range of start and end. Retums 1p g\°% isnot found, “yer Ny 5 | .index(sub[.start[.end]}) [It retums the lowest “index where joy 5 | specified substring is found. ‘| 6 It returns True if the chara n the string are alphanumeric and there is at least One - _| character, False otherwi a _ 7 | isalpha() Il returns True if all characters in the string | are alphabetic and there is at least one — character, False otherwise. _ __| 8 | isdigit() It returns True if all the characters in the string are digits. There must be at least one I character. It returns False otherwise. 9 | .islower() It returns True if all cased characters in the | string are lowercase, False otherwise. | 10 | isspace() It returns True if there are only whitespace i _ characters in the string, False otherwise. (IL | sstring>.isupper() It tests whether all cased characters in the string are uppercase and returns True, False otherwise. 12. | .lower() It returns a copy of the string converted to | i _ ___| lowercase. a | 13 | .upper() It returns a copy of the string converted to | uppercase, (14 [ JstripQ) It returns a copy of the string with leading white-spaces removed .rstrip() It returns a copy of the string with trailing white-spaces removed .strip() It returns a copy of the string with leading | | and trailing white-spaces removed List The Python lists are containers that are used to store a list of values of any type. Python lists are mutable. The lists are depicted through square brackets, e.g. 0 #Empty list [1,23] #list of integers 2,4,5.4,’a'] list of mixed value types a _ a lists a formed by placing a comma-separated list of expressions in square brackets. list( ) function is used to create a blank list or list of sequences like: L=list( ) ist() a rae have an element in it, which itself is a list. Such a list is called nested ist. E.g. =[3,4,[5.6.7,’a"],5] so) ae a art ] will give 5.6 and list{2] will give [5.6,7."a"] as one element. Joining lists , ee , The concatenation operator + joins two lists. e.g, 11=[10,20,30] = [3,5,9.5] Fu print(l) The + operator when used with list H it will print [10,20,30,3. 9.5] S requires that both the operands must be of list types. We cannot add a number or any other value to a list. Repeating or Replicating lists We can use * operator to replicate a list specified number of times. We can use only an integer with a * operator when trying to replicate a list. e.g. print(I*3) # It will print [10, Slicing the lists ,20,30,3,5,9.5,10,20,30,3,5,9.5,10,20,30,3,5,9.5] . List[start:stop:step| creates a list slice out of list with elements falling between indexes start and stop, excluding stop. Lists manipulation methods and functions S. | Function/Method |Description =| No. | | 1 |len() It returns the length of its argument list | 2 | List([) It returns the index of first matched item from | the list | 4 | _Listappend() | List.extend() ‘The append() method adds an item to the end of | thelist The extend() method is multiple elements to a list. also used for a es © _ | List.insert(, ) The insert() method is also an insertion method | for lists, like append() and extend() method. 7 | List.pop() 8 | List.remove() The pop() is used to remove the item from the | list. The remove() method removes the first | occurrence of the given item from the list. \ List.clear() This method removes all the items from the list | and the list becomes an empty list afier this 10 | List.count() function. This function returns nothin; S| This method returns the count of the item that | you passed as argument. If the given item is not | in the list, it returns zero. ‘The reverse() reverses the items of the list. The sort() method sorts the items of the list, by default in increasing ordet | This function takes the name of the list as an argument and returns a new sorted list with | sorted elements in it. a | |The min(), max() and sum() functions take the list sequence and returns the minimum, element, | [ [Sum() | maximum element and sum of the elements. __ the list respectively. Tuples Python Tuples are sequences that are used to store a tuple of values of any type, Tuples are immutable sequences i.e. we cannot change elements of a tuple in place. The tuples are depicted through parentheses. Python will create a fresh tuple when we make changes to an element of a tuple. T=(2,3, 6,7.5,'a°,’S’) Syntax: t=()_ #Empty tuple T=(valuel,value2,......) To construct a single element tuple, we just give a single element in parentheses with a comma symbol. Nested Tuples Ifa tuple contains an element which is a tuple itself then it is called nested tuple. Eg. (2,4.5,'2"\(‘s',4,6.5),56) Tuples are immutable counter-parts of lists. Tuples elements are indexed ie. forward indexing and backward indexing, Joining Tuples The + operator, the concatenation operator, when used with two tuples, joins two tuples. The + operator when used with tuples requires that both the operands must be of tuple types, eg. t=(1,4.5,6.7) 12=(‘a’,9,4.6,7.8) 13-1412 print(t3) — #(1,4.5,6.7,’a,9,4.6,7.8) The * operator, the replication operator, requires a tuple and an integer as operands, Repeating or Replicating Tuples We can use * operator to replicate a tuple specified number of times, The * operator requires a tuple and an integer as operands, e.g, print(t1*3) #Output: (1,4.5,6.7,1,4.5,6.7,1,4.5,6.7) Slice the Tuples Tuple slices are the sub parts of tuple extracted out. We can use indexes of tuple elements to create tuple slice as per following format: seq=t[start:stop:step] It creates a tuple slice out of tuple t with elements falling between indexes start and stop, not including stop with given step. €.g, print(H[1:3))_ will produce: (4.5.6.7) Forming a tuple from individual values is called packing and creating individual values from a tuple’s elements is called unpacking, The de! statement of Python is used to delete elements and objects but as we know that tuples are immutable, which also means that individual elements of a tuple cannot be deleted. . ion/Method | Description a 1 e> _ el This function returns length of the tuple 2 max() | This function returns the element from the tuple 7 __ having maximum value | min() The sum() function takes the tuple seq sequence “and returns the sum of the elements of the tuple | 5 .index( | jee index() method returns the index of an existing | | ) element of a tuple. The count() method returns the count of a member | | name> .count() | This creates tuples from different types of iterable | | ___| sequences. = Dictionary Dictionaries are mutable, unordered collections with elements in the form of a rvalue pairs that associate keys to values are separated by commas(,). To create a ionary, we need to include the key:value pairs in curly braces as per following syntax: ={:, :, .. cd Dictionaries are also called associative arrays or mappings or hashes. dictionaries must be of immutable types. A dictionary operation that takes a key and finds the corresponding value is called lookup. Attempting to access a key that doesn’t exist, causes an error. Traversing a Dictionary The ‘for’ loop makes it easy to traverse or loop over the items in a dictionary, as per following syntax: for in : Process each item here ‘The loop variable will be assigned the keys of one by one which we can use inside the body of the ‘for’ loop. Keys of In Dictionary, the updation and addition of elements are similar in syntax. But for addition, the key must not exist in the dictionary and for updation, the key must exist in the dictionary, []- For deleting clements from a dictionary, we can us popitem() functions. del “dictionary “[-key | either del statement or pop) or

You might also like