Module 3. Understanding Data Types

 

Learning Objectives

  • Distinguish between different data types in Python, including numeric types (int, float, complex), text types (str), and Boolean types (bool), and recognize the appropriate usage and characteristics of each data type.
  • Obtain proficiency in handling basic arithmetic operations with different numeric data types and use the type() function to check and confirm the data types of various variables and expressions in Python.
  • Understand string operations, including concatenation, slicing, and formatting, and learn to work with single and double quotes, as well as utilize multi-line strings and escape characters.
  • Convert between different data types using Python’s built-in functions such as int(), float(), and str(), and handle user input by converting it to the required data type for further processing.
  • Use Boolean expressions and operators for decision-making in programs, and understand the application of comparison operators and logical operators (and, or, not) in control flow statements.

 

1.      Numeric Data Types

Data types are fundamental in programming, as they define the kind of data variables can store and the operations they support. Python includes default built-in data types grouped into several categories. These types are used to store different kinds of data. This module will explore commonly used simple data types, including text types, numeric types, and Boolean types.

Data Types Key Words
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
None Type NoneType

 

When computers were initially created, their primary role was to perform complex calculations, and this remains a significant use today. Problems that involve mathematical formulas are straightforward to convert into Python programs. In this section, we will delve deeper into programs specifically designed for numerical computations.

Numbers in Python are divided into three main types: integers, floating-point numbers, and complex numbers. Integers are whole numbers without a fractional component, while floating-point numbers contain a decimal point, making them suitable for representing more precise values. Complex numbers consist of a real part and an imaginary part, denoted by the suffix 'j'. Python provides a wide range of operations for working with these number types, including arithmetic operations, type conversion, and built-in functions for mathematical calculations.

Numeric variables are created when you assign a value to them. To check the type of any object in Python, you can use the type() function.

  

 

Integer

Integers (int) in Python refer to whole numbers that can be positive or negative, without decimal points, and can be of unlimited size.

 

 

Float

A float, or "floating point number," in Python is a number that can be positive or negative and contains one or more decimals.

 

The following program demonstrates basic input handling, arithmetic operations, and output formatting for calculating and displaying the sum and average of three test scores.

 

Example output:

Test Scores Calculator

Enter score 1: 85

Enter score 2: 92

Enter score 3: 78

Sum of the scores: 255.0

Average of the scores: 85.0

 

In the program, the main() function prompts the user to enter three test scores (score1, score2, and score3) using float(input()) to handle decimal input. Then, it calculates the sum of the three scores using total = score1 + score2 + score3. In addition, it calculates the average of the three scores by dividing the total sum by 3 (average = total / 3). Finally, it prints out the calculated sum and average of the scores.

 

Type Conversion

In Python, you can convert between different data types using int() and float() methods. The int() function is used to convert a number or a string containing a numeric value to an integer.

 

The float() function converts a number or a string containing a numeric value to a float.

 

These methods are handy when you need to change the type of a variable or handle different types of numeric inputs in your Python programs.

 

Random Numbers

Python does not have a built-in function to make a random number, but Python has a built-in module called random that can be used to make random numbers. You need to import the random module to generate random numbers. The following code generates and displays a random number between 1 and 6.

 

2.      Strings

In Python, strings can indeed be enclosed in either single (' ') or double (" ") quotation marks, and both are functionally equivalent. This flexibility allows you to choose the style that best fits your needs, especially when dealing with strings that contain quotation marks.

Here are a few examples to demonstrate different usages:

 

If your string contains a single quote, you can use double quotes to avoid needing to escape the single quote, and vice versa.

 

If you need to use the same type of quotation mark inside the string, you can escape it with a backslash (\):

 

Assigning a string to a variable is done with the variable name followed by an equal sign and the string:

 

Multiline Strings

Multi-line strings in Python can be defined using triple quotes, either """ or '''. These are particularly useful for strings that span multiple lines, such as long text blocks, code snippets, or formatted text.

 

 

Slicing Strings

Slicing is a powerful feature in Python that allows you to extract a subset of characters from a string using a specified range of indices. The general syntax for slicing is string[start:end], where start is the index of the first character you want to include, and end is the index of the character you want to stop before (not included in the slice).

Here's an example that demonstrates how to slice a string to get characters from position 2 to 5 (not included):

 

The syntax for slicing can be broken down into three parts:

  • start (optional): The starting index of the slice. The character at this index is included in the slice. If omitted, the slice starts from the beginning of the string.
  • end (optional): The ending index of the slice. The character at this index is not included in the slice. If omitted, the slice goes until the end of the string.
  • step (optional): The step size, or the interval between indices. If omitted, the default step is 1.

 

 

 

You can also specify a step size to skip characters:

 

Negative indices can be used to count from the end of the string:

 

String Concatenation

String concatenation in Python allows you to combine two or more strings into one. This can be done using the + operator. Here are some examples to illustrate this concept:

To concatenate two strings, you simply use the + operator:

 

If you want to add a space between the concatenated strings, you include the space within the quotation marks:

 

String Format

In Python, we cannot combine strings and numbers like this:

 

However, strings and numbers can be combined by utilizing f-strings or the format() method.

Using f-strings is an efficient and powerful way to format strings in Python. They allow you to embed expressions inside string literals using curly braces {}. This makes it easy to combine strings and variables, perform calculations, and format values.

To create an f-string, prefix the string with the letter f and use curly braces {} to include variables or expressions:

 

You also can include variables directly within the curly braces:

 

The format() method provides another way to format strings, which is particularly useful for creating complex formatted strings. This method allows you to insert values into a string using placeholders defined by curly braces {}.

The simplest use of the format() method involves placing curly braces {} within a string and passing the values you want to insert as arguments to the format() method.

 

You can use positional arguments by placing numbers inside the curly braces, indicating the position of the arguments.

 

3.      Boolean

In Python, Booleans are used to evaluate expressions and make decisions as same as in other programming languages. The Boolean data type has two possible values: True and False.

When you compare two values, the expression is evaluated, and Python returns a Boolean value (True or False).

Python supports several comparison operators that return Boolean values:

greater than

less than

==

equal to

!=

not equal to

>=

greater than or equal to

<=

less than or equal to

 

 

Booleans are often used in control flow statements like if statements to determine which block of code should be executed.

 

The bool() function allows you to evaluate any value and returns True or False. This can be particularly useful for checking the truthiness of values.

 

Python also provides logical operators to combine Boolean expressions:

  • and: Returns True if both operands are true
  • or: Returns True if at least one operand is true
  • not: Returns True if the operand is false

 

 

 

4.      Type Conversion

In Python, you can specify a type for a variable using casting, which involves converting a value from one type to another. Python, being an object-oriented language, uses classes to define data types, including its primitive types. Casting is performed using constructor functions like int(), float(), and str().

Casting to Integer

The int() function converts a value to an integer. This can be done from an integer literal, a float literal (by removing all decimals), or a string literal (provided the string represents a whole number).

 

 

Casting to Float

The float() function converts a value to a float. This can be done from an integer literal, a float literal, or a string literal (provided the string represents a float or an integer).

 

Casting to String

The str() function converts a value to a string. This can be done from strings, integer literals, float literals, and many other data types.

 

 

Practical Use Cases

When reading input from a user, it is often read as a string. You might need to convert it to another type for further processing.

 

When dealing with numbers in string format, you need to convert them to the appropriate numeric type before performing calculations.

 

When you need to format numbers as strings for output purposes, you can use str().

 

5.      Operators

Operators are fundamental in programming as they enable you to perform various operations on variables and values. Python supports several types of operators, including arithmetic, comparison, logical, bitwise, assignment, identity, and membership operators.

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

 

Comparison Operators

Comparison operators compare two values and return a Boolean result (True or False).

 

Logical Operators

Logical operators are used to combine conditional statements.

 

Bitwise Operators

Bitwise operators are used to perform bit-level operations on integers.

 

Assignment Operators

Assignment operators are used to assign values to variables.

 

Practical Examples

You can combine different types of operators to create complex expressions.

 

Operators are often used in conditional statements to control the flow of the program.

 

 

 

 

Summary

  1. Python supports various data types, including numeric types (int, float, complex), text types (str), sequence types (list, tuple, range), mapping types (dict), set types (set, frozenset), Boolean types (bool), binary types (bytes, bytearray, memoryview), and NoneType.
  2. Numeric types in Python include integers (whole numbers without decimals), floats (numbers with decimals), and complex numbers (numbers with real and imaginary parts, denoted by 'j').
  3. You can check the type of any object in Python using the type() function and convert between types using int() and float()
  4. A sample Python program can handle input, perform arithmetic operations, and format output to calculate and display the sum and average of test scores.
  5. Python's random module allows generating random numbers, such as a random number between 1 and 6 using the randrange() function.
  6. In Python, strings can be enclosed in single (' ') or double (" ") quotation marks, and multi-line strings can be defined using triple quotes (""" or ''') for text that spans multiple lines.
  7. Slicing allows extraction of a substring using the syntax string[start:end:step], where indices can be positive or negative to count from the start or end of the string.
  8. String concatenation combines strings using the + operator, and spaces can be added within the quotation marks for separation.
  9. String formatting can be achieved using f-strings or the format() method, allowing the embedding of variables and expressions within strings.
  10. Booleans in Python represent truth values (True or False) and are used with comparison operators to evaluate expressions and make decisions.
  11. In Python, Booleans evaluate expressions and make decisions, with two possible values: True and False.
  12. Comparison operators like >, <, ==, !=, >=, and <= return Boolean values when comparing two values.
  13. Booleans are often used in control flow statements like if statements to determine which block of code to execute.
  14. The bool() function can evaluate any value and return True or False, which helps in checking the truthiness of values.
  15. Python logical operators (and, or, not) combine Boolean expressions, allowing complex conditional statements.
  16. Casting in Python involves converting a value from one type to another using functions like int(), float(), and str().
  17. Arithmetic operators (+, -, *, /, %, **, //) perform basic mathematical operations, while comparison operators return Boolean results.
  18. Logical operators (and, or, not) are used to combine conditional statements, and bitwise operators perform bit-level operations on integers.
  19. Assignment operators (+=, -=, *=, /=, %=, **=, //=) assign values to variables and can perform operations simultaneously.
  20. Combining different types of operators in complex expressions and conditional statements helps control the program's flow effectively.

 

 

 

Programming Exercises

 

Exercise 1: Basic Numeric Operations

Write a program that prompts the user to enter two numbers. Calculate and display the sum, difference, product, and quotient of these two numbers. Check and display the data types of the entered numbers and the results.

 

Exercise 2: Random Number Generator

Write a program that imports the random module. Generate and print five random integers between 1 and 100. Then, generate and print a random floating-point number between 0 and 1.

 

Exercise 3: String Manipulation

Write a program that prompts the user to enter their first name and last name. Concatenate the first name and last name into a full name and print it. Then, slice and print the first three letters of the first name and the last three letters of the last name.

 

Exercise 4: Type Conversion

Write a program that prompts the user to enter a floating-point number. Convert the floating-point number to an integer and print the result. Then, convert the integer back to a floating-point number and print the result.

 

Exercise 5: Test Scores Calculator

Write a program that prompts the user to enter three test scores. Calculate the sum and average of the test scores. Print the sum and average of the scores with appropriate labels.

 

Exercise 6: String Handling and Quotation Marks

Write a Python program that assigns the following text to a variable and prints it: He said, "Python's flexibility with strings is amazing!". Use both single and double quotation marks appropriately to avoid escape characters.

 

Exercise 7: Multi-line Strings and Slicing

Create a multi-line string variable with a short paragraph about your favorite hobby. Print the entire paragraph and then print a slice of the string that contains the first ten characters. Finally, print every second character from the slice.

 

Exercise 8: String Concatenation

Write a Python program that asks the user to input their first name and last name separately. Concatenate these inputs with a space in between to form their full name, and print the full name with the message: "Your full name is: <full_name>".

 

Exercise 9: String Formatting with f-strings

Develop a Python program that prompts the user to enter their name, age, and favorite color. Use an f-string to format and print a message that says: "Hello, my name is <name>, I am <age> years old, and my favorite color is <color>."

 

Exercise 10: Boolean Expressions and Comparison Operators

Write a Python program that asks the user for the price of two different items. Compare the prices using comparison operators and print out which item is more expensive, or if they are priced the same. Use the format method to create the output message.