Curriculum
Course: Ncert - Class 11- Computer Science
Login
Text lesson

Detailed Note – 3 – Chapter 5 -Getting Started with Python

Mapping

Mapping Data Type – Dictionary:

  • A dictionary in Python holds data items in key-value pairs, enclosed in curly braces {}.
  • Each key is separated from its value by a colon : sign.
  • Dictionaries permit faster access to data, and the keys are usually strings, while the values can be any data type.
  • Example
python

dict1 = {‘Fruit’: ‘Apple’, ‘Climate’: ‘Cold’, ‘Price(kg)’: 120}

print(dict1) # Output: {‘Fruit’: ‘Apple’, ‘Climate’: ‘Cold’, ‘Price(kg)’: 120}

print(dict1[‘Price(kg)’]) # Output: 120

  1. Mutable and Immutable Data Types:

    • Python data types can be classified into mutable and immutable types based on whether their values can be changed after creation.
    • Mutable data types allow changes to their values after creation, while immutable data types do not.
    • Attempting to update the value of an immutable variable creates a new object with the updated value, as the original value cannot be modified in place.
    • Examples of immutable data types include integers, floats, strings, and tuples, while examples of mutable data types include lists and dictionaries.

Deciding Usage of Python Data Types

  1. Lists:

    • Preferred when needing a simple iterable collection of data that may undergo frequent modifications.
    • Example: Storing the names of students in a class, where the list can be easily updated when new students join or leave the course.
  2. Tuples:

    • Used when no change in the data is required.
    • Example: Storing names of months in a year, where the data is static and does not need to be modified.
  3. Sets:

    • Preferable when needing uniqueness of elements and to avoid duplicacy.
    • Example: Storing a list of artifacts in a museum, where each artifact needs to be unique.
  4. Dictionaries:

    • Advised when the data is being constantly modified or when fast lookup based on a custom key or logical association between key-value pairs is needed.
    • Example: Storing a mobile phone book, where each contact (key) is associated with a phone number (value), allowing for quick retrieval of phone numbers based on contact names.

OPERATORS

  1. Arithmetic Operators:

    • Perform basic arithmetic operations like addition, subtraction, multiplication, division, modulus, floor division, and exponentiation.
  2. Relational Operators:

    • Compare the values of operands to determine their relationship, such as equality, inequality, greater than, less than, etc.
  3. Assignment Operators:

    • Assign or change the value of a variable. For example, = assigns a value to a variable.
  4. Logical Operators:

    • Used to perform logical operations such as AND, OR, and NOT. They evaluate expressions and return True or False.
  5. Identity Operators:

    • Determine whether the value of a variable is of a certain type or whether two variables are referring to the same object.
  6. Membership Operators:

    • Check if a value is a member of a given sequence, such as a list, tuple, or string.

EXPRESSIONS

In Python, expressions are combinations of constants, variables, and operators that always evaluate to a value. Here are some examples of valid expressions:

  1. 100
  2. num
  3. num - 20.4
  4. 3.0 + 3.14
  5. 23 / 3 - 5 * 7 * (14 - 2)
  6. "Global" + "Citizen"

Precedence of operators determines the order in which operators are evaluated within an expression. Unary operators, which operate on a single operand, typically have higher precedence than binary operators, which operate on two operands. Both the minus (-) and plus (+) operators can act as unary or binary operators. The not operator is a unary logical operator.

For example, let’s evaluate the expression 15.0 / 4 + (8 + 3.0):

  1. 15.0 / 4 + (8.0 + 3.0) (Step 1: Parentheses evaluated first)
  2. 15.0 / 4.0 + 11.0 (Step 2: Division and addition within parentheses)
  3. 3.75 + 11.0 (Step 3: Addition)
  4. 14.75 (Step 4: Final result)

STATEMENT

In Python, a statement is a unit of code that the Python interpreter can execute. Here’s an example illustrating different types of statements:

python

x = 4 # Assignment statement

cube = x ** 3 # Assignment statement

print(x, cube) # Print statement

In this example:

  • x = 4 and cube = x ** 3 are assignment statements, where values are assigned to variables.
  • print(x, cube) is a print statement, which outputs the values of variables x and cube.

INPUT AND OUTPUT

Input:

To receive input from the user, Python provides the input() function. It prompts the user to enter data and accepts it as a string.

python

fname = input(“Enter your first name: “) age = input(“Enter your age: “)

In this example, fname and age variables will contain the strings entered by the user. It’s important to note that all input received using input() is treated as strings.

Output:

Python offers the print() function for displaying output to the user.

python

print(“Hello”) print(10 * 2.5) print(“I” + ” love “ + “my “ + “country”) print(“I’m”, 16, “years old”)

In the above example:

  • The first print() statement displays the string “Hello”.
  • The second print() statement evaluates the expression 10 * 2.5 and displays the result.
  • The third print() statement concatenates multiple strings using the + operator.
  • The fourth print() statement demonstrates how multiple arguments can be passed to the print() function, separated by commas.

Type Conversion:

If necessary, you can convert the input received from the user to the desired data type using typecasting.

python

age = int(input(“Enter your age: “))

Here, the int() function converts the input string to an integer. However, if the input cannot be converted to the specified data type, it will result in an error.

TYPE CONVERSION

Type conversion is a crucial aspect of programming, especially when dealing with different data types. Let’s break down the concept and how it works:

Implicit Conversion:

  • Implicit conversion occurs automatically when the interpreter understands the need to convert one data type to another.
  • For example, adding an integer and a float will result in the float being implicitly converted to an integer before addition.

Explicit Conversion:

  • Explicit conversion, also known as type casting, occurs when the programmer forces the conversion of one data type to another.
  • This is done using specific functions or syntax to convert data from one type to another.

Example of Explicit Conversion:

python
# Explicit type casting priceIcecream = 25 priceBrownie = 45 totalPrice = priceIcecream + priceBrownie # Converting totalPrice to a string before printing print(“The total in Rs.” + str(totalPrice))

In this example:

  • totalPrice is calculated as the sum of priceIcecream and priceBrownie.
  • To concatenate totalPrice with a string for printing, we use str(totalPrice) to explicitly convert it to a string.

Risks of Explicit Conversion:

  • Explicit conversion may lead to loss of information. For example, converting a float to an integer will discard the fractional part.
  • It’s essential to be cautious when explicitly converting data types to avoid unintended consequences.

Example of String to Integer Conversion:

python
# Explicit type conversion – string to integer price = int(icecream) + int(brownie) print(“Total Price Rs.” + str(price))

Here:

  • icecream and brownie are initially strings representing prices.
  • We use int() to explicitly convert them to integers before performing addition.

DEBUGGING

Debugging is an essential skill for programmers to master, as it helps identify and resolve issues in code. Let’s delve into the different types of errors and how to handle them effectively:

Syntax Errors:

  • Syntax errors occur due to violations of Python’s rules, resulting in incorrect code structure.
  • The interpreter halts execution upon encountering a syntax error and displays error messages to pinpoint the issue.
  • Common syntax errors include missing parentheses, unmatched quotes, and incorrect indentation.
  • To resolve syntax errors, carefully review the code, paying attention to syntax rules and correcting any mistakes accordingly.

Logical Errors:

  • Logical errors, also known as semantic errors, cause programs to produce incorrect output due to flawed logic.
  • Unlike syntax errors, programs with logical errors run without interruption, making them harder to detect.
  • Identifying logical errors involves analyzing the program’s output and tracing back to find flaws in the underlying logic.
  • Techniques like debugging tools, code reviews, and test cases can help uncover and rectify logical errors.

Runtime Errors:

  • Runtime errors occur during program execution, often due to unexpected conditions or invalid operations.
  • Examples include division by zero, type mismatch, and index out of range errors.
  • Runtime errors halt program execution and may display error messages indicating the nature of the issue.
  • Handling runtime errors involves implementing error-checking mechanisms, such as try-except blocks, to anticipate and handle potential errors gracefully.
  • Effective runtime error handling enhances program robustness and prevents abrupt terminations.

Example Program:

python
# Example of a program that may encounter runtime errors num1 = 10.0 num2 = int(input(“num2 = “)) # Handle potential division by zero error try: result = num1 / num2 print(“Result:”, result) except ZeroDivisionError: print(“Error: Division by zero is not allowed.”) except ValueError: print(“Error: Please enter a valid integer value for num2.”)

By understanding and addressing different types of errors, programmers can write more reliable and robust code, ensuring smooth program execution and minimizing disruptions.

×

Cart