Python Data Types Session 2
Python Data Types Python has the following standard or built-in data types: 1. Numeric A numeric value is any representation of data which has a numeric value. Python identifies three types of numbers: •Integer: Positive or negative whole numbers (without a fractional part) •Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientific notation •Complex number: A number with a real and imaginary component represented as x+yj.
2. Boolean Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. true and false are not valid booleans and Python will throw an error for them. 3. Sequence Type A sequence is an ordered collection of similar or different data types. Python has the following built-in sequence data types: •String: A string value is a collection of one or more characters put in single, double or triple quotes. •List : A list object is an ordered collection of one or more data items, not necessarily of the same type, put in square brackets. •Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of the same type, put in parentheses.
type() function Python has an in-built function type() to ascertain the data type of a certain value.
Mutable and Immutable Objects Number values, strings, and tuple are immutable, which means their contents can't be altered after creation. On the other hand, collection of items in a List or Dictionary object can be modified. It is possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable objects.
Operator Description + (Addition) Adds operands on either side of the operator. - (Subtraction) Subtracts the right-hand operand from the left-hand operand. * (Multiplication) Multiplies values on either side of the operator. / (Division) Divides the left-hand operand by the right-hand operand. % (Modulus) Returns the remainder of the division of the left-hand operand by right-hand operand. ** (Exponent) Calculates the value of the left-operand raised to the right-operand. Arithmetic Operators
Operator Description > True if the left operand is higher than the right one < True if the left operand is lower than right one == True if the operands are equal != True if the operands are not equal >= True if the left operand is higher than or equal to the right one <= True if the left operand is lower than or equal to the right one Comparison and Logical Operators in Python
Operator Description and True if both are true or True if at least one is true not Returns True if an expression evaluates to false and vice-versa
list1 = [] list2 = [] list3=list1 if (list1 == list2): print("True") else: print("False") if (list1 is list2): print("True") else: print("False") if (list1 is list3): print("True") else: print("False") list3 = list3 + list2 if (list1 is list3): print("True") else: print("False") True as both list1 and list2 are empty lists. False because two empty lists are at different memory locations. “True” as both list1 and list3 are pointing to the same object. “False” because concatenation of two list is always produce a new list.
Escape Sequences in Strings Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways: • You may want to suppress the special interpretation that certain characters are usually given within a string. • You may want to apply special interpretation to characters in a string which would normally be taken literally. It can be done using a backslash () character. A backslash character in a string indicates that one or more characters that follow it should be treated specially.
print(I want to print a single quote (') character.') SyntaxError: invalid syntax print(I want to print a single quote (') character.') I want to print a single quote (') character.
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
Escape Sequence “Escaped” Interpretation a ASCII Bell (BEL) character b ASCII Backspace (BS) character t ASCII Horizontal Tab (TAB) character v ASCII Vertical Tab (VT) character
Type Conversions X=13.14 int(x) will convert into int and display 13 X= 15 Float(x) will convert it into float and display 15.0 a= 12.24 Complex(a) will convert it into complex number 12.24+0j a=11 b=8 Complex(a,b) will give 11+8j
If - Statement Already done in Lab
Python programming language provides following types of loops to handle looping requirements. Loops in PYTHON While Loop: In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed. while expression: statement(s)
count = 0 while count < 5: print(count) count += 1 Using else statement with while loops: While loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
count = 0 while (count < 3): count = count + 1 print("Hello") else: print("In Else Block")
for in Loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages. For loops iterate over a given sequence. for iterator_var in sequence: statements(s)
a= ["ML", "Cprogramming", "Unix"] for i in a: print(i) s = "MACHINE" for i in s : print(i)
The break Statement With the break statement we can stop the loop before it has looped through all the items: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break
The continue Statement With the continue statement we can stop the current iteration of the loop, and continue with the next: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
The range() Function The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. for x in range(5): print(x) for x in range(3, 6): print(x)
The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): for x in range(2, 10, 3): print(x)
Else in For Loop The else keyword in a for loop specifies a block of code to be executed when the loop is finished: print all numbers from 0 to 5, and print a message when the loop has ended: for x in range(6): print(x) else: print("Finally finished!")
Nested Loops A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)

Learn more about the concepts of Data Types in Python

  • 1.
  • 2.
    Python Data Types Pythonhas the following standard or built-in data types: 1. Numeric A numeric value is any representation of data which has a numeric value. Python identifies three types of numbers: •Integer: Positive or negative whole numbers (without a fractional part) •Float: Any real number with a floating point representation in which a fractional component is denoted by a decimal symbol or scientific notation •Complex number: A number with a real and imaginary component represented as x+yj.
  • 3.
    2. Boolean Data withone of two built-in values True or False. Notice that 'T' and 'F' are capital. true and false are not valid booleans and Python will throw an error for them. 3. Sequence Type A sequence is an ordered collection of similar or different data types. Python has the following built-in sequence data types: •String: A string value is a collection of one or more characters put in single, double or triple quotes. •List : A list object is an ordered collection of one or more data items, not necessarily of the same type, put in square brackets. •Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of the same type, put in parentheses.
  • 4.
    type() function Python hasan in-built function type() to ascertain the data type of a certain value.
  • 5.
    Mutable and ImmutableObjects Number values, strings, and tuple are immutable, which means their contents can't be altered after creation. On the other hand, collection of items in a List or Dictionary object can be modified. It is possible to add, delete, insert, and rearrange items in a list or dictionary. Hence, they are mutable objects.
  • 6.
    Operator Description + (Addition)Adds operands on either side of the operator. - (Subtraction) Subtracts the right-hand operand from the left-hand operand. * (Multiplication) Multiplies values on either side of the operator. / (Division) Divides the left-hand operand by the right-hand operand. % (Modulus) Returns the remainder of the division of the left-hand operand by right-hand operand. ** (Exponent) Calculates the value of the left-operand raised to the right-operand. Arithmetic Operators
  • 7.
    Operator Description > Trueif the left operand is higher than the right one < True if the left operand is lower than right one == True if the operands are equal != True if the operands are not equal >= True if the left operand is higher than or equal to the right one <= True if the left operand is lower than or equal to the right one Comparison and Logical Operators in Python
  • 10.
    Operator Description and Trueif both are true or True if at least one is true not Returns True if an expression evaluates to false and vice-versa
  • 12.
    list1 = [] list2= [] list3=list1 if (list1 == list2): print("True") else: print("False") if (list1 is list2): print("True") else: print("False") if (list1 is list3): print("True") else: print("False") list3 = list3 + list2 if (list1 is list3): print("True") else: print("False") True as both list1 and list2 are empty lists. False because two empty lists are at different memory locations. “True” as both list1 and list3 are pointing to the same object. “False” because concatenation of two list is always produce a new list.
  • 16.
    Escape Sequences inStrings Sometimes, you want Python to interpret a character or sequence of characters within a string differently. This may occur in one of two ways: • You may want to suppress the special interpretation that certain characters are usually given within a string. • You may want to apply special interpretation to characters in a string which would normally be taken literally. It can be done using a backslash () character. A backslash character in a string indicates that one or more characters that follow it should be treated specially.
  • 17.
    print(I want toprint a single quote (') character.') SyntaxError: invalid syntax print(I want to print a single quote (') character.') I want to print a single quote (') character.
  • 18.
    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
  • 19.
    Escape Sequence “Escaped”Interpretation a ASCII Bell (BEL) character b ASCII Backspace (BS) character t ASCII Horizontal Tab (TAB) character v ASCII Vertical Tab (VT) character
  • 20.
    Type Conversions X=13.14 int(x) willconvert into int and display 13 X= 15 Float(x) will convert it into float and display 15.0 a= 12.24 Complex(a) will convert it into complex number 12.24+0j a=11 b=8 Complex(a,b) will give 11+8j
  • 21.
  • 22.
    Python programming languageprovides following types of loops to handle looping requirements. Loops in PYTHON While Loop: In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in program is executed. while expression: statement(s)
  • 23.
    count = 0 whilecount < 5: print(count) count += 1 Using else statement with while loops: While loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed. The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
  • 24.
    count = 0 while(count < 3): count = count + 1 print("Hello") else: print("In Else Block")
  • 25.
    for in Loop:For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for each loop in other languages. For loops iterate over a given sequence. for iterator_var in sequence: statements(s)
  • 26.
    a= ["ML", "Cprogramming","Unix"] for i in a: print(i) s = "MACHINE" for i in s : print(i)
  • 27.
    The break Statement Withthe break statement we can stop the loop before it has looped through all the items: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break
  • 28.
    The continue Statement Withthe continue statement we can stop the current iteration of the loop, and continue with the next: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x)
  • 29.
    The range() Function Therange() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. for x in range(5): print(x) for x in range(3, 6): print(x)
  • 30.
    The range() functiondefaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): for x in range(2, 10, 3): print(x)
  • 31.
    Else in ForLoop The else keyword in a for loop specifies a block of code to be executed when the loop is finished: print all numbers from 0 to 5, and print a message when the loop has ended: for x in range(6): print(x) else: print("Finally finished!")
  • 32.
    Nested Loops A nestedloop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop": Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y)