Unit 1
Unit 1
PYTHON PROGRAMMING
UNIT-I INTRODUCTION TO PYTHON
PROGRAMMING
Introduction to Python Programming – Python Interpreter and
Interactive Mode – Variables and Identifiers – Arithmetic Operators–
Values and Types – Statements - Operators – Boolean Values –
Operator Precedence – Expression - Conditionals: if, if-else, if elif else
Constructs
What is Python?
print("Hello, World!")
Python Interpreter
• The Python interpreter can runPython programs that
are saved infiles, or can interactively executePython
statements that are typedat the keyboard. Python
comeswith a program named IDLE thatsimplifies the
process of writing,executing, and testing programs.
Python Interpreter
• The Python Interpreter
• •A program that can read Python programming statements
andexecute them is thePython interpreter
• •Python interpreter has two modes:
• –Interactivemode waits for a statement from the keyboard and executes it
• –Scriptmode reads the contents of a file (Python programorPython script) and
interprets each statement in the file
Python Interpreter
• Interpreter Mode
•Invoke Python interpreter through Windows or command line
•>>>is the prompt that indicates the interpreter is waiting for aPython
statement
>>>python test.py
Python Variables
• Variable names can be any length can have uppercase, lowercase A to Z, a to z),
the digit 09, and underscore character(_). Consider the following example of valid
variables names.
• Example
name = "A"
Name = "B"
naMe = "C"
NAME = "D"
n_a_m_e = "E"
_name = "F"
name_ = "G"
_name_ = "H"
na56me = "I"
• The multi-word keywords can be created by the following
method.
• Camel Case - In the camel case, each word or abbreviation
in the middle of begins with a capital letter. There is no
intervention of whitespace. For example - nameOfStudent,
valueOfVaraible, etc.
• Pascal Case - It is the same as the Camel Case, but here
the first word is also capital. For example - NameOfStudent,
etc.
• Snake Case - In the snake case, Words are separated by
the underscore. For example - name_of_student, etc.
Multiple Assignment
# Calling a function
add()
Output
The sum is: 50
Global Variables
• Global variables can be used throughout the program, and its scope is in the entire program. We can use global variables inside or outside the function.
• A variable declared outside the function is the global variable by default. Python provides the global keyword to use global variable inside the function. If
we don't use the global keyword, the function treats it as a local variable. Let's understand the following example.
# Declare a variable and initialize it
x = 101
mainFunction()
print(x)
101 Welcome To Javatpoint Welcome To Javatpoint
• Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Delete a variable
• We can delete the variable using the del keyword. The syntax is
given below.
del <variable_name>
Eg
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
VARIABLES
• A variable is a location in memory used to store some data (value).
They are given unique names to differentiate between different
memory locations.
• Variable names can be of any length. They can include both letters
and numbers, but they can’t begin with a number. It is legal to use
uppercase letters, but it is conventional to use only lower case for
variables names.
• The underscore character, _, can appear in a name. It is often used in
names with multiple words, such as your_name , air_speed, etc.
• Keywords cannot be used as variable names.
• Example:
• a, read_a, b1 etc
VALUES AND TYPES: INT, FLOAT, BOOLEAN,
STRING, AND LIST
• A value is one of the basic thing to work with a program like a letter or
a number. Some values are 2, 42.0, and 'Hello, World!'.
• These values belong to different types: 2 is an integer, 42.0 is a
floating-point number, and 'Hello, World!' is a string.
INT:
• Integers represent negative and positive integers without fractional
parts.
• >>> type(2)
• <class 'int'>
FLOAT:
Floating point numbers represents negative and positive numbers
with fractional parts
>>> type(42.0)
<class 'float'>
• BOOLEAN:
• The simplest built-in type in Python is the bool type, it represents
the truth values,(True or False)
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
STRING:
• A string type object is a sequence (left-to- right order) of characters.
Strings start and end with single or double quotes. Python strings are
immutable (Once a string is generated, you can not change any
character within the string).
LIST:
>>> type('Hello, World!')
<class 'str'>
A list is a container which holds comma-separated values (items or
elements) between square brackets where all the items or elements
need not to have the same type.
• A list without any element is called an empty list.
>>>list = [ 'abcd', 786 , 2.23, 'name', 70.2 ]
>>> print (list)
[ 'abcd', 786 , 2.23, 'name', 70.2 ]
>>>list1=[ ]
>>>print(list1)
[]
EXPRESSIONS AND STATEMENTS:
2
INTERACTIVE MODE PROGRAMMING
Once Python is
installed,
typing
will python
invoke theininterpreter
the command
in
immediate mode. line
We can directly typein
Python
code, and press Enter to get
the output.
This prompt can be used
as a calculator.
To exit this mode, type quit()
and press enter.
For example,
3
SCRIPT MODE PROGRAMMING - IDE
IDE - Integrated Development Environment
When you install Python, an IDE named IDLE is also installed
We can use any text editing software to write a Python
script file.
When you open IDLE, an interactive Python Shell is opened.
Now you can create a new file and save it
with .py extension.
Write Python code in the file and save it.
To run the file, go to Run > Run Module or simply click F5.
For example,
4
PYTHON KEYWORDS
5
RULES FOR WRITING IDENTIFIERS
Multi-line statement
▪ The end of a statement is marked by a newline character (\).
a=1+2+3+\
4+5+6+\
7+8+9
▪ Multiple statements in a single line using semicolons.
a = 1; b = 2; c = 3
7
CONTINUATION…
Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly
enforced.
For example −
if True:
print ("True")
else:
8
print ("False")
PYTHON COMMENTS
All characters after the #, up to the end of the physical line, are part of the
comment and the Python interpreter ignores them.
# First comment
print (“Welcome to college!") # second comment This produces the following
result −
Welcome to college!
9
QUOTATION IN PYTHON
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as
long as the same type of quote starts and ends the string.
The triple quotes are used to span the string across multiple lines.
For example,
word = 'word'
sentence = "This is a sentence." paragraph = """This is a paragraph. It is
10
CLEAR WINDOWS
>>> import os
>>> clear =
os.system("cls")
11
STANDARD DATA TYPES
>>> xyz
13
15
PYTHON - NUMBERS
You can also delete the reference to a number object by using the del
statement.
You can delete a single object or multiple objects by using the del
statement.
For example,
>>> del abc
>>> abc
Traceback (most recent call last): File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
>>> xyz 150
>>> aa=9
>>> bb=5
>>> aa 9
>>> bb 5
14
>>> del aa,bb
PYTHON - NUMBERS
For example,
15
PYTHON - STRINGS
For example,
Strings in Python are identified as a
>>> it="Welcome to Python class"
contiguous set of characters represented >>> it
in the quotation marks. 'Welcome to Python class'
Python allows either pair of single or >>> print(it)
double Welcome to Python class
quotes. >>> print(it[0]) W
>>> print(it[8:10])
Subsets of strings can be taken using the
to
slice operator ([ ] and [:] )
Indexes 0 Thebeginnin of the >>> print(it[11:]) Python class
starting at in g >>> print(it[-4:22])
string and their wayfrom to the STTP
working -1 16
end.
PYTHON - STRINGS
For example,
The (+) sign is thestring >>> print(it)
plus
concatenation Welcome to Python class
operator.
The asterisk (*) is the repetition >>> print("Hearty " + it)
operator. Hearty Welcome to Python class
>>> print(it+" By CSE Department")
Welcome to Python class By CSE
Department
>>> print(it*2)
Welcome to Python classWelcome 17
to Python class
PYTHON - LISTS
print(list1[3:])
The plus (+) sign is the list concatenation
['cse', 100.5]
PYTHON - TUPLES
For example,
A tuple is another sequence data type that is >>> tuple1 = ( "FX", "cse","Department" )
similar >>> tuple2=("Welcome",1234)
>>> print(tuple1)
to the list.
('FX', 'cse', 'Department')
A tuple consists of a number of values >>> print(tuple2) ('Welcome', 1234)
separated by commas. >>> print(tuple1+tuple2)
('FX', 'cse', 'Department', 'Welcome', 1234)
Unlike lists, however, tuples are enclosed >>> print(tuple2*3)
within parenthesis. ('Welcome', 1234, 'Welcome', 1234, 'Welcome',
1234)
The values stored in a tuple can be accessed >>> print(tuple1[0])
using FX
the slice operator ([ ] and [:]) >>> print(tuple1[1:3]) ('cse', 'Department')
print(tuple1[1:])
The plus (+) sign is the concatenation
('cse', 'Department')
PYTHON - TUPLES
For example,
The main difference between lists and tuples >>> list2=["Welcome",1234]
are − >>> tuple2=("Welcome",1234)
>>> print(list2)
Lists are enclosed in brackets ( [ ]
['Welcome', 1234]
) and their elements and size can be >>> print(tuple2) ('Welcome', 1234)
changed,
>>> list2[1]=5000
Tuples are enclosed in parentheses ( >>> print(list2) ['Welcome', 5000]
( ) ) and >>> tuple2[1]=5000
cannot be updated. Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Tuples can be thought of as read-only lists.
TypeError: 'tuple' object does not
support item assignment
20
PYTHON - DICTIONARY
• For example,
•>>> dict1={}
Python's dictionaries are kind of hash-table •>>> dict1['one'] = "ONE"
type. •>>> dict1[2] = "TWO"
•>>> print(dict1)
A dictionary consist of key-value pairs. •{'one': 'ONE', 2: 'TWO'}
Dictionaries are enclosed by curly braces ({ •>>> print(dict1['one']) ONE
}) and values can be assigned and accessed •>>> print(dict1[2]) TWO
using square braces ([]). •>>> dict2 = {'name': "class",'code':7, 'dept': "cse"}
•>>> print(dict2)
•{'name': 'class', 'code': 7, 'dept': 'cse'}
•>>> print(dict2.keys()) dict_keys(['name', 'code',
'dept'])
>>> print(dict2.values()) 21
dict_values(['class', 7,
'cse'])
TYPES OF OPERATOR
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 21
=
100000000000000000000
0
// Floor Division - The division of operands where the result is 9//2 = 4 and 9.0//2.0 =
the quotient in which the digits after the decimal point are 4.0,
PYTHON COMPARISON OPERATORS
!= If values of two operands are not equal, then condition becomes (a!= b) is true = True
true.
> If the value of left operand is greater than the value of right (a > b) is not true =
operand, then condition becomes true. False
< If the value of left operand is less than the value of right (a < b) is true. = True
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the value (a >= b) is not true = False
of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the value of (a <= b) is true = True 24
+= Add AND It adds right operand to the left operand and assign the c += a is equivalent to c = c + a
result to left operand
-= Subtract AND It subtracts right operand from the left operand and assign c -= a is equivalent to c = c - a
the result to left operand
*= Multiply AND It multiplies right operand with the left operand and assign c *= a is equivalent to c = c * a
the result to left operand
/= Divide AND It divides left operand with the right operand and assign the c /= a is equivalent to c = c / ac /=
result to left operand a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to c %= a is equivalent to c = c % a
left operand 25
**= Exponent AND Performs exponential (power) calculation on operators and c **= a is equivalent to c = c ** a
assign
PYTHON BITWISE OPERATORS
^ Binary XOR It copies the bit, if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
>> Binary Exactly opposite to the left shift operator. The left operand bits are a >> 2 = 15 (means 0000
Right Shift moved towards the right side, the right side bits are removed. Binary 11112)6
number 0 is appended to the beginning.
PYTHON LOGICAL OPERATORS
or Logical OR If any of the two operands are non-zero (true) then condition (a or b) is True. (means 1)
becomes true.
not Logical Used to reverse the logical state of its operand. ❖ Not (a and b) is True.
NOT (means True)
❖ Not (a or b) is False.
(means False)
27
PYTHON MEMBERSHIP OPERATORS
if x is a member of sequence y.
not in Evaluates to true if it does not finds a variable in the x not in y,
specified sequence and false otherwise.
here not in results in a 1,
() Parentheses
** Exponent
+, - Addition, Subtraction
<<, >> Bitwise shift operators
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
or Logical OR 30