5 Getting Started With Python
5 Getting Started With Python
Program: An ordered set of instructions to be executed by a computer to carry out a specific task is called a program,
Programming language: The language used to specify set of instructions to the computer to carry out a specific task is called a
programming language.
Example: Python, C++, Java, C
Machine language or low-level language: Computers understand the language of 0 s and 1s which is called machine language or low level
language.
High-level programming languages: Programs written using English like words is called as high-level programming languages.
Example: Python, C++, Java, C
Language translators: It is a software used to translate the source code into machine language.
Example: interpreter, compiler
Interpreter:
An interpreter processes the program statements one by one, first translating and then executing.
This process continues until an error occurs or the whole program is executed successfully.
In both the cases, program execution will stop.
Python uses an interpreter to convert its instructions into machine language, so that the computer can understand it.
Compiler: Compiler translates the entire source code, as a whole, into the object code (machine code). After scanning the whole program,
it generates error messages, if any.
Features of Python
• Python is a high-level language. It is a free and open source language.
• Python is an interpreted language, as Python programs are executed by an interpreter.
• Python programs are easy to understand as they have a clearly defined syntax and relatively simple structure.
• Python is case-sensitive. For example, NUMBER and number are not same in Python.
• Python is portable and platform independent, means it can run on various operating systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services and applications are built using Python.
• Python uses indentation for blocks and nested blocks.
In the above screen, the symbol >>> is the Python prompt, which indicates that the interpreter is ready to take instructions.
We can type commands or statements on this prompt to execute them using a Python interpreter.
Execution Modes
There are two ways to use the Python interpreter to execute a program:
a) Interactive mode: This mode allows execution of individual statement instantaneously.
b) Script mode: This mode allows us to write more than one instruction in a file called Python source code file that can be executed.
a) Interactive Mode
To work in the interactive mode, simply type a Python statement on the >>> prompt directly.
As soon as enter key is pressed, the interpreter executes the statement and displays the result(s), as shown in the following figure.
Working in the interactive mode is convenient for testing a single line code for instant execution.
However, in the interactive mode, it is not possible to save the statements for future use and the statements need to be retyped to
run them again.
b) Script Mode
In the script mode, write Python program in a file, save it and then use the interpreter to execute it.
Python scripts are saved as files where file name has extension “.py”.
By default, the Python scripts are saved in the Python installation folder.
a) Type the file name along with the path at the prompt. For example, if the name of the file is [Link], type [Link]. Otherwise, open
the program directly from IDE (integrated development environment) as shown below.
b) While working in the script mode, after saving the file, click [Run]->[Run current script] from the menu as shown below.
PYTHON KEYWORDS
Keywords are reserved words, which has a specific meaning to the Python interpreter.
As Python is case sensitive, keywords must be written exactly as given in following table.
IDENTIFIERS: Identifiers are names, given by programmer, used to identify a variable, function, or other entities in a program.
Example:
Valid identifiers Invalid identifiers
Name %name
Total_marks int
A1 1a
Name2 name@
Serial_no Total marks
VARIABLES:
It is a name (identifier) given to memory location to store a value.
Variable in Python refers to an object, which is an item, or element that is stored in the memory.
Value of a variable can be a string (e.g., ‘b’, ‘computer science’), numeric (e.g., 345) or any combination of alphanumeric characters
(CD67).
Example:
gender = 'M'
message = "Keep Smiling"
price = 987.9
Output:
Keep Smiling
User Number is 101
Note:
Variable declaration is implicit in Python, means variables are automatically declared and defined when they are assigned a value
the first time.
Variables must always be assigned values before they are used in expressions, otherwise it will lead to an error in the program.
Wherever a variable name occurs in an expression, the interpreter replaces it with the value of that particular variable.
Program: Python program to find the area of a rectangle given that its length is 10 units and breadth is 20 units.
#Program to find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)
Output: 200
COMMENTS
Comments are used to add a remark or a note in the source code.
In Python, a comment starts with # (hash sign). Everything following the # till the end of that line is treated as a comment and the
interpreter simply ignores it while executing the statement.
Comments are added with the purpose of making the source code easier for humans to understand.
Comments are used, primarily to document the meaning and purpose of source code and its input and output requirements,
Comments are useful when a group of programmers working on developing large and complex software.
Example:
#Variable amount is the total spending on grocery.
amount = 3400
Output: 30
EVERYTHING IS AN OBJECT
Python treats every value or data item whether numeric, string, or other type as an object.
Object can be assigned to some variable or can be passed to a function as an argument.
Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime of that object.
This ID is memory address of the object.
The function id ( ) returns the identity of an object.
Example:
>>> num1 = 20
>>> id (num1)
1433920576 #identity of num1.
>>> num2 = 30 - 10
>>> id (num2)
1433920576 #identity of num2 and num1 are same as both refers to object 20.
DATA TYPES: Data type identifies the type of data or values a variable can hold and the operations that can be performed on that data or
values.
Number
Number data type stores numerical values only.
It is further classified into three different types: int, float and complex.
Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
The three types of sequence data types available in Python are Strings, Lists and Tuples.
a) String
String is a group of characters. These characters may be alphabets, digits or special characters including spaces.
String values are enclosed either in single quotation marks (e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”).
The quotes are not a part of the string, they are used to mark the beginning and end of the string for the interpreter.
It is not possible to perform numerical operations on strings, even when the string contains a numeric value.
Example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
b) List: List is a sequence of items separated by commas and the items are enclosed in square brackets [ ].
Example:
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print (list1)
[5, 3.4, 'New Delhi', '20C', 45]
c) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
Once created, we cannot change the tuple.
Example:
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
Set
Set is an unordered collection of items separated by commas and the items are enclosed in curly brackets { }.
A set is similar to list, except that it cannot have duplicate entries.
Once created, elements of a set cannot be changed.
Example:
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class 'set'>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
Mapping
Mapping is an unordered data type in Python.
There is only one standard mapping data type in Python called dictionary.
a) Dictionary
Dictionary in Python holds data items in key-value pairs.
Items in a dictionary are enclosed in curly brackets { }.
Every key is separated from its value using a colon (:) sign.
The key : value pairs of a dictionary can be accessed using the key.
The keys are usually strings and their values can be any data type.
In order to access any value in the dictionary, we have to specify its key in square brackets [ ].
Dictionaries permit faster access to data.
Example:
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120
Python data types can be classified into mutable and immutable as shown below.
Diagram-2: variables with same value have same memory location number
Diagram-3: variables with different values have different memory location number.
type ( ) function: It is a built-in function used to determine the data type of the variable.
Example 1:
>>> num1 = 10
>>> type (num1)
Output:
<class 'int'>
Example 2:
>>> num2 = -1210
>>> type (num2)
Output:
<class 'int'>
Example 3:
>>> var1 = True
>>> type (var1)
Output:
<class 'bool'>
Example 4:
>>> float1 = -1921.9
>>> type(float1)
Dept. Of Computer Science, Sri Adichunchanagiri Ind PU college, Shivamogga 13
I PUC 2024-25 (New syllabus) Computer Science Chapter 05 Getting started with Python
Output:
<class 'float'>
Example 5:
>>> float2 = -9.8*10**2
>>> print (float2, type(float2))
Output:
-980.0000000000001 <class 'float'>
Example 6:
>>> var2 = -3+7.2j
>>> print (var2, type(var2))
Output:
(-3+7.2j) <class 'complex'>
Note:
Variables of simple data types like integers, float, Boolean, etc., hold single values.
However, such variables are not useful to hold a long list of information.
For example, names of the months in a year, names of students in a class, names and numbers in a phone book or the list of
artefacts in a museum.
For this, Python provides data types like tuples, lists, dictionaries and sets.
Tuples:
Tuples are used when we do not need any change in the data. For example, names of months in a year.
Sets:
When we need uniqueness of elements and to avoid duplicate entries, it is preferable to use sets, for example, list of artefacts in a
museum.
Dictionaries:
If the data is being constantly modified or there is a need for fast lookup, based on a custom key or we need a logical association
between the key : value pair, it is advised to use dictionaries.
A mobile phone book is a good application of dictionary.
OPERATORS
An operator is a special character or a predefined word used to perform specific mathematical or logical operations.
The values that the operators work on are called operands.
For example: In the expression 10 + num, the value 10, and the variable num are operands and the + (plus) sign is an operator.
Types of operators
Arithmetic Operators
Relational Operators
Assignment Operators
Logical Operators
Identity Operators
Membership Operators
1) Arithmetic Operators: Arithmetic operators are used to perform the basic arithmetic operations as well as modular division, floor
division and exponentiation.
Operator Operation Description Example
Adds the two numeric values on either side of the operator. >>> num1 = 5
This operator can also be used to concatenate two strings on >>> num2 = 6
either side of the operator >>> num1 + num2
11
+ Addition -------------------------------
>>> str1 = "Hello"
>>> str2 = "India"
>>> str1 + str2
'HelloIndia'
Subtracts the operand on the right from the operand on the left >>> num1 = 5
- Subtraction >>> num2 = 6
>>> num1 - num2
-1
Multiplies the two values on both side of the operator. >>> num1 = 5
Repeats the item on left of the operator if first operand is a >>> num2 = 6
string and second operand is an integer value. >>> num1 * num2
30
* Multiplication
-------------------------
>>> str1 = 'India'
>>> str1 * 2
'IndiaIndia'
Divides the operand on the left by the operand on the right and >>> num1 = 8
returns the quotient. >>> num2 = 4
/ Division
>>> num2 / num1
0.5
Divides the operand on the left by the operand on the right and >>> num1 = 13
returns the remainder. >>> num2 = 5
% Modulus
>>> num1 % num2
3
Divides the operand on the left by the operand on the right and >>> num1 = 13
returns the quotient by removing the decimal part. >>> num2 = 4
It is sometimes also called integer division. >>> num1 // num2
// Floor division 3
-------------------------
>>> num2 // num1
0
Performs exponential (power) calculation on operands. >>> num1 = 3
That is, raise the operand on the left to the power of the operand >>> num2 = 4
** Exponent
on the right >>> num1 ** num2
81
2) Relational Operators: Relational operator compares the values of the operands on its either side and determines the relationship
among them.
Assume the Python variables num1 = 10, num2 = 0, num3 = 10, str1 = "Good", str2 = "Afternoon" for the following examples:
Operator Operation Description Example
If the values of two operands are equal, then the condition is true, >>> num1 == num2
otherwise, it is False. False
== Equals to ----------------------------
>>> str1 == str2
False
If values of two operands are not equal, then condition is true, >>> num1 != num2
otherwise, it is False. True
---------------------------
>>> str1 != str2
!= Not equal to
True
---------------------------
>>> num1 != num3
False
If the value of the left-side operand is greater than the value of the >>> num1 > num2
right side operand, then condition is true, otherwise it is False. True
> Greater than -------------------------
>>> str1 > str2
True
If the value of the left-side operand is less than the value of the right >>> num1 < num3
side operand, then condition is true, otherwise, it is False. False
< Less than
--------------------------
>>> str2 < str1
True
If the value of the left-side operand is greater than or equal to the >>> num1 >= num2
value of the right side operand, then condition is true, otherwise, it is True
False. -------------------------
Greater than
>= >>> num2 >= num3
or equal to
False
-------------------------
>>> str1 >= str2
True
If the value of the left operand is less than or equal to the value of the >>> num1 <= num2
right operand, then is True otherwise it is False. False
----------------------------
Less than or >>> num2 <= num3
<=
equal to True
----------------------------
>>> str1 <= str2
False
3) Assignment Operators: These operators are used to assign or change the value of the variable on its left.
It subtracts the value of right-side operand from the left-side operand and assigns the >>> num1 = 10
result to left-side operand >>> num2 = 2
-= Note: x -= y is same as x = x - y >>> num1 -= num2
>>> num1
8
It multiplies the value of right-side operand with the value of left-side operand and >>> num1 = 2
assigns the result to left-side operand >>> num2 = 3
Note: x *= y is same as x = x * y >>> num1 *= 3
>>> num1
*= 6
>>> a = 'India'
>>> a *= 3
>>> a
'IndiaIndiaIndia'
It divides the value of left-side operand by the value of right-side operand and assigns >>> num1 = 6
the result to left-side operand >>> num2 = 3
/= Note: x /= y is same as x = x / y >>> num1 /= num2
>>> num1
2.0
It performs modulus operation using two operands and assigns the result to left-side >>> num1 = 7
Operand. >>> num2 = 3
%= Note: x %= y is same as x = x % y >>> num1 %= num2
>>> num1
1
It performs floor division using two operands and assigns the result to left-side >>> num1 = 7
operand. >>> num2 = 3
//= Note: x //= y is same as x = x // y >>> num1 //= num2
>>> num1
2
It performs exponential (power) calculation on operators and assigns value to the left- >>> num1 = 2
side operand. >>> num2 = 3
**= Note: x **= y is same as x = x ** y >>> num1 **= num2
>>> num1
8
4) Logical Operators:
The logical operator evaluates to either True or False based on the logical operands on either side.
Every value is logically either True or False.
By default, all values are True except None, False, 0 (zero), empty collections " ", ( ), [ ], { }, and few other special values.
For example, if num1 = 10, num2 = -20, then both num1 and num2 are logically True.
False
>>> num1 = 10
>>> bool(num1)
True
not Logical NOT Used to reverse the logical state of its operand -------------------------------
>>> not num1
>>> bool(num1)
False
5) Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or not.
Identity operators can also be used to determine whether two variables are referring to the same object or not.
6) Membership Operators: Membership operators are used to check if a value is a member of the given sequence or not.
Operator Description Example
in Returns True if the variable/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 variable/value is not found in the specified sequence and False >>> a = [1,2,3]
otherwise >>> 10 not in a
True
--------------------
>>> 1 not in a
False
EXPRESSIONS
An expression is defined as a combination of constants, variables, and operators. An expression always evaluates to a value.
A value or a standalone variable is also considered as an expression but a standalone operator is not an expression.
Some examples of valid expressions are given below.
a) 100 b) 3.0 + 3.14 c) num d) 23/3 -5 * 7/(14 -2) e) num – 20.4 f) "Global" + "Citizen"
Unary operators: These are the operators work with only one operand.
Example: 1) –a 2) y++ 3) *p
Precedence of Operators
The order of evaluation of operators in the expression is called as precedence of operators.
When an expression contains different kinds of operators, precedence determines which operator should be applied first.
Higher precedence operator is evaluated before the lower precedence operator.
The unary operators have a higher precedence than the binary operators do.
The minus (-) as well as + (plus) operators can act as both unary and binary operators, but not operator is a unary logical operator.
Example:
#variable Depth is using - (minus) as unary operator
Value = -Depth
The following table shows precedence of all operators from highest to lowest.
Order of
Operators Description
Precedence
1 ** Exponentiation (raise to the power)
2 ~ ,+, - Complement, unary plus and unary minus
3 * ,/, %, // Multiply, divide, 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
10 And Logical operators
11 or
Note:
a) Parenthesis can be used to override the precedence of operators. The expression within () is evaluated first.
b) For operators with equal precedence, the expression is evaluated from left to right.
STATEMENT: In Python, a statement is a unit of code that the Python interpreter can execute.
Example:
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
4 64
input ( ) function
This function accepts user input by prompting the user to enter data.
It accepts all user input numeric, alphanumeric as string.
Prompt is the string to display on the screen prior to taking the input and it is optional.
When a prompt is specified, first it is displayed on the screen after which the user can enter data.
The input ( ) takes exactly what is typed from the keyboard, converts it into a string and assigns it to the variable on left-hand side
of the assignment operator (=).
Entering data for the input function is terminated by pressing the enter key.
Example:
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab
----------------------------------------------------------
>>> age = input("Enter your age: ")
Enter your age: 19
---------------------------------------------------------
>>> type(age)
<class 'str'>
It is possible to typecast or change the datatype of the string data accepted from user to an appropriate numeric value. As shown in
following example
>>> age = int( input("Enter your age:")) #function int ( ) to convert string to integer
Enter your age: 19
>>> type(age)
<class 'int'>
print ( ) function
The print ( ) function is used to display the output data on standard output device.
The print ( ) outputs a complete line and then moves to the next line for subsequent output.
Example:
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
TYPE CONVERSION
As and when required, we can change the data type of a variable in Python from one type to another.
1) Explicitly
2) Implicitly, when the interpreter understands such a need by itself and does the type conversion automatically.
1) Explicit Conversion:
(forced) when the programmer specifies for the interpreter to convert a data type to another type;
There is a risk of loss of information since we are forcing an expression to be of a specific type.
The general form of an explicit data type conversion is:
(new_data_type) (expression)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:
30
<class 'int'>
30.0
<class 'float'>
Output:
The total in Rs.70
price = int(icecream)+int(brownie)
print("Total Price Rs." + str(price))
Output:
Total Price Rs.2545
Total Price Rs.70
2) Implicit Conversion: Happens when data type conversion is done automatically by Python and is not instructed by the programmer.
DEBUGGING
The process of identifying and removing such mistakes, also known as bugs or errors, from a program is called debugging.
Errors occurring in programs can be categorised as:
i) Syntax errors
ii) Logical errors
iii) Runtime errors
1) Syntax Errors
These are the errors occurs when the statements are not written syntactically (as per the rules of Python) correct.
Like other programming languages, Python has its own rules that determine its syntax.
The interpreter interprets the statements only if it is syntactically (as per the rules of Python) correct.
If any syntax error is present, the interpreter shows error message(s) and stops the execution there.
For example,
Parentheses must be in pairs, so the expression (10 + 12) is syntactically correct.
Whereas (7 + 11 is not syntactically correct due to absence of right parenthesis.
Such errors need to be removed before the execution of the program
For example:
To find the average of two numbers 10 and 12, code is written as 10 + 12/2.
This runs successfully and produce the result 16. But 16 is not the average of 10 and 12.
The correct code to find the average is (10 + 12)/2 to give the correct output as 11.
Logical errors are also called semantic errors as they occur when the meaning of the program (its semantics) is not correct.
3) Runtime Error
A runtime error causes abnormal termination of program while it is executing.
Runtime error occurs, when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing.
For example:
In division operation, if the denominator value is zero then it will give a runtime error like “division by zero”.
The following program shows two types of runtime errors when a user enters non-integer value or value ‘0’. The program generates
correct output when the user inputs an integer value for num2.