Python Revision of Class 11

 

Python Fundamentals

TOKENS:

Keywords (Predefines words with special meaning to Python e.g. print, form,, while, if, list, dict, True, None etc.)

Identifiers (Names given to different parts of the programs viz. variables, functions, objects, classes, lists, dictionaries etc.)

Literals (Values e.g. 4, 100, 68.9,  "Hello" , "Abhilash" etc.)

Operators (That triggers some computation, action e.g.   + , / ,// , %, - , *, ** etc.)

Punctuators ( Symbols used in programming language to organize statement structure e.g. ' " # ( ) [ ] ; etc. )

 EXPRESSIONS:

An expression is any valid combination of operators, literals and variables
e.g.
3 + 6 / 2 - 10%3         (Arithmetic expression)
x > y != z                   (Relational expression)
A and not B or C       (Logical Expression)

Types of Operators:

  1. Arithmetic Operators      (*  +   %   //    / etc.)
  2. Relational Operators       (< > <=    ==   !=   >=)
  3. Logical Operators           (and     or     not)
  4. Membership Operators   (in    not in)
  5. Identity Operators            (is     is not)

OPERATORS PRECEDENCE: 


Rules for identifier names:

 Keywords and operators are not to be used
 Start with an alphabet or an underscore.
 Special characters other than underscores are allowed.
 Space is not allowed.
 Cannot start with a number.
 Note: Python is case sensitive and hence uppercase and lowercase are treated
differently.
 Example:
engmark, _abc , mark1, mark2

Mutable and Immutable types:

If the values can be changed after creating the variable and assigning values, then it is called mutable
If the value assigned cannot be changed after creating and initializing it, then it is known as Immutable.

TYPE CASTING

The conversion of one data type into the other data type is known as Type Casting (also called Type Conversion). 

There are two types of type conversion in Python

1. Implicit conversion - automatic type conversion

2. Explicit conversion - manual type conversion

Example: 

x = '12'   (Implicit)    - Automatically converted to String
x = int('12')   (Explicit)      -  Converted to integer by the programmer

 Multiple Assignments:

a = b = c = 10
a,b,c = 1,2,"hello"

Types of Errors: 

Syntax Errors:  Syntax errors are mistakes in the source code, such as spelling and punctuation errors, incorrect labels, and so on, which cause an error message to be generated by the compiler/ interpreter. 

Some of the examples of Syntax errors are missing semicolons · unbalanced parenthesis · missing operators · indentation · error etc.

Run time Errors: A runtime error in a program is one that occurs after the program has been successfully compiled. 

  • Some examples of Python Runtime errors
    • division by zero
    • using an identifier that has not been defined
    • accessing a list element, dictionary value, or object attribute which doesn’t exist
    • trying to access a file that doesn’t exist

          Logical ErrorsA logical error occurs in Python when the code runs without any syntax or runtime errors but produces incorrect results due to flawed logic in the code.

           FLOW OF CONTROL

          Selection Statement:

                          if
                          if ... else
                          if ... elif ...elif...  else

          Syntax: if
                              if <logicalcexpression> :
                                    Statement(s)
                  Here, if the logical expression results to True then Statement(s) will be executed other-wise not.

          Syntax: if...else
                              if <logical expression> :
                                  Statement(s)1
                              else:
                                  Statement(s)2  
                     Here, if the logical expression results to True then Statement(s)1 will be executed other-wise Statement(s)2 will be executed. (It means either Statement(s)1 or Statement(s)2 will be executed.)

          Syntax: if...elif...elif...else

                              if <logicalcexpression1> :
                                  Statement(s)1
                              elif <logicalcexpression2>:
                                  Statement(s)2
                              elif <logicalcexpression3>:
                                  Statement(s)3
                              ...
                              ...
                              else:
                                  Statement(s)4  

                  Here, if the logicalexpression1 results to True then Statement(s)1 will be executed otherwise program will check logicalexpression2. If it results to True then Statement(s)2 will be executed and so on. If neither of the logical expressions will results to True then finally Statement(s)4 of else part will be executed.
          Note: Only and only one set of Statement(s) will be executed irrespective of whether any logical expression results to True or False.

          Iteration / Looping Statement:

                          for 
                          while
                          Nested loop

          Syntax: for
                                  for <variable> in <sequence>:
                                         Statement(s)

          Syntax: while
                                  while <logical expression>:
                                        Statement(s)
           

          Syntax: Nested loops (loop within loop):

                                              for <variable1> in <sequence1>:
                                         Statement(s)
                                         for <varibal2> in <sequence2>:
                                                 Statement(s)

          JUMP Statements:  

                      break
                      continue


                  break:    
                        while <logical expression>:
                            Statement1
                            Statement2
                            Statement3
                            break
                            Statement4
                      Here, Statement 1, 2 and 3 will be executed. As soon as the program executes break statement, the program terminates the while loop.

                  continue:
                        while <logical expression>:
                            Statement1
                            Statement2
                            Statement3
                            continue
                            Statement4                                

                       Here, Statement 1, 2 and 3 will be executed. As soon as the program executes continue statement, the program restarts while loop.

          STRING

          String is the collection of characters.
          S = "Python is easy"
          In above statement, S is a string variable. Python sees the string S as follows:

          S P y t h o n i s e a s y
          Positive Indexing 0 1 2 3 4 5 6 7 8 9 10 11 12 13
          Negative Indexing -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

          To access any character of String S, either positive index or negative index can be used.
          Examples:
          S[1] as well as S[-13] will return 'y'
          S[10:14] will return 'easy'
          S[-9::-1] will return 'nohtyP' . Missing middle parameters means it refers the string up to the last position. 
          Default values of First parameter and Last parameter is 0 and 1 respectively.

          In-built String Methods:

          string.count(str, beg= 0,end=len(string))

          Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.
          string.find(str, beg=0 end=len(string)) Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
          string.index(str, beg=0, end=len(string)) Same as find(), but raises an exception if str not found.

          string.isalnum()

          Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
          string.isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

          string.isdigit()

          Returns true if string contains only digits and false otherwise.
          string.isnumeric() Returns true if a unicode string contains only numeric characters and false otherwise.
          len(string) Returns the length of the string.
          string.split(str="", num=string.count(str)) Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.    

          LIST

          List is the collection of various types of data.
          It is an iterable object.
          L = [6, 8.5, True, 'Good', 20, 53.84]
          L1 = [7, [1,3,2] , 7, 9]    (Nested list)
          L1[1][2] will return 2
          Similar to String, List can also be accessed using Positive index and negative index both.

          L[3] will return True
          L[3:5] will return ['Good', 20]

          List Functions:

          len(L) returns the size (number of items) of the list
          list() a Python built-in class that creates a list out of an iterable object passed as an argument.
          type(list) returns the class type of an object
          L.append(value) Adds a single element to a list.
          L.extend(List2) Adds elements of List2 to L
          L.index(value) Returns the first appearance of the specified value.
          max(L) returns an item from the list with max value
          min(L) It returns an item from the list with min value.
          L.clear() Removes all the items from list
          L.count(value) Returns the number of times an element occurs in the list.
          L.insert(index, value) Inserts an item at a given position.
          L.remove(value) Removes the first occurrence of the specified item from the list

          L.reverse()

          Reverses the index positions of the elements in the list.

          L.sort()

          Sorts the list items in ascending, descending, or in custom order.

          L.pop() or L.pop(index)

          Removes and returns the item from last position.

          TUPLE

          Tuple is a collection of elements which is ordered and unchangeable (Immutable).
          Allows duplicate members.
           
          Creating tuple                                            T = (2,5,7,10,34)
          Creating a tuple with single element:        T = (5,)
          Accessing values:                                         T[3] will return 10
          Joining tuples:                                             T = T1 + T2
          Repeating tuple:                                          T * 3

          Slicing operation for tuple is same as for the string or list.

          Packing and Unpacking tuples:
          Packing a tuple means creating a tuple e.g.
                                      T = (4,6,8)
          Unpacking means creating individual values from tuple e.g.
                                      a, b, c = T
          Here a = 4, b=6 and c=8
          Note: While unpacking, Number of variables in left side should be equal to number of items in tuple. 

          Tuple functions:
          Main functions of tuples are
                                      len() , max(), min() , index(), count() 
                          which is self explanatory and similar to list functions.

          DICTIONARY

          Dictionaries are used to store data values in key:value pairs.
          A dictionary is a collection which is unordered, changeable and do not allow duplicates.

          Example:
          D = {1:'SUN', 2:'MON',3:'TUE',4:'WED',5:'THU',6:'FRI'}

          Accessing values: Values can be accessed by keys in dictionary e.g.
                                              print(D[2]) will print 'MON'

          Adding/ appending values: Values can be added by using new key e.g.
                                              D[7] = 'SAT' will add new item.

          Deleting values:
          1. using del statement
                                                  del D[key]
          2. using pop() method
                                                  D.pop(key)

          Dictionary Functions:

          len(d)

          Find the length of a dictionary

          d.clear()

          removes all elements from the dictionary

          d.get(key)

          Returns value of a key.

          d.keys()

          Returns all the keys in the form of a list.

          d.values()

          Returns all the values in the form of a list.

          d.items()

          Returns all the items in the form of a list.

          d1.update(d2)

          Merges two dictionaries. Already present elements are override.

          d.pop(key)

          Deletes the specified item from the dictionary



                          

          No comments:

          Post a Comment