Getting Started with Python Full & easy notes |1st puc
Chapter 5: Getting Started with Python
Complete Short Notes & Exam Preparation Guide
Based on the uploaded textbook PDF
π Chapter Overview
This chapter introduces Python programming and explains programming languages, Python features, execution modes, keywords, identifiers, variables, comments, objects, data types, operators, expressions, statements, input and output, type conversion and debugging.
π Table of Contents
- 5.1 Introduction to Python
- 5.1.1 Features of Python
- 5.1.2 Working with Python
- 5.1.3 Execution Modes
- 5.2 Python Keywords
- 5.3 Identifiers
- 5.4 Variables
- 5.5 Comments
- 5.6 Everything is an Object
- 5.7 Data Types
- 5.8 Operators
- 5.9 Expressions
- 5.10 Statement
- 5.11 Input and Output
- 5.12 Type Conversion
- 5.13 Debugging
- Important Questions & Answers
- Textbook Exercise 1β21
- Case Study
- Documentation Tips
- Quick Revision
5.1 Introduction to Python
An ordered set of instructions to be executed by a computer to carry out a specific task is called a program.
The language used to specify this set of instructions to the computer is called a programming language.
Computers understand machine language consisting of 0s and 1s. It is difficult for humans to write and understand instructions in machine language.
This led to the development of high-level programming languages such as Python, C++, Visual Basic, PHP and Java.
A program written in a high-level language is called source code.
Python uses an interpreter to convert its instructions into machine language so that they can be understood by the computer.
| Interpreter | Compiler |
|---|---|
| Processes program statements one by one, translating and executing them. | Translates the entire source code as a whole into object code. |
| Execution stops when an error is encountered. | Scans the complete program and generates error messages, if any. |
5.1.1 Features of Python
- Python is a high-level language and is free and open source.
- It is an interpreted language.
- Python programs are easy to understand because they have clearly defined syntax and relatively simple structure.
- Python is case-sensitive.
- Python is portable and platform independent.
- Python has a rich library of predefined functions.
- Python is helpful in web development.
- Python uses indentation for blocks and nested blocks.
5.1.2 Working with Python
To write and run a Python program, we need a Python interpreter installed on the computer, or we can use an online Python interpreter.
The interpreter is also called the Python Shell.
Python Prompt
5.1.3 Execution Modes
There are two ways to use the Python interpreter:
- Interactive Mode
- Script Mode
| Interactive Mode | Script Mode |
|---|---|
| Individual statements are executed instantaneously. | More than one instruction can be written in a Python source-code file. |
| Useful for testing a single line of code. | A program can be written, saved and executed later. |
| Statements cannot be saved for future use in the interactive session. | Python scripts are saved with the .py extension. |
Program 5-1
5.2 Python Keywords
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter.
| Keyword | Keyword | Keyword | Keyword | Keyword |
|---|---|---|---|---|
| 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 |
5.3 Identifiers
Identifiers are names used to identify variables, functions or other entities in a program.
Rules for Identifiers
- An identifier can begin with an alphabet or underscore.
- It can contain alphabets, digits and underscores.
- It cannot begin with a digit.
- It cannot be a Python keyword.
- Special symbols such as !, @, #, $, % etc. cannot be used.
- Python identifiers are case-sensitive.
- Meaningful and readable names are preferred.
Good Examples
5.4 Variables
A variable in a program is uniquely identified by a name or identifier. A variable in Python refers to an object stored in memory.
The value of a variable can be a string, numeric value or other data.
Python uses an assignment statement to create variables and assign values. Variable declaration is implicit in Python.
Variables must be assigned values before they are used in expressions.
Program 5-2
Output
Program 5-3
Output
5.5 Comments
Comments are used to add a remark or note in source code. Comments are not executed by the interpreter.
Comments make source code easier for humans to understand and help document the meaning, purpose, input and output requirements of code.
Single-line Comment
Examples
Program 5-4
Output
5.6 Everything is an Object
Python treats every value or data item as an object.
Every object has a unique identity during its lifetime. The id() function returns the identity of an object.
5.7 Data Types
Every value in Python has a data type. The data type identifies the kind of data and the operations that can be performed on it.
5.7.1 Number
| Data Type | Description | Examples |
|---|---|---|
| int | Integer numbers | -12, -3, 0, 125, 2 |
| float | Real or floating-point numbers | -2.04, 4.0, 14.23 |
| complex | Complex numbers | 3 + 4j, 2 – 2j |
Boolean
Boolean is a subtype of integer and has the constants True and False.
5.7.2 Sequence
A sequence is an ordered collection of items where each item is indexed by an integer.
String
A string is a group of characters enclosed in single or double quotation marks.
List
A list is a sequence of comma-separated items enclosed in square brackets.
Tuple
A tuple is a sequence of comma-separated items enclosed in parentheses. Once created, a tuple cannot be changed.
5.7.3 Set
A set is an unordered collection of comma-separated items enclosed in curly brackets. A set cannot contain duplicate entries.
5.7.4 None
None is a special data type with a single value. It signifies absence of value.
5.7.5 Mapping β Dictionary
A dictionary stores data in key-value pairs inside curly brackets. A colon separates the key and value.
5.7.6 Mutable and Immutable
| Mutable | Immutable |
|---|---|
| Values can be changed after creation and assignment. | Values cannot be changed after creation and assignment. |
| Example: List | Example: Integer |
5.7.7 Deciding Usage of Python Data Types
| Data Type | When Preferred | Example |
|---|---|---|
| List | When a simple iterable collection needs frequent modification. | Names of students in a class. |
| Tuple | When data should not change. | Names of months in a year. |
| Set | When uniqueness is required and duplication should be avoided. | List of artefacts in a museum. |
| Dictionary | When fast lookup or key:value association is required. | Mobile phone book. |
5.8 Operators
An operator is used to perform a specific mathematical or logical operation on values. The values on which operators work are called operands.
5.8.1 Arithmetic Operators
Python supports arithmetic operators for basic arithmetic operations, modular division, floor division and exponentiation.
| Operator | Operation | Description | Example β Try in Lab |
|---|---|---|---|
| + | Addition | Adds two numeric values. It can also concatenate two strings. |
>>> num1 = 5
>>> num2 = 6
>>> num1 + num2
11
>>> str1 = “Hello”
>>> str2 = “India”
>>> str1 + str2
‘HelloIndia’
|
| – | Subtraction | Subtracts the right operand from the left operand. |
>>> num1 = 5
>>> num2 = 6
>>> num1 – num2
-1
|
| * | Multiplication | Multiplies two values. It can repeat a string when the first operand is a string and the second is an integer. |
>>> num1 = 5
>>> num2 = 6
>>> num1 * num2
30
>>> str1 = ‘India’
>>> str1 * 2
‘IndiaIndia’
|
| / | Division | Divides the left operand by the right operand and returns the quotient. |
>>> num1 = 8
>>> num2 = 4
>>> num2 / num1
0.5
|
| % | Modulus | Divides the left operand by the right operand and returns the remainder. |
>>> num1 = 13
>>> num2 = 5
>>> num1 % num2
3
|
| // | Floor Division | Returns the quotient after removing the decimal part. It is also called integer division. |
>>> num1 = 13
>>> num2 = 4
>>> num1 // num2
3
>>> num2 // num1
0
|
| ** | Exponent | Raises the operand on the left to the power of the operand on the right. |
>>> num1 = 3
>>> num2 = 4
>>> num1 ** num2
81
|
5.8.2 Relational Operators
Relational operators compare values of operands and determine the relationship between them.
| Operator | Operation | Description | Example β Try in Lab |
|---|---|---|---|
| == | Equals to | True if the values are equal; otherwise False. |
>>> num1 == num2
False
>>> str1 == str2
False
|
| != | Not equal to | True if values are not equal. |
>>> num1 != num2
True
>>> str1 != str2
True
>>> num1 != num3
False
|
| > | Greater than | True if the left operand is greater than the right operand. |
>>> num1 > num2
True
>>> str1 > str2
True
|
| < | Less than | True if the left operand is less than the right operand. |
>>> num1 < num3
False
>>> str2 < str1
True
|
| >= | Greater than or equal to | True if the left operand is greater than or equal to the right operand. |
>>> num1 >= num2
True
>>> num2 >= num3
False
>>> str1 >= str2
True
|
| <= | Less than or equal to | True if the left operand is less than or equal to the right operand. |
>>> num1 <= num2
False
>>> num2 <= num3
True
>>> str1 <= str2
False
|
5.8.3 Assignment Operators
An assignment operator assigns or changes the value of the variable on its left.
| Operator | Description | Example β Try in Lab |
|---|---|---|
| = | Assigns the value from the right-side operand to the left-side operand. |
>>> num1 = 2
>>> num2 = num1
>>> num2
2
>>> country = ‘India’
>>> country
‘India’
|
| += |
Adds the right operand to the left operand and assigns the result.
x += y is same as x = x + y |
>>> num1 = 10
>>> num2 = 2
>>> num1 += num2
>>> num1
12
>>> num2
2
>>> str1 = ‘Hello’
>>> str2 = ‘India’
>>> str1 += str2
>>> str1
‘HelloIndia’
|
| -= |
Subtracts the right operand from the left operand and assigns the result.
x -= y is same as x = x – y |
>>> num1 = 10
>>> num2 = 2
>>> num1 -= num2
>>> num1
8
|
| *= |
Multiplies the left operand by the right operand and assigns the result.
x *= y is same as x = x * y |
>>> num1 = 2
>>> num2 = 3
>>> num1 *= 3
>>> num1
6
>>> a = ‘India’
>>> a *= 3
>>> a
‘IndiaIndiaIndia’
|
| /= |
Divides the left operand by the right operand and assigns the result.
x /= y is same as x = x / y |
>>> num1 = 6
>>> num2 = 3
>>> num1 /= num2
>>> num1
2.0
|
| %= |
Performs modulus operation and assigns the result.
x %= y is same as x = x % y |
>>> num1 = 7
>>> num2 = 3
>>> num1 %= num2
>>> num1
1
|
| //= |
Performs floor division and assigns the result.
x //= y is same as x = x // y |
>>> num1 = 7
>>> num2 = 3
>>> num1 //= num2
>>> num1
2
|
| **= |
Performs exponential calculation and assigns the value.
x **= y is same as x = x ** y |
>>> num1 = 2
>>> num2 = 3
>>> num1 **= num2
>>> num1
8
|
5.8.4 Logical Operators
Python supports three logical operators: and, or, not. They must be written in lower case.
| Operator | Operation | Description | Example β Try in Lab |
|---|---|---|---|
| and | Logical AND | If both operands are True, the condition becomes True. |
>>> True and True
True
>>> num1 = 10
>>> num2 = -20
>>> bool(num1 and num2)
True
>>> True and False
False
>>> num3 = 0
>>> bool(num1 and num3)
False
>>> False and False
False
|
| or | Logical OR | If any one of the two operands is True, the condition becomes True. |
>>> True or True
True
>>> True or False
True
>>> bool(num1 or num3)
True
>>> False or False
False
|
| not | Logical NOT | Reverses the logical state of its operand. |
>>> num1 = 10
>>> bool(num1)
True
>>> not num1
>>> bool(num1)
False
|
5.8.5 Identity Operators
Identity operators are used to determine whether two variables are referring to the same object.
| Operator | Description | Example β Try in Lab |
|---|---|---|
| is | Evaluates True if the variables on either side point towards the same memory location and False otherwise. |
>>> num1 = 5
>>> type(num1) is int
True
>>> num2 = num1
>>> id(num1)
1433920576
>>> id(num2)
1433920576
>>> num1 is num2
True
|
| is not | Evaluates False when variables point to the same object and True otherwise. |
>>> num1 is not num2
False
|
5.8.6 Membership Operators
Membership operators check whether a value is a member of a given sequence or not.
| Operator | Description | Example β Try in Lab |
|---|---|---|
| in | Returns True if the value is found in the specified sequence and False otherwise. |
>>> a = [1,2,3]
>>> 2 in a
True
>>> ‘1’ in a
False
|
| not in | Returns True if the value is not found in the specified sequence and False otherwise. |
>>> a = [1,2,3]
>>> 10 not in a
True
>>> 1 not in a
False
|
5.9 Expressions
An expression is a combination of constants, variables and operators. An expression always evaluates to a value.
A value or standalone variable is also considered an expression, but a standalone operator is not an expression.
Examples of Valid Expressions
5.9.1 Precedence of Operators
When an expression contains different types of operators, precedence determines which operator is applied first.
Higher-precedence operators are evaluated before lower-precedence operators.
| Order | Operators | Description |
|---|---|---|
| 1 | ** | Exponentiation |
| 2 | ~, +, – | Complement, unary plus and unary minus |
| 3 | *, /, %, // | Multiplication, division, modulo and floor division |
| 4 | +, – | Addition and subtraction |
| 5 | <=, <, >, >=, ==, != | Relational and comparison operators |
| 6 | =, %=, /=, //=, -=, +=, *=, **= | Assignment operators |
| 7 | is, is not | Identity operators |
| 8 | in, not in | Membership operators |
| 9 | not | Logical NOT |
| 10 | and | Logical AND |
| 11 | or | Logical OR |
1. Parentheses can override operator precedence. The expression inside parentheses is evaluated first.
2. Operators having equal precedence are evaluated from left to right.
Example 5.9
Example 5.10
Example 5.11
Example 5.12
5.10 Statement
In Python, a statement is a unit of code that the Python interpreter can execute.
Example 5.13
5.11 Input and Output
input()
The input() function prompts the user to enter data. It accepts user input as a string.
Syntax
The prompt is optional. When specified, it is displayed before the user enters data.
Example 5.14
Example 5.15
print()
Python uses the print() function to output data to the standard output device β the screen.
Syntax
| Parameter | Purpose | Default |
|---|---|---|
| sep | Separator between output values. | Space |
| end | String appended after the last value. | New line |
Example 5.16
| Statement | Output |
|---|---|
|
print(“Hello”)
|
Hello |
|
print(10*2.5)
|
25.0 |
|
print(“I” + “love” + “my” + “country”)
|
Ilovemycountry |
|
print(“I’m”, 16, “years old”)
|
I’m 16 years old |
5.12 Type Conversion
Type conversion means changing the data type of a variable from one type to another.
Type conversion can happen in two ways:
- Explicit conversion
- Implicit conversion
Input Example
If the user enters 2, the output is:
This happens because input() returns a string by default, so * acts as a repetition operator.
Corrected Version
Output
5.12.1 Explicit Conversion
Explicit conversion, also called type casting, happens when the programmer forces data type conversion.
Syntax
| Function | Description |
|---|---|
| int(x) | Converts x to integer. |
| float(x) | Converts x to floating-point number. |
| str(x) | Converts x to string representation. |
| chr(x) | Converts ASCII value of x to character. |
| ord(x) | Returns the character associated with the ASCII code x. |
Program 5-5
Program 5-6
Program 5-7 β Type Conversion between Numbers and Strings
Program 5-8 β Explicit Type Casting
Output
Program 5-9 β Explicit Type Conversion
Output
5.12.2 Implicit Conversion
Implicit conversion, also known as coercion, happens automatically by Python without being instructed by the programmer.
Program 5-10
Output
5.13 Debugging
A programmer can make mistakes while writing a program. The program may not execute or may generate incorrect output.
Debugging is the process of identifying and removing mistakes, bugs or errors from a program.
5.13.1 Syntax Errors
A syntax error occurs when the program does not follow Python syntax rules.
5.13.2 Logical Errors
A logical error occurs when a program executes but produces an undesired or incorrect output.
5.13.3 Runtime Error
A runtime error occurs while the program is executing.
Division by zero is an example of a runtime error.
Program 5-11
π Important Questions & Answers
An ordered set of instructions executed by a computer to carry out a specific task.
A language used to specify instructions to a computer.
A program written in a high-level programming language.
An interpreter processes program statements one by one, translating and executing them.
Keywords are reserved words having specific meanings to the Python interpreter.
Identifiers are names used to identify variables, functions and other entities in a program.
A variable is a name that refers to an object stored in memory.
A comment is a remark or note in source code that is not executed by the interpreter.
int, float and complex.
A list is a sequence of comma-separated items enclosed in square brackets.
A tuple is a sequence of comma-separated items enclosed in parentheses. It cannot be changed after creation.
A set is an unordered collection of items that cannot contain duplicate entries.
A dictionary stores data in key-value pairs.
Type conversion is the process of changing a value from one data type to another.
Explicit conversion is type conversion forced by the programmer.
Implicit conversion is type conversion performed automatically by Python.
Debugging is the process of identifying and removing errors from a program.
Syntax errors, logical errors and runtime errors.
An expression is a combination of constants, variables and operators that evaluates to a value.
The symbol >>> is called the Python prompt.
String.
It displays data on the standard output device, the screen.
Mutable data can be changed after creation, whereas immutable data cannot be changed after creation.
Identity operators determine whether variables refer to the same object.
Membership operators check whether a value belongs to a given sequence.
π Textbook Exercise β Questions 1 to 21
Identify the valid and invalid identifier names and give reasons based on Python identifier rules.
Write corresponding Python assignment statements for the given values and variables.
Write and evaluate logical expressions for the given conditions.
Add parentheses to the expressions so that they evaluate to True.
Find the output of the given Python variable-assignment programs.
Choose appropriate Python data types for the given data and explain the choice.
For the given values of variables, evaluate the specified expressions.
Identify whether the given situations represent syntax, logical or runtime errors.
Write an expression to test whether a dart lies within the specified dartboard radius.
Write a Python program to convert Celsius temperature to Fahrenheit.
Write a program to calculate the amount payable using simple interest.
Write a program to calculate in how many days a work will be completed by three persons A, B and C working together.
If A, B and C take x, y and z days respectively to complete the work alone, the textbook gives the formula:
Write a program to enter two integers and perform all arithmetic operations on them.
Write a program to swap two numbers using a third variable.
Write a program to swap two numbers without using a third variable.
Write a program to repeat the string GOOD MORNING n times, where n is an integer entered by the user.
Write a program to find the average of three numbers.
The volume of a sphere with radius r is 4/3 ΟrΒ³. Write a Python program to find the volume of spheres with radii 7 cm, 12 cm and 16 cm respectively.
Write a program that asks the user to enter their name and age. Print a message addressed to the user that tells the year in which the user will turn 100 years old.
Using the formula E = mcΒ², where the speed of light is approximately 3 Γ 10βΈ m/s, write a program that accepts the mass of an object and determines its energy.
A ladder is placed upright against a wall. Let length and angle store the length of the ladder and the angle it makes with the ground. Write a Python program to calculate the height reached by the ladder on the wall for:
- 16 feet and 75 degrees
- 20 feet and 0 degrees
- 24 feet and 45 degrees
- 24 feet and 80 degrees
β‘ Quick Revision
Important Definitions
- Program: Ordered set of instructions executed to perform a specific task.
- Programming Language: Language used to specify instructions to a computer.
- Source Code: Program written in a high-level language.
- Interpreter: Translates and executes statements one by one.
- Keyword: Reserved word with a predefined meaning.
- Identifier: Name used to identify a program entity.
- Variable: Name referring to an object stored in memory.
- Comment: Non-executable remark in source code.
- Expression: Combination of constants, variables and operators that evaluates to a value.
- Statement: Unit of code executable by the Python interpreter.
- Debugging: Process of identifying and removing errors.
Important Data Types
| Category | Types |
|---|---|
| Number | int, float, complex |
| Boolean | True, False |
| Sequence | String, List, Tuple |
| Set | Set |
| Special | None |
| Mapping | Dictionary |
Important Operators
| Category | Operators |
|---|---|
| Arithmetic | +, -, *, /, %, //, ** |
| Relational | ==, !=, >, <, >=, <= |
| Assignment | =, +=, -=, *=, /=, %=, //=, **= |
| Logical | and, or, not |
| Identity | is, is not |
| Membership | in, not in |
Operator Precedence
| Priority | Operators |
|---|---|
| 1 | ** |
| 2 | ~, +, – |
| 3 | *, /, %, // |
| 4 | +, – |
| 5 | <=, <, >, >=, ==, != |
| 6 | =, %=, /=, //=, -=, +=, *=, **= |
| 7 | is, is not |
| 8 | in, not in |
| 9 | not |
| 10 | and |
| 11 | or |
Input / Output
Type Conversion
- Explicit: Programmer forces the conversion.
- Implicit: Python performs the conversion automatically.
Three Major Errors
| Error | Meaning |
|---|---|
| Syntax Error | Program does not follow Python syntax rules. |
| Logical Error | Program executes but produces incorrect or undesired output. |
| Runtime Error | Error occurs while the program is executing. |
- Learn Python features.
- Learn identifier rules.
- Learn all data types.
- Learn mutable vs immutable.
- Learn all operator categories.
- Practise every Try in Lab example.
- Learn operator precedence.
- Learn input() and print() syntax.
- Learn explicit and implicit conversion.
- Learn syntax, logical and runtime errors.
- Practise textbook programs.
- Practise Exercise 1β21.
- Read the SMIS case study and documentation checklist.
π― Final Revision
This chapter provides the basic foundation required to start programming with Python. For examination preparation, students should give special attention to definitions, identifier rules, data types, operator tables, Try in Lab examples, expressions, precedence, input-output functions, type conversion, debugging, textbook programs and exercise questions.