Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

Chapter 1 introduction to Python

Uploaded by

ridaysingha7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Chapter 1 introduction to Python

Uploaded by

ridaysingha7
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Getting Started

with Python
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 set of instructions


to the computer is called a programming language
for example Python, C, C++, Java, etc.

• In this Chapter we will see brief overview of Python


programming language

• Python is a very popular and easy to learn


programming language, created by Guido van
Rossum in 1991.

• Python got its name from a BBC comedy series


from seventies- “Monty Python‟s Flying Circus”
A Python program is called a script.
Sc ript is a sequenc e of definitions and
commands.

These commands are exec uted by Python


interpreter known as PYTHON SHELL.

In python programming,
data types are inbuilt henc e support
“dynamic typing”
 dec laration of variables is not required.
memory management is automatic ally
done.
Features of Python

1. Python is an interpreted, interactive, directly


executed language.

2. It is free open-source software having large


repository of libraries.

3. It is extensible and highly efficient as there is no


wastage of time in declaring variables.
Advantages of Python

1. Platform independent – It can run across different


platforms like windows, Linux, Mac OS and other OS.

2.Easy to use (Readability) – It uses simple, concise


and English like instructions that are easy to read and
understand.

3.High Productivity – It is a simple language with small


codes and extensive libraries. Therefore it offers higher
productivity to programmers as compared to C++
and java.
Advantages of Python

4.Less learning time– Because of simple and shorter


code, lesser time is required to understand and learn
python.

5.Syntax highlighting – It allows to distinguish between


input, output and error message by different colour
codes.

6.Interpreted language – Code execution &


interpretation line by line.
Installing Python
1. Download python distribution
you can download python distribution from the link given below
https://www.python.org/downloads/
Installing Python
Python Installation process:

Note: while installing python one thing keep in mind i.e. tick the button Add
python 3.10 to path so that your python address will added implicitly to
environment variable. And continue to install now if you got a prompt window to
ask to run the just simply click yes .
Two modes to interact with Python

(Python Shell)
(Python Editor)
Execution Modes:
1) Interactive Mode :
we can type a Python statement on the
>>> prompt directly. As soon as we
press enter, the interpreter executes the
statement and displays the result(s)
Working in the interactive mode is convenient
for testing a single line code for instant
execution. But in the interactive mode, we
cannot save the statements for future use and
we have to retype the statements to run them
again.
2) Script Mode:
In the script mode, we can write a Python program in a
file, save it and then use the interpreter to execute the
program from the file. Such program files have a .py
extension and they are also known as scripts. But for
programs having more than a few lines, we should
always save the code in files for future use. Python
scripts can be created using any editor. Python has a
built-in editor called IDLE (Integrated Development and Learning
Environment )which can be used to create programs. After
opening the IDLE, we can click File>New File to create a
new file, then write our program on that file and save it
with a desired name. By default, the Python scripts are
saved in the Python installation folder.
Python Character Set
A set of valid characters recognized by python.
• Python uses the traditional ASCII character set.
• The latest version recognizes the Unicode character set.
The ASCII character set is a subset of the Unicode
character set.
Letters: a-z, A-Z
Digits : 0-9

Special symbols : Special symbol available over keyboard


White spaces: blank space, tab, carriage return, new
line, form feed

Other characters: Unicode


Tokens

Smallest individual unit in a program is


known as token.

1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Delimiters
1. Keywords
Reserved word of the compiler/interpreter which can’t
be used as identifier.
2. Identifiers
A Python identifier is a name used
to identify a variable, function,
class, module or other object.
Identifier Naming Convention
1. A variable name can contain letter, digits and underscore (_). No
other characters are allowed.

2. A variable name must start with an alphabet or and underscore (_).

3. A variable name cannot contain spaces.

4. Keyword cannot be used as a variable name.

5. Variable names are case sensitive. Num and num are different.

6. Variable names should be short and meaningful.

Invalid variable names – 3dgraph, roll#no, first name, d.o.b, while


Variables
• Variable is an identifier whose value can
change.
• For example variable age can have
different value for different person.
Variable name should be unique in a
program. Value of a variable can be
string (for example: ’b‘, 'Global Citizen‘),
number (for example : 10,71,80.52) or any
combination of alphanumeric (alphabets
and numbers for example 'b10‘)
characters.
• In Python, we can use an assignment
statement to create new variables
and assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9

• Variables must always be assigned


values before they are used in the
program, otherwise it will lead to an
error.
3. Literals
Literals in Python can be defined as number,
text, or other data that represent values to be
stored in variables.
Example of String Literals in Python
name = 'Johni' , fname='johny'

Example of Integer Literals in Python(numeric literal)


age = 22

Example of Float Literals in Python(numeric literal)


height = 6.2

Example of Special Literals in Python


name = None
3. Literals
Escape sequence :

An escape sequence is a sequence of characters that


does not represent itself when used inside
a character or string literal, but is translated into
another character or a sequence of characters that
may be difficult or impossible to represent directly.
e.g. 1) \n is newline character
2) \t is tab leaves 5 spaces

print(“I am a student of \n APS \t You Can't”)


output : I am a student of
APS You cann’t
Escape sequence :
4. Operators
Operators can be defined as symbols that are used to
perform operations on operands.

Types of Operators
a. Arithmetic Operators.
b. Relational Operators.
c. Assignment Operators.
d. Logical Operators.
e. Membership Operators
f. Identity Operators
Operators
a. Arithmetic Operators.
Arithmetic Operators are used to perform arithmetic
operations like addition, multiplication, division etc.
print ("hello"+"python")
print(2+3)
print(10-3)
print(22%5)
print(19//5)
print(2**3)
Output:
hellopython
5
7
2
3
8
Operators
b. Relational Operators.
Relational Operators are used to compare the values.
print(5==3) False
print(7>3) True
print(15<7) False
print(3!=2) True
print(7>=8) False
print(3<=4) True
Operators
c. Assignment Operators.
Used to assign values to the variables.
a=10
print(a)

a+=9
print(a)
Output:
b=11 10
b*=3 19
print(b) 33
9.5
c=19
c/=2 16
print(c)

d=2
d**=4
print(d)
Operators
d. Logical Operators.
Logical Operators are used to perform logical operations
on the given two variables or values.

a=30 a=70
b=20 b=20
if(a==30 and b==20):
print("hello")
if(a==30 or b==20):
print("hello")
Output :-
hello
Operators
e. Membership Operators
It used to validate whether a value is found within a
sequence such as such as strings, lists, or tuples.

E.g. E.g.
a = 22 a = 22
list = [11, 22,33,44] list = [11, 22,33,44]
ans= a in list ans= a not in list
print(ans) print(ans)
Output: True Output: False
Operators
f. Identity Operators
Identity operators in Python compare the memory
locations of two objects.
5. Delimiters
These are the symbols which can be used as
separator of values or to enclose some values.

e.g ( ) {} [ ] , ; :
Token Category
X Variable

y Variable

z Variable

print Keyword

() Delimiter

/ Operator

68 Literal

“x, y, z” Literal
Comment
• Comments are used to add a remark or a note in
the source code. Comments are not executed by
interpreter. They are added with the purpose of
making the source code easier for humans to
understand. They are used primarily to document
the meaning and purpose of source code.
• In Python, a single line 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.
• Multiline comment can be given using
‘'‘ Docstring‘‘‘
Example :- ‗„ this is program for
find maximum of 2 numbers‘‘‘
Expressions
Expressions are c ombination of value(s). i.e.
constant, variable and operators.
Expression Value
5+2*4 13
8+12*2-4 28

Converting mathematical expression to


equivalent Python expression
Algebraic Expression Python Expression
y = 3 ( 2𝑥 ) y=3*x/2
z= 3bc + 4 z = 3*b*c + 4
First python code
Write a Python program to find the sum of two
numbers.

#To find the sum of two given numbers


num1 = 10
num2 = 20
result = num1 + num2
print(result)
#print function in python displays the output
Output:
30
Write a Python program to find the area of a
rectangle given that its length is 10 units and
breadth is 20 units.
#To find the area of a rectangle
length = 10
breadth = 20
area = length * breadth
print(area)
Output:
200
Data Type
• Data type identifies the type of data which a variable
can hold and the operations that can be performed
on those data.

Data types

Numbers Sequences Sets None Mappings

Floating
Integer Complex Strings Dictionaries
Point

Boolean Lists

Tuples
Data Type
a. int (integer): Integer represents whole
numbers. (positive or negative)
e.g. -6, 0, 23466
b. float (floating point numbers): It
represents numbers with decimal
point.
e.g. -43.2, 6.0
c. Complex numbers: It is made up of pair
of real and imaginary number.
e.g. 2+5j
Data Type
Boolean (bool): It represents one of the
two possible values – True or False.

>>> bool_1 = (6>10)


>>> print (bool_1)
False
>>> bool_2 = (6<10)
>>> print (bool_2)
True
Sequence
• A Python sequenc e is an ordered
collection of items, where each item is
indexed by an integer value.
• Three types of sequenc e data types
available in Python are Strings, Lists
and Tuples. A brief introduction to
these data types is as follows:
a) String
b) List
c) Tuple
String
String (str): It is a sequence of characters.
(combination of letters, numbers and
symbols).
It is enclosed within single or double
quotes.
e.g:
>>> rem= 'Helo Welcome to Python’
>>> print (rem)
Hello Welcome to Python
•It is possible to change one type of value/
variable to another type. It is known as type
conversion or type casting.

•For explicit type casting, we use


functions (constructors):
• int ( )
• float ( )
• str ( )
• bool ( )
List
• List is a sequence of items separated
by commas and items are enclosed in
square brackets [ ]. Note that items
may be of different date types.

#To create a list


>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
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
items in the tuple. Similar to List, items may be of
different data types.

#create a tuple tuple1


>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
Sets
• Sets: Sets is an unordered collection
of values, of any type, with no
duplicate entry. Sets are mutable.

Example:
>>> s = set ([1,2,34])
>>> s
output: {1, 2, 34}
None: It is a special data type with single
value.
It is used to signify absenc e of value
evaluating to false in a situation.

>>> value_1 = None


>>> print (value_1)
None
Mapping
• Mapping is an unordered data type in Python.
Currently, there is only one standard mapping data
type in Python called Dictionary.

(A) Dictionary
• Dictionary in Python holds data items in key-value
pairs and Items are enclosed in curly brackets {}.
dictionaries permit faster access to data. Every key
is separated from its value using a colon (:) sign. The
key value pairs of a dictionary can be accessed
using the key. Keys are usually of string type and
their values can be of any data type. In order to
access any value in the dictionary, we have to
specify its key in square brackets [ ].
Example of Dictionary
#create a dictionary
>>>dict1 ={'Fruit':'Apple', 'Climate':'Cold',
'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key
>>> print(dict1['Price(kg)'])
120
Mutable and Immutable Variables

A mutable variable is one whose value may


change in place.

1. List
2. Set
3. Dictionary
An immutable variable change of value
will not happen in place. Modifying an
immutable variable will rebuild the
same variable.
1. int
2. float
3. decimal
4. complex
5. bool
6. string
7. tuple
Precedence of Operators
Input/Output
Python provides three functions for getting
user's input.

1. input() function– It is used to get data in


script mode.
The input() function takes string as an
argument.
It always returns a value of string type.
Input/Output
2.int() function– It is used to convert input
string value to numeric value.

3.float() function – Itconverts fetched value in float


type.

4.eval() – This function is used to evaluate the


value of a string.
It takes input as string and evaluates this string as
number and return numeric result.

NOTE : input() function always enter string value in


python 3. So on need int(), float() function can be
used for data conversion.
Type Conversion
We can change the data type of a variable in
Python from one type to another.

Such data type conversion can happen in two


ways: either explicitly (forced) when the
programmer specifies for the interpreter to
convert a data type to another type;

or implicitly, when the interpreter understands


such a need by itself and does the type
conversion automatically.
Explicit Conversion
Explicit conversion, also called type casting
happens when data type conversion takes
place because the programmer forced it in the
program.
The general form of an explicit data type
conversion is:
(new_data_type) (expression)

With explicit type conversion, there is a risk of loss of


information since we are forcing an expression to be of
a specific type.
For example, converting a floating value of x =20.67
into an integer type, i.e., int(x) will discard the fractional
part .67.
Implicit Conversion

Implicit conversion, also known as coercion,


happens when data type conversion is done
automatically by Python and is not instructed by
the programmer.
Debugging
Due to errors, a program may not execute
or may generate wrong output. :
• Syntax errors
• Logical errors
• Runtime errors

• The process of identifying and removing


logical errors and runtime errors is called
debugging.
Syntax Errors
• Rules that determine how a program is to be
written. This is ca lled syntax.
• The interpreter can interpret a statement of a
program only if it is syntactically correct.
• For example, parentheses must be in pairs, so
the expression (10 +12) is syntactically
correct, whereas (7 + 11 is not due to
absence of right parenthesis. If any syntax
error is present, the interpreter shows error
message(s) and stops the execution there.
Such errors need to be removed before
execution of the program.
Logical Errors
• A logical error/bug (called semantic error) does
not stop execution but the program behaves
incorrectly and produces undesired /wrong
output. Since the program interprets
successfully even when logical errors are
present in it, it is sometimes difficult to identify
these errors.
• For example, if we wish to find the average of
two numbers 10 and 12 and we write the code
as 10 + 12/2, it would run successfully and
produce the result 16, which is wrong. The
correct code to find the average should have
been (10 +12) /2 to get the output as 11.
Runtime Error
• A runtime error causes abnormal
termination of program while it is
executing. Runtime error is when the
statement is correct syntactically, but
the interpreter can not execute it.
• For example, we have a statement
having division operation in the
program. By mistake, if the
denominator value is zero then it will
give a runtime error like ―division by
zero‖.
Sample Program

n1 = input("Enter first number")


n2 = input("Enter second number")
Sum=n1+n2
print("Sum is:", Sum)
Sample Program
n1 = eval(input("Enter first number"))
n2 = eval(input("Enter second number"))
Sum=n1+n2
print("Sum is:", Sum)

n1 = int(input("Enter first number"))


n2 = int(input("Enter second number"))
Sum=n1+n2
print("Sum is:", Sum)
Sample Program
n1 = eval(input("Enter first number"))
n2 = eval(input("Enter second number"))
Sum=n1+n2
print("Sum is:", Sum)

n1 = int(input("Enter first number"))


n2 = int(input("Enter second number"))
Sum=n1+n2
print("Sum is:", Sum)
To calculate simple interest

p = int(input("Enter Principal:"))
r = float(input("Enter Rate:"))
t = int(input("Enter Time:"))
si=0.0
si=(p*r*t)/100
print("Simple Interest is:", si)
To calculate total and percentage

m1 = int(input("Enter marks in English:"))


m2 = int(input("Enter marks in Hindi:"))
m3 = int(input("Enter marks in Maths:"))
m4 = int(input("Enter marks in Science:"))
m5 = int(input("Enter marks in Social Science:"))
total=m1+m2+m3+m4+m5
per = total/5
print("Total is:", total)
print("Percenatge is:", per)

You might also like