Variables Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory . 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 . 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 1000.0 John
Comment Lines Single-line comments: These begin with a hash symbol (#) and extend to the end of the line. Any text following the # on that line is considered a comment. # This is a single-line comment x = 10 # This is an inline comment explaining the variable Multi-line comments (using multi-line strings): Multi-line strings (enclosed in triple quotes, ''' or """) can be used to achieve a similar effect. If these strings are not assigned to a variable, they are ignored by the interpreter and effectively act as comments. This is commonly used for doc strings , which provide documentation for modules, classes, and functions. Triple quotes useful for multi-line strings >>> s = """ a long ... string with "quotes" or anything else""" >>> s ' a long\012string with "quotes" or anything else' >>> len (s) 45 """This is a multi-line comment. It can span across multiple lines. """ '''Another example of a multi-line comment using single triple quotes. '''
Multiple Assignment Python allows 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 .
Data Types Integers: 2323, 3234L Floating Point: 32.3, 3.1E2 Complex: 3 + 2j, 1j Lists : l = [ 1,2,3] Tuples: t = (1,2,3) Dictionaries: d = {‘hello’ : ‘there’, 2 : 15 } Lists, Tuples, and Dictionaries can store any type (including other lists, tuples, and dictionaries!) Only lists and dictionaries are mutable All variables are references
Keyword Description and A logical operator as To create an alias assert For debugging break To break out of a loop class To define a class continue To continue to the next iteration of a loop def To define a function del To delete an object elif Used in conditional statements, same as else if else Used in conditional statements except Used with exceptions, what to do when an exception occurs False Boolean value, result of comparison operations finally Used with exceptions, a block of code that will be executed no matter if there is an exception or not for To create a for loop from To import specific parts of a module global To declare a global variable
if To make a conditional statement import To import a module in To check if a value is present in a list, tuple, etc. is To test if two variables are equal lambda To create an anonymous function None Represents a null value nonlocal To declare a non-local variable not A logical operator or A logical operator pass A null statement, a statement that will do nothing raise To raise an exception return To exit a function and return a value True Boolean value, result of comparison operations try To make a try...except statement while To create a while loop with Used to simplify exception handling yield To return a list of values from a generator
Use of ‘ and “ quote In Python, both single quotes (') and double quotes (") are used to define string literals. Functionally, they are interchangeable , meaning a string defined with single quotes behaves identically to the same string defined with double quotes. me = "It's a beautiful day .“ print(me ) me = 'It's a beautiful day .‘ print(me )
Input The raw_input (string) method returns a line of user input as a string The parameter is used as a prompt The string can be converted by using the conversion methods int (string), float(string), etc.
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
Practice Program x = 5 y = 10 x = y print ("x= ",x) print ("y= ",y )
Practice Program x = 5 y = 10 print (x + y) Output: 15
Practice Program x = "Python is " y = " awesome " z = x + y print (z) Output : Python is awesome
Practice Program print ('I am good!') print ('But not always!') print ('I am good,','But not always!') print ('I am good,'+ 'But not always !') Output: I am good ! But not always ! I am good, But not always ! I am good,But not always!
Practice Program x , y, z = "Orange", "Banana", "Cherry" print(x ) print(y ) print(z) Output: Orange Banana Cherry x, y, z ="Orange","Banana"," Cherry " print ( x,y,z ) Output: Orange Banana Cherry
Practice Program x, y, z ="Orange","Banana"," Cherry " print ( x,y,z ) print ( x+y+z ) print ( xyz ) Orange Banana Cherry OrangeBananaCherry ERROR!Traceback (most recent call last): File "<main.py>", line 4, in <module> NameError : name 'xyz' is not defined
Practice Program x=y=z=100 print(x) print(y) print(z) Output: 100 100 100
a=input("Enter value for a") b=20 c=30 print ( c+b ) print(type(a)) print(type(b )) Output: Enter value for a5 50 <class ' str '> < class ' int '>
x, y = 2, 3 x , y = y, x print 'x =', x print 'y =', y Output: x = 3 y = 2
Practice Program x = 349 # int y = 53.52 # float z = -232.23e100 # float in scientific notation w = 2j # complex print(type(x)) print(type(y)) print(type(z)) print(type(w) Output: <class ' int '> < class 'float '> < class 'float '> < class 'complex'>
Escape Sequence
Practice Program print('Hello') print('Hello") print('Let's Go') print('Let\'s Go') print ("Hello") print("Let's Go!') print("Let's Go!")
Practice Program x = 42 print ("The value of x is ", x, ".“) x = 42 print "$" + x x = 42 print ("$" + str (x))
Practice Program x = int (1) # x will be 1 y = int (2.8) # y will be 2 z = int ("3") # z will be 3 x = float (1) # x will be 1.0 y = float (2.8) # y will be 2.8 z = float ("3") # z will be 3.0 w = float (" 4.2 ") # w will be 4.2 x = str ("s1") # x will be 's1 ' y = str (2) # y will be '2' z = str (3.0) # z will be '3.0 '
Methods in string upper() lower() capitalize() count(s) find(s) rfind (s) index(s) strip(), lstrip (), rstrip () replace(a, b) expandtabs () split() join() center(), ljust (), rjust ()
Indexing s = " Hello " print (s) # Multiline strings s1 = """ This is the example line . Example of a Python strings with multiple lines This is the fourth line . """ print (s1) s2 = "Hello , World !" print (s2 [1]) print (s2 [2:5])
Negative Indexing # Negative Indexing - To start the slice from the end of the string : s2 = " Hello World !" print (s2 [ -5: -2]) s = " Hello World !" print (s. len ()) # Length of a string print (s. lower ()) # Convert the string into lower case print (s. upper ()) # Convert the string into upper case print (s. strip ()) # Remove the white spaces in the string
Practice Program # Negative Indexing - To start the slice from the end of the string : s2 = " Hello World !" print (s2 [ -5: -2]) s = " Hello World !" print (s. len ()) # Length of a string print (s. lower ()) # Convert the string into lower case print (s. upper ()) # Convert the string into upper case print (s. strip ()) # Remove the white spaces in the string
Membership "Membership" in Python can refer to two distinct concepts: Python Membership Operators : These are operators used to test for the presence or absence of a value within a sequence (like a string, list, tuple, set, or dictionary). The in operator returns True if the specified value is found in the sequence, and False otherwise. The not in operator returns True if the specified value is not found in the sequence, and False otherwise .
List It is a general purpose most widely used in data structures List is a collection which is ordered and changeable and allows duplicate members.(Grow and shrink as needed, sequence type, sortable ). To use a list, you must declare it first. Do this using square brackets and separate values with commas.We can construct / create list in many ways . Ex :>>> list1=[1,2,3,'A','B',7,8,[10,11 ]] >>> print(list1 ) Output: [ 1, 2, 3, 'A', 'B', 7, 8, [10, 11]]
List A container that holds a number of other objects, in a given order Defined in square brackets a = [1, 2, 3, 4, 5] print a[1] # number 2 some_list = [] some_list.append ("foo") some_list.append (12) print len ( some_list ) # 2
a = [ 98, "bottles of beer", ["on", "the", "wall"]] Flexible arrays Same operators as for strings a+b , a*3, a[0], a[-1], a[1:], len (a) Item and slice assignment a[0] = 98 a[1:2] = ["bottles", "of", "beer"] -> [98, "bottles", "of", "beer", ["on", "the", "wall"]] del a[-1] # -> [98, "bottles", "of", "beer"]
Operations in List append insert index count sort reverse remove pop Extend Indexing e.g., L[ i ] Slicing e.g ., L[1:5] Concatenation e.g ., L + L Repetition e.g., L * 5 Membership test e.g., ‘a’ in L Length e.g ., len (L)
Nested List List in a list E.g., >>> s = [1,2,3] >>> t = [‘begin’, s, ‘end’] >>> t [‘begin’, [1, 2, 3], ‘end’] >>> t[1][1] 2
Operations on Lists >>> li = [1, 11, 3, 4, 5] >>> li.append (‘a’) # Note the method syntax >>> li [1, 11, 3, 4, 5, ‘a’] >>> li.insert (2, ‘ i ’) >>> li [1, 11, ‘ i ’, 3, 4, 5, ‘a’]
Operations on Lists Lists have many methods, including index, count, remove, reverse, sort >>> li = [‘a’, ‘b’, ‘c’, ‘b’] >>> li.index (‘b’) # index of 1 st occurrence 1 >>> li.count (‘b’) # number of occurrences 2 >>> li.remove (‘b’) # remove 1 st occurrence >>> li [‘a’, ‘c’, ‘b’]
Operations on Lists >>> li = [5, 2, 6, 8] >>> li.reverse () # reverse the list *in place* >>> li [8, 6, 2, 5] >>> li.sort () # sort the list *in place* >>> li [2, 5, 6, 8] >>> li.sort ( some_function ) # sort in place using user-defined comparison
The extend method vs + + creates a fresh list with a new memory ref extend operates on list li in place. >>> li.extend ([9, 8, 7]) >>> li [1, 2, ‘ i ’, 3, 4, 5, ‘a’, 9, 8, 7] Potentially confusing : extend takes a list as an argument. append takes a singleton as an argument . >>> li.append ([10, 11, 12]) >>> li [1, 2, ‘ i ’, 3, 4, 5, ‘a’, 9, 8, 7, [10, 11, 12 ]]
Iterating over the list list = ['M','R','C','E','T '] i = 1 # Iterating over the list for a in list: print ('college ', i ,' is ',a) i = i+1 Output: college 1 is M college 2 is R college 3 is C college 4 is E college 5 is T
Tuple What is a tuple? A tuple is an ordered collection which cannot be modified once it has been created. In other words, it's a special array, a read-only array . How to make a tuple? In round brackets E.g., >>> t = () >>> t = (1, 2, 3) >>> t = (1, ) >>> t = 1, >>> a = (1, 2, 3, 4, 5) >>> print a[1] # 2
Access individual members of a tuple, list, or string using square bracket “array” notation Note that all are 0 based… >>> tu = (23, ‘ abc ’ , 4.56, (2,3), ‘ def ’ ) >>> tu [1] # Second item in the tuple. ‘ abc ’ >>> li = [ “ abc ” , 34, 4.34, 23] >>> li[1] # Second item in the list. 34 >>> st = “Hello World” >>> st [1] # Second character in string. ‘e’
>>> t = (23, ‘ abc ’ , 4.56, (2,3), ‘ def ’ ) Positive index: count from the left, starting with 0 >>> t[1] ‘ abc ’ Negative index: count from right, starting with –1 >>> t[-3] 4.56
>>> t = (23, ‘ abc ’ , 4.56, (2,3), ‘ def ’ ) Return a copy of the container with a subset of the original members. Start copying at the first index, and stop copying before second. >>> t[1:4] (‘ abc ’, 4.56, (2,3)) Negative indices count from end >>> t[1:-1] (‘ abc ’, 4.56, (2,3))
>>> t = (23, ‘ abc ’ , 4.56, (2,3), ‘ def ’ ) Omit first index to make copy starting from beginning of the container >>> t[:2] (23, ‘ abc ’) Omit second index to make copy starting at first index and going to end >>> t[2:] (4.56, (2,3), ‘ def ’)
[ : ] makes a copy of an entire sequence >>> t[:] (23, ‘ abc ’, 4.56, (2,3), ‘ def ’) Note the difference between these two lines for mutable sequences >>> l2 = l1 # Both refer to 1 ref, # changing one affects both >>> l2 = l1[:] # Independent copies, two refs
‘in’ operator Boolean test whether a value is inside a container: >>> t = [1, 2, 4, 5] >>> 3 in t False >>> 4 in t True >>> 4 not in t False For strings, tests for substrings >>> a = ' abcde ' >>> 'c' in a True >>> 'cd' in a True >>> 'ac' in a False Be careful: the in keyword is also used in the syntax of for loops and list comprehensions
The + Operator The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments. >>> (1, 2, 3) + (4, 5, 6) (1, 2, 3, 4, 5, 6) >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] >>> “Hello” + “ ” + “World” ‘Hello World’
The * Operator The * operator produces a new tuple, list, or string that “repeats” the original content. >>> (1, 2, 3) * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> “Hello” * 3 ‘ HelloHelloHello ’
Iterating over a dictionary # creating a dictionary college = {" ces":"block1","it":"block2","ece":"block3 "} # Iterating over the dictionary to print keys print ('Keys are :') for keys in college : print (keys ) # Iterating over the dictionary to print values print ('Values are :') for blocks in college.values (): print(blocks) Output: Keys are: ces it ece Values are: block1 block2 block3
Operations on Tuple Indexing e.g ., T[ i ] Slicing e.g., T[1:5] Concatenation e.g., T + T Repetition e.g., T * 5 Membership test e.g., ‘a’ in T Length e.g., len (T)
List vs Tuple What are common characteristics? Both store arbitrary data objects Both are of sequence data type What are differences? Tuple doesn’t allow modification Tuple doesn’t have methods Tuple supports format strings Tuple supports variable length parameter in function call. Tuples slightly faster
Lists are mutable >>> li = [ ‘ abc ’ , 23, 4.34, 23] >>> li[1] = 45 >>> li [‘ abc ’, 45, 4.34, 23] We can change lists in place. Name li still points to the same memory reference when we’re done.
Tuples are immutable >>> t = (23, ‘ abc ’ , 4.56, (2,3), ‘ def ’ ) >>> t[2] = 3.14 Traceback (most recent call last): File "<pyshell#75>", line 1, in - toplevel - tu [2] = 3.14 TypeError : object doesn't support item assignment You can’t change a tuple. You can make a fresh tuple and assign its reference to a previously used name. >>> t = (23, ‘ abc ’ , 3.14, (2,3), ‘ def ’ ) The immutability of tuples means they’re faster than lists.
Summary: Tuples vs. Lists Lists slower but more powerful than tuples Lists can be modified, and they have lots of handy operations and methods Tuples are immutable and have fewer features To convert between tuples and lists use the list() and tuple() functions: li = list( tu ) tu = tuple(li)
Dictionaries Dictionaries: curly brackets What is dictionary? Refer value through key ; “associative arrays” Like an array indexed by a string An unordered set of key: value pairs Values of any type; keys of almost any type {" name":"Guido ", "age":43, (" hello","world "):1, 42:"yes", "flag": [" red","white","blue "]} d = { "foo" : 1, "bar" : 2 } print d["bar"] # 2 some_dict = {} some_dict ["foo"] = "yow!" print some_dict.keys () # ["foo"]
Dictionaries Keys must be immutable : numbers, strings, tuples of immutables these cannot be changed after creation reason is hashing (fast lookup technique) not lists or other dictionaries these types of objects can be changed "in place" no restrictions on values Keys will be listed in arbitrary order again, because of hashing
CONTROL FLOW, LOOPS Boolean values and operators Conditional ( if) Alternative ( if-else) Chained conditional ( if- elif -else) Iteration : while, for, break, continue.
Boolean values and operators Boolean values represent truth values and can only be one of two states: True or False . These values belong to the bool data type. Boolean Operators : Logical AND Returns True if both operands are True. Otherwise, returns False. Logical OR Returns True if at least one of the operands is True. Returns False only if both operands are False. Logical NOT A unary operator that inverts the Boolean value of its operand. If the operand is True, not returns False. If the operand is False, not returns True.
Boolean values and operators Comparison Operators : Boolean values are frequently generated through comparison operators, which evaluate relationships between values and return a bool result: == (Equal to) != (Not equal to) > (Greater than) < (Less than) >= (Greater than or equal to) <= (Less than or equal to)
Boolean values and operators
Boolean values and operators
Boolean values and operators
Conditional Statement
Nested if
Odd or Even Program x= int (input("Enter the Value for x :")) if(x%2 ==0): print ('Even ') else: print('Odd')
Program x = 34 - 23 # A comment. y = “Hello” # Another one. z = 3.45 if z == 3.45 or y == “Hello”: x = x + 1 y = y + “ World” # String concat . print x print y
r ange() Function To iterate over a sequence of numbers, the built-in function range() comes in handy. It generates arithmetic progressions. Example for i in range(5): print( i ) Output 1 2 3 4
Program a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range( len (a)): print( i , a[ i ]) Output: 0 Mary 1 had 2 a 3 little 4 lamb
While loop a = 10 while a > 0: print a a -= 1 Output: 10 9 8 7 6 5 4 3 2 1
Fibonacci series # Fibonacci series: # the sum of two elements defines the next a , b = , 1 while a < 10 : print(a ) a , b = b, a+b Output: 1 1 2 3 5 8
For loops x = 4 for i in range(0, x): print( i ) Output: 1 2 3
For loop Output: 3 1 4 1 5 9 a = [3, 1, 4, 1, 5, 9] for i in range( len (a)): print a[ i ]
Nested for loops for i in range(1,6 ): for j in range(0,i ): print( i , end=" ") print('') Output: 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Practice Program # Program to display all the elements before number 88 for num in [11, 9, 88, 10, 90, 3, 19 ]: print( num ) if( num ==88 ): print(“Number 88 found ") print ("Terminating the loop ") break Output: 11 9 88 The number 88 is found
Break for letter in "Python": if letter == "h ": break print ("Current Letter :", letter ) Output: Current Letter : P Current Letter : y Current Letter : t
for num in range(2, 10): if num % 2 == 0: print( f"Found an even number { num }") continue print( f"Found an odd number { num }") Output: Found an even number 2 Found an odd number 3 Found an even number 4 Found an odd number 5 Found an even number 6 Found an odd number 7 Found an even number 8 Found an odd number 9
break and continue Statements for n in range(2, 10): for x in range(2, n): if n % x == 0: print(f"{n} equals {x} * {n//x}") break Output: 4 equals 2 * 2 6 equals 2 * 3 8 equals 2 * 4 9 equals 3 * 3
Modules Python module can be defined as a python program file which contains a python code including python functions, class, or variables. Python code file saved with the extension (. py ) is treated as the module. We may have a runnable code inside the python module. A module in Python provides us the flexibility to organize the code in a logical way. To use the functionality of one module into another, we must have to import the specific module . Syntax : import <module-name > Every module has its own functions, those can be accessed with . (dot)
Modules To import a module directly you just put the name of the module or package after the import keyword. •Please note that this statement is case sensitive. •You can also use the asterisk ( * ) as a wild card. The following statement will import every function and property contained in the math package. from math import *
Why use modules? Code reuse Routines can be called multiple times within a program Routines can be used from multiple programs Namespace partitioning Group data together with functions used for that data Implementing shared services or data Can provide global data structure that is accessed by multiple subprograms
Modules Modules are functions and variables defined in separate files Items are imported using from or import from module import function function() import module module.function() Modules are namespaces Can be used to organize variable names, i.e. atom.position = atom.position - molecule.position
Modules Access other code by importing modules import math print math.sqrt(2.0) or: from math import sqrt print sqrt(2.0)
Modules or: from math import * print sqrt(2.0) Can import multiple modules on one line: import sys, string, math Only one " from x import y " per line
def foo(x): y = 10 * x + 2 return y All variables are local unless specified as global Arguments passed by value
def foo(x): y = 10 * x + 2 return y print foo(10) # 102