0% found this document useful (0 votes)
4 views11 pages

Python Chapter5.PDF(Anjali)

Chapter 5 introduces Python as a versatile and widely-used programming language, highlighting its history, applications, and features. It covers Python's execution modes, keywords, identifiers, variables, data types, and operators, providing examples and explanations for each concept. The chapter also discusses mutable and immutable data types, expressions, statements, input/output functions, and type conversion.

Uploaded by

tsraj2108
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Python Chapter5.PDF(Anjali)

Chapter 5 introduces Python as a versatile and widely-used programming language, highlighting its history, applications, and features. It covers Python's execution modes, keywords, identifiers, variables, data types, and operators, providing examples and explanations for each concept. The chapter also discusses mutable and immutable data types, expressions, statements, input/output functions, and type conversion.

Uploaded by

tsraj2108
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Chapter 5: Introduction to Python Programming

Python Introduction

Python is the world's most popular and fastest-growing computer programming language. It is a multi-
purpose and high-level programming language. Python was invented by Guido Van Rossum in the
year 1989, but it was introduced into the market on 20th February 1991. Python got its
name from a BBC comedy series from seventies- “Monty Python‟s Flying Circus”.
The Python programming language has been used by many people like Software Engineers, Data
Analysts, Network Engineers, Mathematicians, Accountants, Scientists and many more.

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 it can be understood by the computer. An
interpreter processes the program statements one by one, first translating and then executing. This
process is continued until an error is encountered or the whole program is executed successfully.

Applications in the real world


1. Web Development
2. Machine Learning and Artificial Intelligence
3. Data Science
4. Game Development
5. Audio and Visual Applications
6. Software Development
7. CAD Applications
8. Business Applications
9. Desktop GUI
10. Web Scraping Application

The language is used by companies in real revenue generating products, such as:
 In operations of Google search engine, youtube, etc.
 Bit Torrent peer to peer file sharing is written using Python
 Intel, Cisco, HP, IBM, etc use Python for hardware testing.
 Maya provides a Python scripting API
 i–Robot uses Python to develop commercial Robot.
 NASA and others use Python for their scientific programming task.

Features of Python
The Python is a very popular programming language with the following features.

 Python is easy to learn and easy to understand.


 The Python is an interpreted programming language. It executes the code line by line.
 It is a platform independent programming language. It can be used with any operating system
like Windows, Linux, MAC OS, etc.
 The Python is a free and open-source programming language.
 The Python is an Object-Oriented, Procedural and Functional programming language
 The Python is a multi-purpose programming language
 The Python is a high-level programming language.
 Python uses indentation for blocks and nested blocks.
 Python has a large Ecosystem of Libraries, Frameworks and Tools to work with it.

Python Interpreter / Python shell


Python Interpreter is a program that reads and executes Python code. It uses 2 modes of
Execution.1 . I n t e r a c t i v e m o d e 2.Script mode
Python Interactive Mode
Interpreter uses prompt on screen, it means IDLE is working in interactive mode.
We type Python expression / statement / command after the Python prompt (>>>) and Python
immediately responds with the output . Let’s start typing,
>>>print “How are you?” Output : How are you?
Example :>>> x=2
>>> y=6
>>> z = x+y
>>> print z OUTPUT is 8

Disadvantages of interactive mode


 The interactive mode is not suitable for large programs.
 The interactive mode doesn’t save the statements, we cannot use it in the future. In order to use
it in the future, we need to retype all the statements.
 Editing the code written in interactive mode is a tedious task. We need to revisit
all our previous commands and if still we could not edit, we need to type everything again.

Python Script Mode


In this mode source code (user written code) is stored in a file with the .py extension and use the
interpreter to execute the contents of the file. To execute the script by the interpreter, you have to give
the interpreter the name of the file.

Example: Step 1: File> New Window


Step 2: def test():
x=2
y=6
z = x+y
print z
Step 3: Use File > Save or File > Save As - option for saving the file
(By convention all Python program files have names which end with .py)
Step 4: For execution, press ^F5, and it will go to Python prompt (in other window)
>>> test() Output is 8

PYTHON KEYWORDS
Reserved words which as a pre-defined meaning. There are 33 keywords in python.
IDENTIFIERS
The name given to a variable, class, function, etc. is known as Identifier.
Rules for identifiers:
1. It can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore. It cannot start with a digit.
2. Keywords cannot be used as an identifier.

3. We cannot use special symbols like !, @, #, $, %, + etc. in identifier.


4. _ (underscore) can be used in identifier.
5. Commas or blank spaces are not allowed within an identifier.
 Example :1num is invalid where num1 is valid

Variables

Variable in Python refers to an object — an item or element that is stored in the memory. We use
objects to capture data, object/ variable is a name which refers to a value.Variable is a quantity which
keeps on changing during the execution of the program.
Every object has:
 An Identity - can be known using id (object)
 A type – can be checked using type (object) and
 A value
Syntax: variable_name = value

Examples: 1. a=100 2. price = 987.9 3. message = "Keep Smiling" 4. gender = 'M'

EVERYTHING IS AN OBJECT
Python treats every value or data item whether numeric, string, or other type as an object in the sense
that it can be assigned to some variable or can be passed to a function as an argument.

Example :>>> num1 = 20


>>> id(num1)
1433920576 #identity of num1
>>> num2 = 30 - 10
>>> id(num2)
1433920576 #identity of num2 and num1 are same refers to object 20

COMMENTS
 Comments are not executed.
 Comments explain a program and make a program understandable and readable.
 All characters after the # and up to the end of the physical line are part of the comment and the
Python interpreter ignores them.
Example :
#totalMarks is sum of marks in all the tests of Mathematics
totalMarks = test1 + test2 + finalTest

Python data types are type of data that a variable can hold.
 Numeric data types: int, float, complex.
 String data types: str.
 Sequence types: list, tuple, range.
 Binary types: bytes, memoryview.
 Mapping data type: dict.
 Boolean type: bool.
 Set data types: set

1. Numbers: Number data type stores numerical values only. It is further classified into three
different types: int, float and complex. Boolean data type (bool) is a subtype of integer. It is a
unique data type, consisting of two constants, True and False.
Type ( ) determines the type of data in a variable.
Examples:
1. x = 5 2. x=20.5 3. x=1j 4. x=true
print(type(x)) print(type(x)) print(type(x)) print(type(x))
O/P: <class 'int'> <class ‘float’> <class ‘complex’> <class ‘bool’>

2. Sequences: A sequence is an ordered collection of items. It is the combination of mutable and non-
mutable data types. Three types of sequence datatype available in Python are Strings, Lists & Tuples.

String : String is a group of characters. These characters may be alphabets, digits or special characters
including spaces.
Example: x = 'Hello Friend'
print(type(x)) O/P: <class ‘str’>

List List is a sequence of items separated by commas and the items are enclosed in square brackets [ ].
Example: 1. list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1) O/P: [5, 3.4, 'New Delhi', '20C', 45]

2. x = ["apple", "banana", "cherry"]


print(x)
print(type(x)) O/P: [ ‘apple’ ,’banana’ ,’cherry’]
<class ‘list’>
Tuple : Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
This is unlike list, where values are enclosed in brackets [ ]. Once created, we cannot change the tuple.
Example: 1. tuple1 = (10, 20, "Apple", 3.4, 'a')
print(tuple1) O/P: (10, 20, "Apple", 3.4, 'a')

2. x = ("apple", "banana", "cherry")


print(x)
print(type(x)) 0/P: ("apple", "banana", "cherry")
<class ‘tuple’>

3.Sets: 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 : 1.set1 = {10,20,3.14,"New Delhi"}
print(type(set1))
print(set1) O/P: <class 'set'>
{10, 20, 3.14, "New Delhi"}

#duplicate elements are not included in set


1. set2 = {1,2,1,3}
print(set2) O/P: {1, 2, 3}
2. x = {"apple", "banana", "cherry"}
print(x)
print(type(x)) 0/P: {'apple', 'cherry', 'banana'}
<class 'set'>
4. None: This is special data type with single value. It is used to signify the absence of
value/false in a situation. It is represented by None.
Example:1. x = None
print(x)
print(type(x)) O/P: None
<class ‘NoneType’ >
5.Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping data type
in Python called dictionary.
Dictionary: Dictionary in Python holds data items in key-value pairs. Items in a dictionary are
enclosed in curly brackets { }.
Example : 1. dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
print(dict1) o/p:{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120
print(dict1['Price(kg)']) o/p: 120
2. x = {"name" : "John", "age" : 36}
print(x)
print(type(x)) o/p: {"name" : "John", "age" : 36}
<class ’dict’>
6. Binary Types:
1. x = memoryview(bytes(5))
print(x)
print(type(x)) o/p: <memory at 0x00B08FA0>
<class 'memoryview'>
2. x = b"Hello"
print(x)
print(type(x)) o/p: b'Hello'
<class 'bytes'>

Mutable and Immutable Data Types

Mutable Immutable
The objects can be modified after the creation as Objects cannot be modified after the creation of the
well. objects.
Classes that are mutable are not considered final. Classes that are immutable are considered final.

Thread unsafe. Thread-safe.


Classes are not made final for the mutable objects. Classes are made final for the immutable objects.

Example: Lists, Dict, Sets, User-Defined Classes, Example: int, float, bool, string, Unicode, tuple,
Dictionaries, etc. Numbers, etc.

OPERATORS
1. Arithmetic Operators

2. Relational Operators /Comparison Operators


3. Assignment Operators

4. Logical Operators
Operator Description Example

x=5
Returns True if both the x>7 and x>10
and
operands are true returns FALSE
Operator Description Example

X=5
Returns True if either of the
or x<7 or x>15
operands is true
returns TRUE

X=5
Returns True if the operand
not not(x>7 and x> 10)
is false
returns TRUE

5. Identity Operators
Operator Description Example

is In the example above, a and b both refer to the a = [1, 2, 3] o/p: True
same list object, so a is b evaluates to True. On the b=a False
other hand, a and c have the same values, but they c= [1, 2, 3]
refer to different list objects, so a is c evaluates to print(a is b)
False. print(a is c)

is not In the above example, we define two lists a and b a = [1, 2, 3]


that contain the same values. Since a and b are two b = [1, 2, 3] o/p: True
different list objects, the is not operator returns c=a False
True. We also define a variable c that refers to the print(a is not b)
same object a. Since a and c have the same print(a is not c)
identity, the is not operator returns False.

6. Membership Operators
Operator Description Example

in This returns True if ‘cherry’ exists in fruits = ['apple', 'cherry', 'orange']


sequence in fruits list if 'cherry' in fruits:
print("Yes, 'cherry' is a
fruit!")
o/p: Yes, 'cherry' is a fruit!

not in This returns True if ’ grape’ does not fruits = ['apple', 'banana', 'orange']
exist in sequence in fruits list if 'grape' not in fruits:
print("No, 'grape' is not a fruit!")
o/p: No, 'grape' is not a fruit!
EXPRESSIONS
An expression is defined as a combination of constants, variables, and operators. An expression
always evaluates to a value.
Precedence of Operators

Example 1: How will Python evaluate the following expression?


(20 + 30) * 40
= (20 + 30) * 40
= 50 * 40
= 2000
Example 2: How will the following expression be evaluated in Python?
15.0 / 4 + (8 + 3.0)
= 15.0 / 4 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

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 o/p: 4 64

INPUT AND OUTPUT


The input() function prompts the user to enter data. It accepts all user input as string.
The user may enter a number or a string but the input() function treats them as strings only.
The syntax for input() is: input ([Prompt])
Example: name = input("Enter your first name: ")
o/p: Enter your first name: Tanush
Output-The print() function displays the result on the monitor screen.
Example: print (“hello”) o/p: hello

TYPE CONVERSION
1. Explicit Conversion/Type Casting: The data type is manually changed by the user as per
their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type.
Example: x = float(1) o/p: 1.0
print(type(x)) <class ‘float’>
y = int(2.8) 2
print(type(y)) <class ‘int’>

2. Implicit Conversion/Coercion: The Python interpreter automatically converts one data type
to another without any user involvement.
Example: x = 10
print("x is of type:",type(x)) o/p: x is of type: <class 'int'>
y = 10.6 y is of type: <class 'float'
print("y is of type:",type(y)) 20.6
z=x+y z is of type: <class 'float'>
print(z)
print("z is of type:",type(z))

DEBUGGING
A programmer can make mistakes while writing a program, and hence, the program may not execute
or may generate wrong output. 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: When the interpreter is unable to parse the code due to the code violating Python
language rules, such as inappropriate indentation, erroneous keyword usage, or incorrect operator use.
Syntax errors prohibit the code from running, and the interpreter displays an error message that
specifies the problem and where it occurred in the code.
Example: x = 10
if x == 10
print("x is 10") # The Syntax Error occurs in line 2 because the if statement is missing a
colon : at the end of the line. The correct code should be:
x = 10
if x==10:
print("x is 10")

ii) Logical errors/Semantic Errors: A logical error occurs in Python when the code runs without any
syntax or runtime errors but produces incorrect results due to incorrect logic in the code. These types
of errors are often caused by incorrect assumptions, an incomplete understanding of the problem, or
the incorrect use of algorithms or formulas.
Examples:1. area=pie*r gives output but the output will be incorrect since the area of circle is
area=pie*r*r where pie=3.14287, r=2.3.
2. Incorrect order of operation:
This above code will not produce a syntax or runtime error, but the output will be incorrect because the
order of operations is incorrect. The correct calculation should be x + (y / z) to ensure that division is
performed before addition.
3. Incorrect calculation:

This above
code will not produce a syntax or runtime error, but the output will be incorrect because the
average is calculated incorrectly. The correct calculation should be (x + y) / 2.0 to ensure that
floating-point division is used.
4. Flawed logic/Incorrect logic:

This code will not produce a syntax or runtime error, but the output will be incorrect if the age is
exactly 18. The correct logic should be to include an elif statement to handle this case.

iii) Runtime errors: They occur during the execution of the program/runtime.
Example: x = "10"
y=5
Z=x+y
print(z) # TypeError: can only concatenate str (not "int") to str
Corrected Code is:
x = "10"
y=5
Z = x + str(y)
print(z)

You might also like