Unit-1 Introduction To Python, Datatypes, Operators, Conditional Statements
Unit-1 Introduction To Python, Datatypes, Operators, Conditional Statements
Unit-I
Introduction to Python Programming
-Python is an interpreted, object-oriented programming language.
-It was created by Guido van Rossum in 1989, and released in 1991.
-ABC programming language is said to be the predecessor of Python language.
-Python is influenced by following programming languages:
*ABC language *Modula-3
-This programming language was named as Python because. One comedy
seriesnamed- Monty Python's Flying Circus
Applications of Python:
Python is known for its general-purpose nature that makes it applicable in almost
every domain of software development.
Here, we are specifying application areas where Python can be applied.
1) Web Applications:
We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML, XML, Email processing ,etc.
One of Python web-framework named Django is used on Instagram.
3) Console-based Application:
Console-based applications run from the command-line or shell. These applications
are computer program which are used commands to execute.
5) Software Development:
Python is useful for the software development process. It works as a support language
and can be used to build control and management, testing, etc.
-Computers understands only machine code i.e. 1s and 0s.Our source code is in high
level language which needs to convert in machine level language.
-Compiler normally converts the source code into machine code called as byte code
size of each byte code (instruction) is 1 byte.
2
-Byte code is platform independent. The roll of Python Virtual Machine (PVM) is to
convert byte code into machine code. Computer can execute this machine code and
gives final output.
-The PVM is equipped with an interpreter. Interpreter checks and understand
processor and OS.according to this interpreter converts byte code into machine code
and sends that machine code to processor for execution.
-Since interpreter plays main role, often the PVM is also called as interpreter
Datatypes in Python :-
Tokens In Python:
“Token is nothing but smallest individual unit of Python program.”
Python program has classes and every classes has some methods and methods contains
executable statement and every executable statement contains the tokens i.e.
statements are made up of several tokens.
Python supports 4 types of Tokens
1) Keywords 2) Identifiers 3) Literals 4) Operators
1) Keywords
The Keywords are reserved words, whose meaning is already known by Python
compiler.
Each keyword have unique and fixed meaning and we are not able to change that
meaning therefore they are also called as ‘Reserved Words’
Let’s see Python Keywords
3
2) Python Identifiers
“Identifier is the name given by the programmer for any variable, package, class,
interface, array, object etc.”
It helps to differentiate one entity from another.
Rules for writing identifiers
i) Identifiers can be a combination of letters in lowercase or uppercase or digits or an
underscore _.
ex. myClass, var_1 and print_this_to_screen, all are valid example.
ii) An identifier cannot start with a digit.
ex. 1name (It is invalid)
iii) Keywords cannot be used as identifiers.
ex. global = 1 (It is invalid because global is a keyword)
iv) We cannot use special symbols like !, @, #, $, % etc. in our identifier.
v) An identifier can be of any length.
3) Literals
A literal represent a fixed value that is stored into variable directly in the program.
They are represented directly in the code without any computation.
Literals can be assigned to any variable.
e.gstr=”welcome” or x=10 etc.
following are types of literals,
• String literals :- "hello" , '12345'
• Int literals :- 0,1,2,-1,-2
• Long literal- :: 89675L
• Float literals :- 3.14
• Complex literals :- 12j
• Boolean literals :- True or False
• Special literals :- None
• Unicode literals :- u"hello"
• List literals :- [], [5,6,7]
• Tuple literals :- (), (9,),(8,9,0)
• Dict literals :- {}, {'x':1}
• Set literals :- {8,9,10}
4) Operators
Operators are special symbols in Python that operates in operands. And the operands
are nothing but Data values.
Python divides the operators in the following groups:
i) Arithmetic operators
ii) Assignment operators
4
iii) Comparison operators
iv) Logical operators
v) Identity operators (Special Operator)
vi)Membership operators (Special Operator)
vii) Bitwise operators
i) Arithmetic operators :-
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
5
*Program for Assignments operators:-
x=15
print("\n Assignment operator:",x)
x+=5 #same like x=x+5
print("\n Addition assignment:",x)
x/=5 #same like x=x/5
print("\n Division assignment:",x)
6
*Program for comparison operator :-
x=15
y=20
if(x>y):
print("\n x is greater")
else:
print("\n Y is greater")
-Here logical and operator returns true result if and only if both conditions are true.
-The logical or operator returns true result when both the conditions are true
Also returns true value when at least one condition is true
- The logical not operator complements the result .i.e. True converted in false
And false converted in true.
* Program for logical and operator :-
x=15
y=20
if(x>y and x==15):
print("\n Condition is true")
else:
print("\n Condition is false")
7
* Program for logical or operator :-
x=15
y=20
if(x>y or x==15):
print("\n Condition is true")
else:
print("\n Condition is false")
x=15
y=20
if not(x>y):
print("\n Condition is true")
else:
print("\n Condition is false")
v) Identity Operators :-
is and is not are the identity operators in Python. They are used to check if two values
(or variables) are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
In above program variable x and y have same value i.e. 20, we know that if multiple
variables have same values then a common memory location is allocated to those same
valued variables.
is operator returns True when multiple variables have common memory location.
9
vii) Bitwiseoperators :-
x=10
y=4
print("\n output of bitwise and-",int(x&y));
print("\n output of bitwise or-",int(x|y));
print("\n output of bitwise not-",int(~x));
print("\n output of bitwise EXOR-",int(x^y));
print("\n output of bitwise shift right-",int(x>>y));
print("\n output of bitwise shift Left-",int(x<<y));
* Operator Precedence:
10
* Associativity of Python Operators :-
• We can see in the previous table that more than one operator exists in the same
group. These operators have the same precedence.
• When two operators have the same precedence, associativity helps to determine
the order of operations.
• Associativity is the order in which an expression is evaluated that has multiple
operators of the same precedence. Almost all the operators have left-to-right
associativity.
• For example, multiplication and floor division have the same precedence. Hence,
if both of them are present in an expression, the left one is evaluated first.
• # Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))
• Note: Exponent operator ** has right-to-left associativity in Python.
# Shows the right-left associativity of **
# Output: 512, Since 2**(3**2) = 2**9
11
print(2 ** 3 ** 2)
• # If 2 needs to be exponatedfisrt, need to use ()
# Output: 64
print((2 ** 3) ** 2)
Some operators like assignment operators and comparison operators do not have
associativity in Python. There are separate rules for sequences of this kind of operator
and cannot be expressed as associativity.
Python Datatypes
Variable:“Variable is the name given to the memory location where the data is stored”.
Unlike other programming languages, Python has no command for declaring a variable.
A variable is created the moment we first assign a value to it.
• There are several rules to declare the variable:
1) Variable should not be keyword.
2) Variable should not start with digit.
3) Variable can be combination of alphabets, digits or underscore.
4) Variable should not contain special symbol except underscore.
5) Variable should not contain any white space character like horizontal tab, vertical tab,
new line etc.
6) Variable can be of any length.
Example
x = 5
y = “Sangola"
print(x)
print(y)
Here,
Variables do not need to be declared with any particular type and can even change type after they
have been set.
String variables can be declared either by using single or double quotes:
-print() is a function which is used to print anything in python
1)Local Variable:
The variables which are declared inside methods, constructors or blocks are called local
variables.
These variables are declared and initialized within the method and they will be destroyed
automatically when the method completes its execution.
12
2)Global variable
The variables which are declared outside methods, constructors or blocks are called global
variables.
The scope of global variable is entire program.
Constants:
Constant is a value that remains the same and does not change or it cannot be modified.
Python does not allow us to create constants as easy as we do in C, C++ or Java
In Python, we can define constants in a module, where a module is a file which could be
imported to access the defined constants and methods.
Note: A module constant should be in uppercase alphabets, where multi-word constant
Example:
Step 1 :Create a module and define a constant.
save module file by any name
Here we save module as conex.py
INK = 'RED'
PI = 3.14
Step 2: import our module in python terminal or in new script and use it.
To access our constant following syntax will be used
Modulename.constatname
importconex
Here first we imported our module asimport conexafter that we accessed our constants INK
and PI asconex.INK and conex.PI
13
Data Types In Python:
1)Numeric Type:
• There are three numeric types in Python:
int: for integral values
float: for floatl value
complex: for complex numbers
• Variables of numeric types are created when we assign a value to them.
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Here we assigned numeric values to variables x,y,and z and we used type()function to know
14
data types of variables x,y, and z.
Type Conversion:
Type Conversion is a process to convert one data type value in another.
We can convert from one type to another with the int(), float(), and complex() methods:
Example:
x = 1 # int
y = 2.8 # float
b = int(y)
print(type(a))
print(type(b))
2) String:
String literals in python are surrounded by either single quotation marks, or double quotation marks
or Triple quotation.
Ex. ‘Hello’ or “Hello” or “””Hello”””
a = "Hello"
print(a)
• Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
• However, Python does not have a character data type, a single character is simply a string
with a length of 1.
• We will see String in details in next chapter.
3) List:
A list is a collection of elements or items which is ordered and changeable.
List allows duplicate members.
In Python lists are written with square brackets.One list can contain another list as Element.
Example to create a List:
x = [1,2,3,"apple",[11,22]]
print(x)
5) Set:
• Set is a collection of elements which is unordered and indexed.
• There are no duplicate members in Set.
• In Python set is written with curly brackets
• Example to create a Set:
z = {5,10, "cherry"}
print(z)
6) Dictionary:
• A dictionary is a collection which is unordered, changeable and indexed.
Dictionary do not allows duplicate members.
• In Python dictionaries are written with curly brackets, and they have keys and values.
• Example
a={
"brand": "Ford",
"model": "Mustang",
"year": 2019
}
print(a)
7) Boolean Type:
• Booleans represent one of two values: True or False.
• In programming we often need to know if an expression is True or False.
• We can evaluate any expression in Python, and get one of two answers, True or False.
• When we compare two values, the expression is evaluated and Python returns the Boolean
answer
• The bool() function allows us to evaluate any value, and give us True or False in return
print(10 > 9)
print(bool("Hello"))
print(bool(0))
8) Bytes Type:
16
• The bytes type in Python is immutable and stores a sequence of values ranging from 0-255
(8-bits).
y=bytes(4)
print(y)
print(type(y))
*Control Statements/Structure:
The control structure is used to control flow of execution of python program.
The control structure are as follows
a) If…else statements (Decision making)
b) Looping (for loop and while loop)
c)break and continue statements
a) Decision Making :
• Decision making is required when we want to execute a code only if a certain condition is
satisfied.
• We can make decision with the help of,
if Statement
if...else statement
if...elif...else Statement
Nested if statements
Let’s see them in brief
i) if statement:
• Python gives us a conditional if statement, which is used when we want to test a condition.
• This condition is evaluated for a boolean value true or false.
Syntax
if(test_condition):
statement(s)
x=10
y=5
if(x>y):
print("x is greater")
Output: X is greater
Syntax of if...else
if(test_condition):
Body of if
else:
Body of else
x=10
y=5
if(x>y):
print("x is greater")
else:
print("y is greater")
Output: X is greater
Syntax of if...elif...else
if(test_condition):
Body of if
elif(test_condition):
Body of elif
else:
Body of else
per=55
if(per>70):
print("Distinction") Output: Second class
if(test_condition):
body
if(test_condition):
body
x=120
if(x<200):
print("value is less than 200")
if(x<150):
print("\n also less than 150")
b) Looping(Loops):
A Loop is sequence of instruction/s that repeated until certain condition is reached.
There are following loops present in python
i)for loop
ii) while loop
i) for loop:
• The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects.
• Iterating over a sequence is called traversal.
Syntax of for Loop
19
Here each item from sequence is assigned to variable one by one. The loop terminates when there
Is no any item left in sequence.
Program of for loop
x=[0,1,5]
for p in x:
print(p)
x=[0,1,5]
for p in range(1,10):
print(p)
20
We used range() function to create a sequence of numbers as,
Range(1,10) where 1 is start and 10 is stop. By this a sequence if 1 to (10-1)=9is created.
The step size is optional part
ii) while loop : The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
• We generally use this loop when we don't know the number of times to iterate beforehand.
Syntax of while Loop in Python
while (test_expression):
Body of while
i=1
while(i<=10):
print(i)
i+=1
21
* break:
• The break statement terminates the loop containing it.
• Control of the program flows to the statement immediately after the body of the loop.
• If the break statement is inside a nested loop (loop inside another loop), the break statement
will terminate the innermost loop.
* continue :
• The continue statement is used to skip the rest of the code inside a loop for the current
iteration only.
• Loop does not terminate but continues on with the next iteration.
Program for continue
for val in "string":
ifval == "i":
continue
print(val)
print("The end")
a=10
b=0
assert b!=0
print (a/b)
print() function :
• We use the print() function to output data to the standard output device (screen).
• We can also output data to a file, but this will be discussed later.
• An example of its use is given below.
print('This sentence is output to the screen')
• Another example is given below:
a=5
print('The value of a is', a)
input() function :
• Up until now, our programs were static. The value of variables was defined or hard coded
into the source code.
• To allow flexibility, we might want to take the input from the user. In Python, we have
the input() function to allow this.
• The syntax for input() is:
input([prompt])
• where prompt is the string we wish to display on the screen. It is optional.
s=input(‘enter any string’)
Note: input() function accepts all inputs in string format so we have to do typecasting as
per necessary.
23
Command Line Arguments :-
The Argument that is passing at the time of execution is called the Command Line Argument.
➢ Using sys.argv
The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment and maintained by the interpreter. One such variable is sys.argv, which is a
simple list structure. Its main purpose is:
It is a list of command line arguments.
len(sys.argv) provides the number of command line arguments.
sys.argv[0] is the name of the current Python script.
Within the Python Program, these Command Line Arguments are available in argv. Which is
present in SYS Module.
Note: argv[0] represents Name of Program. argv[1] represents the First Command Line Argument.
To display Command Line Arguments :-
* Nested Loop :
A loop inside loop is called as nested loop.
Program for nested loop
rows=6
for i in range(rows):
for j in range(i):
print('*',end=" ")
print(" ")
24