Python Basics
Python Basics
TION
Python was created by Guido Van Rossum when he was working at
CWI (Centrum Wiskunde & Informatica) which is a National Research
Institute for Mathematics and Computer Science in Netherlands. The
language was released in 1991. Python got its name from a BBC
comedy series from seventies called “Monty Python ′s Flying Circus”.
It is based on two programming languages called ABC and Modula–3.
Expressive Language: Because of simple syntax and fewer lines of code, it is more capable
to express code's purpose than many other languages
int a = 2, b = 3, temp; a, b = 2, 3
temp = a; a, b = b, a
a = b;
b = temp;
Interpreted Language: Python interprets and executes the code line by line at a time. It
makes Python an easy–to–debug language and thus suitable for beginners and advanced users
ADVANTAGES OF PYTHON
Completeness: Python CONTD…..
Standard Library provides various modules for
different functionalities. For example, it can be used for different
functionalities like email, web–pages, databases, GUI development,
network connections and many more. Hence no additional libraries to be
installed
Free and Open Source: Python is freely available at free of cost and its
source code is available to every body for further improvement
Lesser Libraries: Python offers library support for almost all computing
programs, but its library is still not competent with languages like C, Java, Perl as
they have larger collection of libraries
Not Easily Convertible: The syntax of Python language is simple but different
compared to other programming languages. Hence it is not easy to convert a
program which is in Python into other language
PYTHON
To write and run Python program, install Python interpreter in
computer. IDLE (GUI integrated) is the standard, most popular
Python development environment. IDLE is an acronym of
Integrated Development Environment. It lets edit, run, browse
and debug Python Programs from a single interface. This
environment makes it easy to write programs.
To create and run a Python script, the following steps to be used in IDLE
Digits 0–9
Unary Operator: If an operator takes only one operand then it is called Unary Operator
Binary Operator: If an operator takes two operands then it is called Binary Operator.
Ternary Operator: If an operator takes three operands then it is called Ternary Operator
'"#\()[]{}@,:.=
BASIC STRUCTURE OF
PYTHON PROGRAM
The following is a simple Python program
BASIC STRUCTURE OF PYTHON
PROGRAM CONTD…..
Expression: An expression is any valid combination of symbols and represents
a value
Comments: These are the statements that will be ignored by Python interpreter
and will increase readability of program. A single line comment starts with the
symbol #. For multiline comment content will be enclosed in triple quotes (" " ")
or triple apostrophe (' ' '). A multiline comment is also known as docstring.
Ex3: a, b, c = 5, 10, 7
b, c, a = a+1, b+2, c–1
print (a, b, c) # a=6, b=6, c=12
x = 10
print (x)
x = "Informatics Practices"
print(x)
10
Informatics Practices
VARIABLES CONTD…
Displaying type of variable : The type( ) can be used to
display the data type of a variable or constant or object
In the above case the value 10 inputted is assumed as string. Hence type of x is
string
Syntax:
print(object1, [object2, object3, ....., sep=' ' or seperator_string, end=' ' or
end_string])
Example Command Output
1 print("Informatics Practices") Informatics Practices
2 print("Sum of 2 and 3 is", 2+3) Sum of 2 and 3 is 5
a=2
3 b=3 Sum of 2 and 3 is 5
print("Sum of", a, "and", b, "is", a+b)
a=2
4 b=3 Sum of$2$and$3$is$5
print("Sum of",a,"and",b,"is",a+b, sep='$')
a=2
5 b=3 Sum of 2 and 3 is 5*
print("Sum of",a,"and",b,"is",a+b, end='*')
DATA TYPES
A data type represents the type of data like character, integer, real,
string etc. Different types of data types in Python are,
bool: These represent the truth values False and True, that resembles
integers 0 and 1 respectively. The bool( ) function returns the
boolean equivalent digit.
>>> bool(1)
True
>>> bool(0)
False
NUMBERS CONTD…
Floating Point Numbers: Numbers with fractions or decimal point
are called floating point numbers. A floating point number will
consist of sign (+,–) sequence of decimals digits and a dot such as
0.0, –21.9, 0.98333328, 15.2963. These numbers can be written in
two forms
>>> c=2–3j
>>> c.real
2.0
>>> c.imag
–3.0
DATA TYPES – NONE
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. It is used to define a null value, or no value at all.
None is not the same as 0, False, or an empty string.
>>> x=None
>>> print(x)
None
SEQUENCES
Sequence: A sequence is an ordered collection of items, indexed
by positive integers. It is combination of mutable and immutable
data types. Three types of sequence data type available in Python
are Strings, Lists & Tuples.
Example
>>> a = 'Ram'
SEQUENCES CONTD…
Every string is a sequence of characters. Every character in a
string has an index and the character can be accessed using its
index
Ex: 0 1 2 3 4 5
Index
String P Y T H O N
Index –6 –5 –4 –3 –2 –1
Every character has two indexes like above and can be accessed
using either of the two indexes
>>> name="PYTHON"
>>> print(name[2])
T
>>> print(name[–4])
T
SEQUENCES CONTD…
It is possible to change one type of value/variable to another type.
It is known as type conversion or type casting. The conversion
can be done explicitly (programmer specifies the conversions) or
implicitly (Interpreter automatically converts the data type).
Example1 Example2
>>> a= 12.34 >>>a=25
>>> b= int(a) >>>y=float(a)
>>> print (b) >>>print (y)
12 25.0
SEQUENCES CONTD…
Lists: List is also a sequence of values of any type. Values in the
list are called elements / items. These are mutable and
indexed/ordered. List is enclosed in square brackets.
Example: d = {1:'a',2:'b',3:'c'}
DATA TYPES – MUTABLE AND
IMMUTABLE TYPES
Immutable Types: The immutable types are those that can never
change their value in place. Integers, Floating Point Numbers,
Booleans, Strings and Tuples are immutable types
Mutable Types: The mutable types are those that can change
their value in place. Lists, Dictionaries and Sets are mutable
types
VARIABLE
that refer to a value.INTERNALS
The data or values are referred to as object. Similarly, a variable is also an object
Every object has three key attributes associated to it. These
are,
(i) type of object: The data type of a constant or variable can be displayed using
type( ) statement with the required argument
⮚Value and variables when used with operator are known as operands.
Arithmetic or Mathematical
Operators
Symbol Description Example 1 Example 2
>>>55+45 >>>'Good'+'Morning'
+ Addition
100 GoodMorning
>>>55–45 >>>30–80
– Subtraction
10 –50
>>>55*45 >>>'Good'*3
* Multiplication
2475 GoodGoodGood
>>>17/5 >>>28/3
3.4 9.33
>>>17/5.0
/ Division
3.4
>>>17.0/5
3.4
Remainder / >>>17%5 >>>23%2
%
Modulo Division 2 1
>>>2**3 >>>2**8
8 256
** Exponentiation
>>>16**.5
4.0
Integer Division (or) >>>7.0//2 >>>3//2
//
Floor Division 3.0 1
Relational Operators
Symbol Description Example 1 Example 2
>>>7<10
True
>>>7<5 >>>'Hello'<'Goodbye'
False False
< Less Than
>>>7<10<15 >>>'Goodbye'<'Hello'
True True
>>>7<10 and 10<15
True
>>>7>5 >>>'Hello'>'Goodbye'
True True
> Greater Than
>>>10>10 >>>'Goodbye'>'Hello'
False False
>>>2<=5 >>>'Hello'<='Goodbye'
True False
<= Less Than or Equal To
>>>7<=4 >>>'Goodbye'<='Hello'
False True
>>>10>=10 >>>'Hello'>='Goodbye'
True True
>= Greater Than or Equal To
>>>10>=12 >>>'Goodbye'>='Hello'
False False
>>>10!=11 >>>'Hello'!='HELLO'
True True
!= Not Equal To
>>>10!=10 >>>'Hello’!='Hello'
False False
>>>10==10 >>>'Hello'=='Hello'
True True
== Equal To
>>>10==11 >>>'Hello'=='Goodbye'
False False
Logical Operators
Symbol Description
and If any one of the operand is true, then the condition becomes true
or If both the operands are true, then the condition becomes true
>>> 2 in numSeq
Returns True if the variable True
or value is found in the >>> '1' in numSeq
in
specified sequence and False False
otherwise
#'1' is a string while numSeq
contains number 1.
>>> numSeq = [1,2,3]
Returns True if the
>>> 10 not in numSeq
variable/value is not found
not in True
in the specified sequence
>>> 1 not in numSeq
and False otherwise
False
Precedence of
Operators
While evaluating an expression the precedence of operators will
be like below. It gives the order of evaluation of operators in an
expression. However the precedence can be changed by using
parenthesis
EXPRESSION
an expression may be anS
An expression is a combination of literals, operators and variables. In Python,
arithmetic expression, string expression, relational
expression, logical expression, compound expression etc.
✔ Syntax Errors
✔ Runtime Errors
✔ Logical Errors
d = (b * b – (4 * a * c)
DEBUGGING
CONTD…
Runtime Errors: These errors are so called because
these will be occurred during runtime of program. A
program may be syntactically correct, but may generate
errors during run time. For example,
a = 10, b = 0;
c = a / b;
✔ In the first statement, two built–in functions used are int( ) and input( ).
The third line has a function print( )
✔ Similarly the print function has four arguments "the square of", num, "is",
✔ The int function in the first line takes as argument the value entered by
the
user from the keyboard and converts it into a string and returns it. Thus
the return value from the int( ) function is an integer.
Some examples for built–in functions are print( ), bool( ), dict( ), list( ),
Statement Flow Control
⮚Empty Statement
⮚Simple (Single) Statement
⮚Compound(Multiple) Statement
Example 2: print(name)
Body: It consists of one or more indented statements inside the header line. All the
statements in the body are at the same level of indentation
Syntax:
<compound statement header>:
<indented body containing multiple simple and / or compound statements>
SELECTION / CONDITIONAL
STATEMENTS
SELECTION / CONDITIONAL STATEMENTS
CONTD…
SELECTION / CONDITIONAL STATEMENTS
CONTD…
The if–elif Statement:
if <condition>:
statements1
elif <condition>:
statements2
elif <condition>:
statements3
else:
statements
SELECTION / CONDITIONAL STATEMENTS
CONTD…
The nested if statement:
Ex:
if <condition>:
if <condition>:
statements1a
else:
statements1b
elif <condition>:
statements2
elif <condition>:
statements3
else:
statements
ITERATIVE / REPETITIVE / LOOP
STATEMENTS
The while loop:
✔ When the control enters while loop the logical expression will be evaluated
✔ If it evaluates to true then the statements part will be executed and again control
transfers to logical_expression part
✔ If the logical expression returns false then the control will be exited from while loop
✔ If the condition becomes false then the else part will be executed, if present
ITERATIVE / REPETITIVE / LOOP STATEMENTS
CONTD…
The range( ) function:
This function generates a list which is a special sequence type. A sequence is a succession of
values bound together by a single name. Some sequence are: strings, lists, tuples etc.
Use : The function in the form range(l, u) will produce a list having values
starting from l to u–1(Upper limit not included), where l and u are integers.
If step value is ignored then default step value is +1
These operators are used along with range( ) to check whether a value is
contained inside a list or not. These operators returns a value either True or False
Boolean Value
Example Expression
Returned
1 3 in [1, 2, 3, 4] True
2 5 in [1, 2, 3, 4] False
3 5 not in [1, 2, 3, 4] True
4 ′a′ in ″trade″ True
5 ″ash″ in ″trash″ True
6 ″the″ in ″Python″ False
ITERATIVE / REPETITIVE / LOOP STATEMENTS
CONTD…
The for loop:
❖ All the statements in the body of for loop are executed with assigned value of
loop variable
❖ Now, the loop–variable is assigned the next value in the sequence and the
loop–body is executed with new value of loop–variable
❖ After processing all the elements in the sequence the else part
will be executed,
if present