Python BasicsJIdentifiers LJReserved Keywords LJData Types LJTypecasting, Error
Python BasicsJIdentifiers LJReserved Keywords LJData Types LJTypecasting, Error
Introduction
• But officially Python was made available to public in 1991. The official
Date of Birth forPython is: Feb 20th 1991.
Eg1: To print
Helloworld:
Python:
print("Hello World")
Python:
1) a=10
3) print("The Sum:",(a+b))
Features of Python
• Python is a high-level language. It is a free and open-source language.
• It 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.
1. Simple and easy to learn:
We can use Python software without any license and it is freeware. Its source
code is open, so that we can we can customize based on our requirement.Eg:
Jython is customized version of Python to work with Java Applications.
4. Platform Independent:
Once we write a Python program, it can run on any platform without rewriting
once again. Internally PVM is responsible to convert into machine
understandable form.
5. Portability:
6. Dynamically Typed:
This dynamic typing nature will provide more flexibility to the programmer.
7.
Both Procedure Oriented and Object Oriented
Python language supports both Procedure oriented (like C, pascal etc) and
object oriented(like C++,Java) features. Hence, we can get benefits of both
like security and reusability etc
8. Interpreted:
9. Extensible:
10. Embedded:
Python has a rich inbuilt library. Being a programmer we can use this library
directly and we are not responsible toimplement the functionality.
Flavors of Python:
1. CPython:
It is the standard flavor of Python. It can be used to work with C lanugage
Applications
2. Jython or JPython:
It is for Java Applications. It can run on JVM
3. IronPython:
It is for C#.Net platform
4. PyPy:
The main advantage of PyPy is performance will be improved because JIT
compiler isavailable inside PVM.
5. RubyPython
For Ruby Platforms
6. AnacondaPython
It is specially designed for handling large volume of data processing.
...
Python Versions:
Current versions
variable name.a = 10
By mistake if we are using any other symbol like @ then we will get syntax
error.
• cash = 10 √
• ca@h =20 x
• 123total x
• total123 √
• total=10
• TOTAL=999
• print(total) #10
• print(TOTAL) #999
1. Alphabet Symbols (Either Upper case OR Lower case)
1) 123total X
2) total123 √
3) java2share √
4) ca$h X
5) _abc_abc_ √
6) def X
7) if X
Note:
Eg: add
Reserved Words
In Python some words are reserved to represent some meaning or
functionality. Such typeof words is called Reserved words.
• True,False,None
• and, or ,not,is
• if,elif,else
• while,for,break,continue,return,in,yield
• try,except,finally,raise,assert
• import,from,as,class,def,pass,global,nonlocal,lambda,del,with
Note:
1. All Reserved words in Python contain only alphabet symbols.
2. Except the following 3 reserved words, all contain only lower-case alphabet
symbols.
• True
• False
• None
Eg: a= true X
a=True √
1. int
2. float
3. compl
ex
4.bool
5.str
6. bytes
7. bytearra
Y
8. range
9.list
10.tuple
11.set
12. frozen
set
13. dict
14.None
Note: Python contains several inbuilt
functions
1. type()
to check the type of variable
2. id()
to get address of object
3. print()
to print the value
Number
Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.
Note:
In Python2 we have long data type to represent very large integral values.
But in Python3 there is no long type explicitly and we can represent long
values also byusing int type only.
1. Decimal form
2. Binary form
3. Octal form
4. Hexa decimal form
1. Decimal form(base-10):
It is the default number system in PythonThe allowed digits are: 0 to 9
Eg: a =10
2. Binary form(Base-2):
The allowed digits are : 0 & 1
Literal value should be prefixed with 0b or 0B
Eg: a = 0B1111
a =0B123
a=b111
3. Octal Form(Base-8):
Eg: a=0o123
a=0o786
The allowed digits are : 0 to 9, a-f (both lower and upper cases are
allowed)Literal value should be prefixed with 0x or 0X
Eg:
a =0XFAC
a=0XBeef
a=10
b=0o10
c=0X10
d=0B10
print(a)
10
print(b)
8
print(c)
16
print(d)
2
Base Conversions
Python provide the following in-built functions for base conversions
1. bin():
to binaryEg:
1 >>> bin(15)
)
2 '0b1111'
)
3 >>> bin(0o11)
)
4 '0b1001'
)
5 >>> bin(0X10)
)
6 '0b10000'
)
2. oct():
Eg:
1 >>> oct(10)
)
2 '0o12'
)
3 >>> oct(0B1111)
)
4 '0o17'
)
5 >>> oct(0X123)
)
'0o443'
6
)
3. hex():
decimalEg:
1 >>> hex(100)
)
2 '0x64'
)
3 >>> hex(0B111111)
)
4 '0x3f'
)
5 >>> hex(0o12345)
)
6 '0x14e5'
)
Eg: f=1.234
type(f) float
Eg: f=1.2e3
print(f) 1200.0
instead of 'e' we can use 'E'
The main advantage of exponential form is we can represent big values in less
memory.
***Note:
We can represent int values in decimal, binary, octal and hexa decimal
forms. But we canrepresent float values only by using decimal form.
1) f=0B11.01
2) ^
SyntaxError: invalid syntax
j2 = -1
a + bj
j = √−1
Real Part Imaginary Part
values
Eg:
3+5j
10+5.5j
0.5+0.1j
In the real part if we use int value then we can specify that either by
decimal,octal,binary or hexa decimal form.But imaginary part should be
specified only by using decimal form.
1) >>> a=0B11+5j
2)>>>a
3) (3+5j)
c=10.5+3.6j
c.real==>10.5
c.imag==>3.6
b=True
type(b) =>bool
Eg:
a=10
b=20
c=a<b
print(c)==>True
True+True==>2
True-False==>1
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.
5. str type:
str represents String data type.
By using single quotes or double quotes we cannot represent multi line string
literals.
s1="Python
programming” X
For this requirement we should go for triple single quotes(''') or triple double
quotes(""")
s1='''Python
Programming'''
s1="""Python
Programming"""
We can also use triple quotes to use single quote or double quote in our
String.
Slicing of Strings:
slice means a piece
[ ] operator is called slice operator, which can be used to retrieve
parts of String.
-5 -4 -3 -2 -1
O F F E R
0 1 2 3 4
1 >>> s="OFFER"
2 >>> s[0]
3 'O'
4 >>> s[40]
1 >>> s[1:40]
2 'FFER'
3 >>> s[1:]
4 'FFER'
5 >>> s[:4]
6 'OFFE'
7 >>> s[:]
8 'OFFER'
9 >>> len(s)
10 5
Note:
1. In Python the following data types are considered as Fundamental Data
types
• int
• float
• complex
• bool
• str
2. In Python,we can represent char values also by using str type and
explicitly char type isnot available.
Eg:
1) >>> c='a'
3) <class 'str'>
4. In Python we can present char Value also by using str Type and
explicitly char Type isnot available.
list data type:
List is a sequence of items separated by commas and the items are enclosed in
square brackets [ ]
Eg:
1) list=[10,10.5,'python',True,10]
2) print(list) # [10,10.5,'python',True,10]
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.
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
>>> print(set1) {10, 20, 3.14, "New Delhi"}
None is a special data type with a single value. It is used to signify the absence
of value in a situation. None supports no special operations, and it is neither
same as False nor 0 (zero).
None means Nothing or No value associated. If the value is not available, then
to handle such type of cases None introduced.It is something like null value in
Java.
Eg:
def m1():
a=10
print(m1())
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. Items in a
dictionary 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.
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 [ ].
#create a dictionary
120
Duplicate keys are not allowed but values can be duplicated. If we are
trying to insert an entry with duplicate key then old value will be
replaced with new value.
Mutable and Immutable Data Types
Variables whose values can be changed after they are created and assigned
are called mutable.
Variables whose values cannot be changed after they are created and
assigned are called immutable.
When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory.
Concepts immutability
Constants:
1. Arithmetic Operators:
Python supports arithmetic operators that are used to perform the four basic
arithmetic operations as well as modular division, floor division and
exponentiation.
But Floor division (//) can perform both floating point and integral
arithmetic. If arguments are int type then result is int type. If atleast
one argument is float type thenresult is float type.
Relational Operators:
Eg:
1 10<20 ==>True
2 10<20<30 ==>True
3 10<20<30<40 ==>True
4 10<20<30<40>50 ==>False
Eg:
1) >>> 10==20==30==40
2) False
3) >>> 10==10==10==10
4) True
Logical Operators:
There are three logical operators supported by Python. These operators (and, or,
not) are to be written in lower case only.
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.
So if we say num1 = 10, num2 = -20, then both num1 and num2 are logically True.
0 means False
non-zero means True
empty string is always treated as False
Assignment Operators:
We can use assignment operator to assign value to the variable.
Eg:
x=10
+= ,-= ,*=,/=,%=,//=,**=&=,|=,>>=,<<=
Special operators:
Python defines the following 2 special operators
1. Identity Operators
2. Membership operators
1. 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. There are two identity
operators.
We can use identity operators for address comparison.
Note:
We can use is operator for address comparison where as ==
operator for contentcomparison.
2. Membership operators:
We can use Membership operators to check whether the given object
present in thegiven collection.(It may be String,List,Set,Tuple or Dict)
Collection
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.
(i) 100
(ii) num
(iii) num – 20.4
(iv) 3.0 + 3.14
(v) 23/3 -5 * 7(14 -2)
(vi) "Global" + "Citizen”
Operator Precedence:
Evaluation of the expression is based on 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.
Example
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement 4 64
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.
(new_data_type) (expression)
Following are some of the functions in Python that are used for explicitly
converting an expression or a variable to a different type.
Type Casting
We can convert one type value to another type. This conversion is
called Typecasting orType coersion.
The following are various inbuilt functions for type casting.
1. int()
2. float()
3. complex()
4. bool()
5. str()
1.int():
We can use this function to convert values from
1) >>> int(123.987)
2) 123
3) >>> int(10+5j)
4) TypeError: can't convert complex to int
5) >>> int(True)
6 1
)
7) >>> int(False)
8 0
)
9 >>> int("10")
)
10) 10
11) >>> int("10.5")
12) ValueError: invalid literal for int() with base 10: '10.5'
13) >>> int("ten")
14) ValueError: invalid literal for int() with base 10: 'ten'
15) >>> int("0B1111")
16) ValueError: invalid literal for int() with base 10: '0B1111'
Note:
2. float():
We can use float() function to convert other type values to float type.
1 >>> float(10)
)
2 10.0
)
3 >>> float(10+5j)
)
4) TypeError: can't convert complex to float
5) >>> float(True)
6 1.0
)
7) >>> float(False)
8 0.0
)
9 >>> float("10")
)
10) 10.0
11) >>> float("10.5")
12) 10.5
13) >>> float("ten")
14) ValueError: could not convert string to float: 'ten'
15) >>> float("0B1111")
16) ValueError: could not convert string to float: '0B1111'
Note:
1. We can convert any type value to float type except complex type.
3. complex():
Form-1: complex(x)
We can use this function to convert x into complex number with real
part x and imaginarypart 0.
Eg:
1 complex(10)==>10+0j
)
2 complex(10.5)===>10.5+0j
)
3) complex(True)==>1+0j
4) complex(False)==>0j
5 complex("10")==>10+0j
)
6 complex("10.5")==>10.5+0j
)
7) complex("ten")
8) ValueError: complex() arg is a malformed string
Form-2: complex(x,y)
We can use this method to convert x and y into complex number such
that x will be realpart and y will be imaginary part.
Eg: complex(10,-2)==>10-
2j
complex(True,False)==>1+
0j
4. bool():
1) bool(0)==>False
2) bool(1)==>True
3) bool(10)===>True
4) bool(10.5)===>True
5) bool(0.178)==>True
6) bool(0.0)==>False
7) bool(10-2j)==>True
8) bool(0+1.5j)==>True
9) bool(0+0j)==>False
10) bool("True")==>True
11) bool("False")==>True
12) bool("")==>False
5.str():
1) >>> str(10)
2) '10'
3) >>> str(10.5)
4) '10.5'
5) >>> str(10+5j)
6) '(10+5j)'
7) >>> str(True)
8) 'True'
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.
Output: 30.0
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
ii) Logical errors
iii) Runtime errors
Syntax errors
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. Such errors need to be removed
before the execution of the program.
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. A
logical error produces an undesired output but without abrupt termination
of the execution of the program. Since the program interprets successfully
even when logical errors are present in it, it is sometimes difficult to identify
these errors. The only evidence to the existence of logical errors is the wrong
output. While working backwards from the output of the program, one can
identify what went wrong. Logical errors are also called semantic errors as
they occur when the meaning of the program (its semantics) is not correct.
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 cannot execute it. Runtime errors do not appear until after
the program starts running or executing.
Accepting data as input from the console
and displaying output
1. raw_input()
2. input()
1. raw_input():
This function always reads the data from the keyboard in the form of
String Format. We have to convert that string type to our required type
by using the corresponding type casting methods.
Eg:
x=raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any input type
2. input():
x=input("Enter Value)
type(x)
Eg: x = eval(“10+20+30”)
print(x)
Output: 60
Within the Python Program this Command Line Arguments are available in argv.
Which ispresent in SYS Module.
test.py 10 20 30
Note: argv[0] represents Name of Program. But not first Command Line
Argument.argv[1] represent First Command Line Argument.
sysimport argv
print(type(argv))
D:\Python_classes\py test.py
output statements:
We can use print() function to display output.
Form-2:
1) print(String):
2) print("Hello World")
3) We can use escape characters also
4) print("Hello \n World")
5) print("Hello\tWorld")
6) We can use repetetion operator (*) in the string
7) print(10*"Hello")
8) print("Hello"*10)
9) We can use + operator also
10) print("Hello"+"World")