Humanities/Arts Exam  >  Humanities/Arts Notes  >  Informatics Practices for Class 11  >  Chapter Notes: Brief Overview of Python

Brief Overview of Python Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts PDF Download

Introduction to Python

  • An ordered set of instructions or commands to be executed by a computer is called a program.
  • The language used to specify those instructions is called a programming language, such as Python, C, C++, Java, etc.
  • Python is a popular and easy-to-learn programming language, created by Guido van Rossum in 1991.
  • It is widely used in software development, web development, scientific computing, big data, and artificial intelligence.
  • Programs in this book are written using Python 3.7.0, but any Python 3 version can be used.

Working with Python

  • To write and run a Python program, a Python interpreter must be installed, or an online Python interpreter can be used.
  • The interpreter, also called the Python shell, displays a prompt (>>>) indicating it is ready to receive instructions.
  • Commands or statements can be typed at the prompt for execution.

Execution Modes

Python programs can be run in two modes: Interactive mode and Script mode.

Interactive Mode:

  • Allows typing Python statements directly at the >>> prompt.
  • Pressing Enter executes the statement and displays the result immediately.
  • Convenient for testing single-line code but does not allow saving statements for future use.
  • Statements must be retyped to run again.

Script Mode:

  • Involves writing a Python program in a file with a .py extension, known as a script.
  • Scripts can be created using any editor, such as Python’s built-in IDLE editor.
  • To create a script in IDLE, select File > New File, write the program, and save it with a .py extension.
  • Scripts are saved by default in the Python installation folder.
  • To execute a script in IDLE, open the program, go to Run > Run Module, and the output appears in th

Comments:

  • Comments are non-executable remarks or notes in the source code to improve readability.
  • Single-line comments start with #, and everything after # on that line is ignored by the interpreter.
  • Multiline comments can be added using triple quotes (''') or (""") for multiline strings. 
  • Example:  """ This is a multiline comment """.

Python Keywords

  • Keywords are reserved words with specific meanings to the Python interpreter.
  • Python is case-sensitive, so keywords must be written exactly as specified (e.g., False, class, finally, is, return, None, continue, for, lambda, try, True, def, from, nonlocal, while, and, del, global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, raise).

Identifiers

Identifiers are names used to identify variables, functions, or other entities in a program.

Rules for naming identifiers:

  • Must begin with an uppercase or lowercase letter or an underscore (_).
  • Can be followed by any combination of letters (a-z, A-Z), digits (0-9), or underscores.
  • Cannot start with a digit.
  • Can be of any length, but should be short and meaningful.
  • Cannot be a keyword or reserved word.
  • Cannot include special symbols like !, @, #, $, %, etc.

Example: For calculating the average of marks in Maths, English, and Informatics Practices, use meaningful identifiers like marksMaths, marksEnglish, marksIP, and avg instead of vague ones like a, b, c.

Variables

  • A variable is an identifier whose value can change.
  • Variable names must be unique within a program.
  • Values can be strings (e.g., 'b', 'Global Citizen'), numbers (e.g., 10, 71, 80.52), or alphanumeric combinations (e.g., 'b10').
  • Variables are created and assigned values using assignment statements (e.g., gender = 'M', message = "Keep Smiling", price = 987.9).
  • Variables must be assigned values before use, or an error occurs.
  • The interpreter replaces a variable name with its value during execution.

Data Types

  • Every value in Python belongs to a specific data type, which determines the operations that can be performed on it.
  • Data types include Number, Boolean, Sequence (Strings, Lists, Tuples), Mapping (Dictionary), Sets, and None.

Number

Number data type stores numerical values and is classified into:

  • int: Integer numbers (e.g., -12, -3, 0, 123).
  • float: Floating-point numbers (e.g., -2.04, 4.0, 14.23).
  • complex: Complex numbers (e.g., 3+4i, 2-2i).
  • Boolean (bool): A subtype of integer with two values, True (non-zero) and False (zero).
  • The type() function can be used to determine a variable’s data type (e.g., type(10) returns , type(-1921.9) returns ).
  • Simple data types (int, float, bool) hold single values, while sequence and mapping types hold multiple values.

Sequence

A sequence is an ordered collection of items indexed by integers.

Types of sequences

String:

  • A group of characters (alphabets, digits, or special characters, including spaces).
  • Enclosed in single ('') or double ("") quotes, which mark the string’s boundaries.
  • Example: str1 = 'Hello Friend', str2 = "452".
  • Numerical operations cannot be performed on strings, even if they contain numeric values.

List:

  • A sequence of items separated by commas, enclosed in square brackets [].
  • Items can be of different data types.
  • Example: list1 = [5, 3.4, "New Delhi", "20C", 45].

Tuple:

  • A sequence of items separated by commas, enclosed in parentheses ().
  • Items can be of different data types but cannot be changed once created (immutable).
  • Example: tuple1 = (10, 20, "Apple", 3.4, 'a').

Mapping

  • Mapping is an unordered data type, with Dictionary being the only standard mapping type in Python.

Dictionary:

  • Holds data in key-value pairs, enclosed in curly brackets {}.
  • Keys are usually strings, and values can be of any data type.
  • Keys are separated from values by a colon (:), and values are accessed using keys in square brackets [].
  • Example: dict1 = {'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}, accessing dict1['Price(kg)'] returns 120.
  • Permits faster data access.

Operators

  • Operators perform mathematical or logical operations on values (operands).
  • Example: In 10 + num, 10 and num are operands, and + is the operator.

Arithmetic Operators

Perform basic arithmetic operations, modular division, floor division, and exponentiation:

  • + (Addition): Adds two numeric values (e.g., 5 + 6 = 11).
  • - (Subtraction): Subtracts the right operand from the left (e.g., 5 - 6 = -1).
  • * (Multiplication): Multiplies two values (e.g., 5 * 6 = 30).
  • / (Division): Divides the left operand by the right, returns quotient (e.g., 5 / 2 = 2.5).
  • % (Modulus): Returns the remainder of division (e.g., 13 % 5 = 3).
  • // (Floor Division): Divides and returns the quotient without decimal part (e.g., 5 // 2 = 2).
  • ** (Exponent): Raises the base to the power of the exponent (e.g., 3 ** 4 = 81).

+ can concatenate strings (e.g., "Hello" + "India" = "HelloIndia").
* repeats a string if the first operand is a string and the second is an integer (e.g., "India" * 2 = "IndiaIndia").
Similar behavior applies to lists and tuples.

Relational Operators

Compare operands and determine their relationship:

  • == (Equals to): True if operands are equal (e.g., 10 == 0 is False).
  • != (Not equal to): True if operands are not equal (e.g., 10 != 0 is True).
  • > (Greater than): True if left operand is greater (e.g., 10 > 0 is True).
  • < (Less than): True if left operand is less (e.g., 10 < 10 is False).
  • >= (Greater than or equal to): True if left operand is greater or equal.
  • <= (Less than or equal to): True if left operand is less or equal.

Assignment Operators

Assign or change the value of a variable:

  • =: Assigns right operand to left (e.g., num1 = 2).
  • +=: Adds right operand to left and assigns result to left (e.g., num1 += 2 is num1 = num1 + 2).
  • -=: Subtracts right operand from left and assigns result (e.g., num1 -= 2 is num1 = num1 - 2).
  • *=: Multiplies and assigns.
  • /=: Divides and assigns.
  • %=: Computes modulus and assigns.
  • //=: Performs floor division and assigns.
  • **=: Performs exponentiation and assigns.

Logical Operators

Evaluate to True or False based on logical operands:

  • and: True if both operands are True (e.g., num1 == 10 and num2 == -20 is True).
  • or: True if at least one operand is True (e.g., num1 > -10 or num2 > -10 is True).
  • not: Reverses the logical state (e.g., not (num1 == 20) is True).
  • Operators must be written in lowercase.

Membership Operators

Check if a value is in a sequence:

  • in: True if value is found in sequence (e.g., 2 in [1, 2, 3] is True).
  • not in: True if value is not found (e.g., 10 not in [1, 2, 3] is True).

Expressions

  • An expression is a combination of constants, variables, and operators that evaluates to a value.
  • Examples: num - 20.4, 23 / 3 - 5 * (14 - 2), 3.0 + 3.14, "Global" + "Citizen".
  • A value or standalone variable is an expression, but a standalone operator is not.

Precedence of Operators

  • Operator precedence determines the order of evaluation in expressions.
  • Higher precedence operators are evaluated first (e.g., * and / have higher precedence than + and -).
  • Parentheses () override precedence, evaluating the enclosed expression first.
  • For equal-precedence operators, evaluation is from left to right.
  • Example: 20 + 30 * 40 = 20 + 1200 = 1220 (multiplication first).
  • Example: (20 + 30) * 40 = 50 * 40 = 2000 (parentheses first).
  • Example: 15.0 / 4.0 + (8 + 3.0) = 15.0 / 4.0 + 11.0 = 3.75 + 11.0 = 14.75.

Input and Output

input() function:

  • Prompts the user to enter data via an input device (e.g., keyboard).
  • Accepts all input as a string.
  • Syntax: variable = input([Prompt]), where Prompt is an optional string displayed on the screen.
  • Example: fname = input("Enter your first name: ") assigns the entered string to fname.
  • Use int() or float() to convert string input to numeric types (e.g., age = int(input("Enter your age: "))).
  • Non-numeric strings cause an error when converted to numeric types.

print() function:

  • Outputs data to the standard output device (screen).
  • Evaluates expressions before displaying them.
  • Syntax: print(value).
  • Example: print("Hello") outputs Hello, print(10 * 2.5) outputs 25.0.

Debugging

Errors can prevent a program from executing or produce incorrect output.

Types of errors
Syntax Errors:

  • Occur when program statements violate Python’s syntax rules.
  • Example: (7 + 11 is incorrect due to a missing parenthesis.
  • The interpreter displays an error message and stops execution.
  • Must be fixed before the program can run.

Logical Errors:

  • Do not stop execution but produce incorrect output.
  • Example: 10 + 12 / 2 incorrectly calculates 16 instead of (10 + 12) / 2 = 11 for the average.
  • Hard to identify as the program runs successfully.

Runtime Errors:

  • Cause abnormal program termination during execution.
  • Example: Division by zero (e.g., 25 / 0) results in a “division by zero” error.
  • Debugging is the process of identifying and removing logical and runtime errors to ensure correct output.

Functions

  • A function is a set of statements grouped under a name to perform a specific task.
  • Functions are defined once and can be reused by calling the function name.
  • Example: A function CalcCompInt can calculate compound interest with inputs (interest rate, duration, principal) and be called whenever needed.
  • Built-in Functions:
    • Predefined functions like print(), input(), int().
    • Grouped in modules, which can be imported using the import command.
    • Make programming faster and more efficient.
  • Key aspects of functions:
    • Function Name: The name used to call the function.
    • Arguments: Values passed to the function in parentheses, which the function uses. Some functions take no arguments.
    • Return Value: The result returned by the function to the calling point. Some functions do not return values.
  • Example: In num = int(input("Enter the first number")), input() takes a prompt argument, int() converts the input to an integer, and print() outputs multiple arguments (e.g., print("the square of", num, "is", square)).
  • Common built-in functions:
    • Input/Output: input(), print().
    • Datatype Conversion: bool(), chr(), dict(), float(), int(), list(), ord(), set(), str(), tuple().
    • Mathematical: abs(), divmod(), max(), min(), pow(), sum().
    • Others: __import__(), len(), range(), type().

if..else Statements

Conditional statements allow programs to execute different tasks based on conditions.

Types of if..else statements
if statement:

  • Executes statements if the condition is True.
  • Example: if age >= 18: print("Eligible to vote").
  • if..else statement:
  • Executes if block if the condition is True, else block if False.
  • Example: If num1 > num2, compute diff = num1 - num2, else diff = num2 - num1.

if..elif..else statement:

  • Checks multiple conditions using elif (elseif).
  • Example: Check if a number is positive, negative, or zero using if number > 0, elif number < 0, else.
  • Executes the first True condition’s block and skips the rest.
  • Indentation defines blocks of code; statements at the same indentation level form a single block.
  • The interpreter enforces strict indentation, raising syntax errors for incorrect indentation.
  • A single tab is commonly used for each indentation level.

For Loop

  • Used for iteration over a range of values or a sequence (e.g., numbers, strings, lists, tuples).
  • Executes the loop body for each item in the sequence.
  • After exhausting all items, the interpreter executes statements following the loop.
  • The number of iterations must be known in advance.
  • Syntax: for <control statement> in <range>: .
  • Example: For a list numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], print even numbers using if (num % 2) == 0.
  • The loop body is indented relative to the for statement.

The range() Function

  • A built-in function to generate a sequence of integers.
  • Syntax: range([start], stop[, step]).
  • Generates integers from start (default 0) up to but excluding stop, with a step difference (default 1).
  • All parameters must be integers; step can be positive or negative (not zero).
  • Examples:
    • range(10) generates [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].
    • range(2, 10) generates [2, 3, 4, 5, 6, 7, 8, 9].
    • range(0, 30, 5) generates [0, 5, 10, 15, 20, 25].
    • range(0, -9, -1) generates [0, -1, -2, -3, -4, -5, -6, -7, -8].
  • Commonly used in for loops to generate number sequences.
  • Example: Print multiples of 10 for numbers in range(5), outputting 10, 20, 30, 40.

Nested Loops

  • A loop inside another loop is called a nested loop.
  • Example: An outer loop with range(3) and an inner loop with range(2) prints iteration numbers and inner loop values.
  • Output shows each outer loop iteration followed by inner loop values, then “Out of inner loop” and finally “Out of outer loop”.
The document Brief Overview of Python Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts is a part of the Humanities/Arts Course Informatics Practices for Class 11.
All you need of Humanities/Arts at this link: Humanities/Arts
16 docs

FAQs on Brief Overview of Python Chapter Notes - Informatics Practices for Class 11 - Humanities/Arts

1. What is the difference between Interactive Mode and Script Mode in Python?
Ans. Interactive Mode allows users to input Python commands one at a time and see immediate results. It is useful for testing small code snippets and debugging. Script Mode, on the other hand, involves writing a complete Python program in a file and executing it all at once. This mode is more suitable for developing larger applications and is used for running scripts that contain multiple lines of code.
2. What are the basic data types in Python, specifically regarding sequences and mappings?
Ans. In Python, sequences are ordered collections that can store multiple items. Common sequence types include lists, tuples, and strings. Mappings, on the other hand, are collections of key-value pairs, with the most common mapping type being the dictionary. Sequences allow access to elements via their index, while mappings allow access to values through unique keys.
3. How does operator precedence work in Python?
Ans. Operator precedence determines the order in which operations are performed in a Python expression. Operators with higher precedence are evaluated before those with lower precedence. For example, multiplication and division have higher precedence than addition and subtraction. Parentheses can be used to explicitly define the order of operations.
4. What are syntax errors in Python, and how can they be fixed?
Ans. Syntax errors occur when the code does not conform to Python's rules of syntax, making it impossible for the interpreter to understand. Common causes include missing colons, incorrect indentation, or misspelled keywords. To fix syntax errors, carefully review the code, check for any typos or formatting issues, and ensure that all syntax rules are followed.
5. How do if..else statements work in Python?
Ans. If..else statements in Python are used for conditional execution of code blocks. The "if" statement evaluates a condition, and if it is true, the block of code under it executes. If the condition is false, the "else" block executes instead. Additionally, "elif" can be used for multiple conditions. This structure allows for making decisions within the code based on varying conditions.
Related Searches

shortcuts and tricks

,

MCQs

,

Brief Overview of Python Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts

,

Summary

,

pdf

,

Extra Questions

,

video lectures

,

practice quizzes

,

Exam

,

Brief Overview of Python Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts

,

study material

,

Important questions

,

Viva Questions

,

Free

,

past year papers

,

mock tests for examination

,

Previous Year Questions with Solutions

,

Semester Notes

,

Sample Paper

,

Objective type Questions

,

Brief Overview of Python Chapter Notes | Informatics Practices for Class 11 - Humanities/Arts

,

ppt

;