Chap-2 Basics of Python Programming
Chap-2 Basics of Python Programming
PYTHON PROGRAMMING
PROGRAMMING -- II
Chap - 2 By-
Prof. A. P. Chaudhari
within identifiers.
• Class names start with an uppercase letter. All other identifiers start
private identifier.
• If the identifier also ends with two trailing underscores, the identifier is
Python does not have a syntax for multi-line comments. If you wish to
add a multiline comment you could insert a # for each line, as like in following
code:
# This is a comment.
# This is a comment, too.
# This is more comment
Expressions and Statements:
Expression:
Expression in any programing language is a combination of values, and
operators. A value is also considered expression and same with a variable, so
the followings are all legal expressions.
e.g.: If you type an expression in an interactive mode, the interpreter
evaluates it and display the result:
1) >>> 5 * 4
20
2) >>> 2 + 2
4
3) >>> 'ABC‘ + 'abc'
'ABCabc'
Expressions and Statements:
Statements:
A statement is a part of code that is executed by the Python interpreter.
When you type a statement in interactive mode, the interpreter executes it and
display the result, if there is one statement.
A script usually contains a sequence of statements. If there is more than
one statement, the result appear at a time as the statement execute.
e.g.:
print 10
x = 20
print x
O/P: 10
20
Data Types:
The data stored in memory can be of many types. For example,
a person's age is stored as a numeric value and his or her address is
stored as alphanumeric characters. Python has various standard data
types that are used to define the operations possible on them and the
storage method for each of them.
Python has five standard data types −
1) Numbers
2) String
3) List
4) Tuple
5) Dictionary
Data Types:
1) Numbers:
Number data types store numeric values. Number objects are
created when you assign a value to them. For example −
var1 = 1
var2 = 10
Python supports four different numerical types −
i. int (signed integers)
ii. long (long integers, they can also be represented in octal and hexadecimal)
iii. float (floating point real values)
iv. complex (complex numbers)
Data Types:
Here are some examples of numbers −
int long float complex
10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
• Python allows you to use a lowercase l with long, but it is recommended that you
use only an uppercase L to avoid confusion with the number 1. Python displays
long integers with an uppercase L.
• A complex number consists of an ordered pair of real floating-point numbers
denoted by x + yj, where x and y are the real numbers and j is the imaginary unit.
Data Types:
2) Strings:
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks. Python allows for either pairs of single or
double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the string.
The plus (+) sign is the string concatenation operator and the asterisk (*)
is the repetition operator. For example −
str = ‘Good Morning'
print str # Prints complete string (Good Morning)
print str[0] # Prints first character of the string (G)
print str[5:8] # Prints characters starting from 5th to 8th (Morn)
print str[5:] # Prints string starting from 5th character (Morning)
print str * 2 # Prints string two times (Good MorningGood Morning)
print str + “ Ram" # Prints concatenated string (Good Morning Ram)
Data Types:
3) Lists:
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets ([ ]). To
some extent, lists are similar to arrays in C. One difference between them is that
all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ]
and [:]) with indexes starting at 0 in the beginning of the list. The plus (+) sign is
the list concatenation operator, and the asterisk (*) is the repetition operator.
For example −
list = [ 'abcd', 135, 2.23, ‘shyam', 70.2 ]
tinylist = [123, ‘viraj']
Data Types:
list = [ 'abcd', 135, 2.23, ‘shyam', 70.2 ]
tinylist = [123, ‘viraj']
print list # Prints complete list [ 'abcd', 135, 2.23, ‘shyam', 70.2 ]
print list[0] # Prints first element of the list abcd
print list[1:3] # Prints elements starting from 2nd till 3rd [135, 2.23]
print list[2:] # Prints elements starting from 3rd element [2.23, shyam ', 70.2]
print tinylist * 2 # Prints list two times [123, ' viraj ', 123, ' viraj ']
print list + tinylist # Prints concatenated lists
[ 'abcd', 135, 2.23, ‘shyam', 70.2, 123, ‘viraj']
Data Types:
4) Tuples:
A tuple is another sequence data type that is similar to the list. A tuple
consists of a number of values separated by commas. Unlike lists, however,
tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of
as read-only lists.
For example −
tuple = ('abcd', 135, 2.23, ‘shyam', 70.2)
tinytuple = (123, ‘viraj')
Data Types:
tuple = ('abcd', 135, 2.23, ‘shyam', 70.2)
tinytuple = (123, ‘viraj')
print tuple # Prints complete list ('abcd', 135, 2.23, ‘shyam', 70.2)
print tuple[0] # Prints first element of the list abcd
print tuple[1:3] # Prints elements starting from 2nd till 3rd (135, 2.23)
print tuple[2:] # Prints elements starting from 3rd element
(2.23, ‘shyam', 70.2)
print tinytuple * 2 # Prints list two times (123, ‘viraj‘, 123, ‘viraj')
print tuple + tinytuple # Prints concatenated lists
('abcd', 135, 2.23, ‘shyam', 70.2, 123, ‘viraj')
Data Types:
The following code is invalid with tuple, because we attempted to update a
tuple, which is not allowed. Similar case is possible with lists −
print dict ['one'] # Prints value for 'one' key This is one
print dict[2] # Prints value for 2 key This is two
print tinydict # Prints complete dictionary
{'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys ['dept', 'code', 'name']
print tinydict.values() # Prints all the values ['sales', 6734, 'john']
Function Description
If the value of left operand is less than or equal to the value of right
<= a<=b is true.
operand, then condition becomes true.
Operators:
3) Assignment Operators :
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
Assigns values from right side operands to left c = a + b assigns
=
side operand value of a + b into c
+= It adds right operand to the left operand and c += a is equivalent to
Add AND assign the result to left operand c=c+a
-= It subtracts right operand from the left operand c -= a is equivalent to
Subtract AND and assign the result to left operand c=c-a
*= It multiplies right operand with the left operand c *= a is equivalent to
Multiply AND and assign the result to left operand c=c*a
/= It divides left operand with the right operand and c /= a is equivalent to
Divide AND assign the result to left operand c=c/a
%= It takes modulus using two operands and assign c %= a is equivalent to
Modulus AND the result to left operand c=c%a
**= Performs exponential power calculation on c **= a is equivalent to
Exponent AND operators and assign value to the left operand c = c ** a
//= It performs floor division on operators and c //= a is equivalent to
Floor Division assign value to the left operand c = c // a
Operators:
4) Logical Operator: The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then -
1) raw_input():
This function works in older version. It takes exactly what it typed from
the keyboard, convert it into string and then return it to the variable in which we
want to store it.
e.g: val = raw_input(“Enter any value:”)
print “Value is: “,val
o/p: Enter any value: 5 * 4
Value is: 5 * 4
Accepting Input:
2) input():
This function initially takes the input from the user and then evaluates
the expression, it means Python automatically identifies whether user entered a
string or a number or list. If the input provided is not correct then either syntax
error or exception is raised by Python.
e.g: val = input(“Enter any value:”)
print “Value is: “,val
o/p: Enter any value: 5 * 4
Value is: 20
Conditional Statements:
Conditional Statement in Python performs different computations or
actions depending on whether a specific condition evaluates to True or False.
Conditional statement are handled by if statements in Python.
In Python, if statement is used for decision
making. You need to determine which action to take
and which statements to execute if outcome is TRUE
or FALSE otherwise.
Python programming language provides
following types of conditional statements.
1) if statement
2) if … else statement
3) Nested if statement
Conditional Statements:
1) if statement:
It is similar to that of other languages. The if statement contains a
logical expression using which data is compared and a decision is made based
on the result of the comparison.
Syntax: if condition:
statement(s)
If the condition evaluates to TRUE, then the block of statement(s) inside
the if statement is executed. If condition expression evaluates to FALSE, then the
first set of code after the end of the if statement(s) is executed.
Ex 1: Ex 2: a = 10
no = 5 b=5
if no > 0: if a > b:
print “Positive Value” print “A greater than B”
o/p – Positive Value o/p- A greater than B
Conditional Statements:
2) If…else statement:
An else statement can be combined with an if statement.
An else statement contains the block of code that executes if the conditional
expression in the if statement resolves to FALSE value.
Syntax:
if condition:
statement(s)
else:
statement(s)
Conditional Statements:
Example 1: Example 2:
a = input("Enter first value:") a = input("Enter any number:")
b = input("Enter second value:") if a%2==0:
if a>b: print "Even Number"
print "A greater than B" else:
else: print "Odd Number"
print "B greater than A"
o/p – Enter any number: 18
o/p – Enter first value: 5 Even Number
Enter second value: 10
B greater than A Enter any number: 21
Odd Number
Conditional Statements:
3) Nested if statement:
There may be a situation when you want to check for another condition
after a condition resolves to true. In such a situation, you can use the
nested if construct.
In a nested if construct, you can have an if...elif...else construct inside
another if...elif...else construct.
Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else: statement(s)
else: statement(s)
Conditional Statements:
Example: O/P:
per = input("Enter Percentage:") Enter Percentage: 85
if per <=100: Distinction Class
print "Percentage is less than 100"
if per >= 70: Enter Percentage: 48
print "Distinction Class" Second Class
elif per >= 60:
print "First Class" Enter Percentage: 24
elif per >= 35: Fail
print "Second Class"
else:
print "Fail"
else:
print "Not valid Percentage"
Looping Statements:
In general, statements are executed sequentially: The first statement in
a function is executed first, followed by the second, and so on. There may be a
situation when you need to execute a block of code several number of times.
A loop statement allows us to
execute a statement or group of statements
multiple times.
Python programming language
provides following types of loops to handle
looping requirements.
1) while loop
2) for loop
3) nested loops
Looping Statements:
1) While loop:
A while loop statement in Python programming language repeatedly
executes a target statements as long as a given condition is true.
Syntax:
while expression:
statement(s)
O/P: O/P:
5 The sum is: 183
10
15
20
25
30
35
40
Looping Statements:
For loop Using range() function:
The range() function is used to generate the sequence of the numbers.
If we pass the range(10), it will generate the numbers from 0 to 9.
Syntax:
range(start, stop, step_size)
O/P:
e.g 2:
Enter the number 20
n = input("Enter the number ")
2 4 6 8 10 12 14 16 18
for i in range(1,11):
c = n*i
print(c)
A final note on loop nesting is that you can put any type of loop inside of
any other type of loop. For example a for loop can be inside a while loop or vice
versa.
Looping Statements:
e.g : O/P:
adj = ["red", "big", "tasty"] red apple
fruits = ["apple", "banana", "cherry"] red banana
for x in adj: red cherry
for y in fruits: big apple
print x, y big banana
big cherry
tasty apple
tasty banana
tasty cherry
Break Statements:
You might face a situation in which you need to exit a loop completely
when an external condition is triggered or there may also be a situation when you
want to skip a part of the loop and start next execution.
Python provides break and continue statements to handle such
situations and to have good control on your loop.
Break Statement: The break statement in Python terminates the current loop
and resumes execution at the next statement, just like the traditional break found
in C.
The most common use for break is when some external condition is
triggered requiring an exit from a loop. The break statement can be used in
both while and for loops.
Break Statements:
e.g. 1: e.g. 2:
for letter in 'Python': var = 1
if letter == 'h': while var < 10:
break print ‘Variable value :', var
print 'Current Letter :', letter if var == 3:
break
O/P: var = var + 1
Current Letter : P print "Good bye!"
Current Letter : y
Current Letter : t O/P:
Variable value : 1
Variable value : 2
Variable value : 3
Good bye!
Continue Statements:
The continue statement in Python returns the control to the beginning
of the loop. The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top of the loop.
The continue statement skips the remaining lines of code inside the loop and
start with the next iteration.
The continue statement can be used in both while and for loops.
e.g.1:
O/P:
i=1
1
while(i < 10):
2
if(i == 5):
3
continue
4
print(i)
i = i+1
Continue Statements:
e.g. 2: e.g. 3:
str = 'Python' fruit = ['Apple', 'Banana', 'Mango', 'Papaya']
for i in str: for i in fruit:
if i=='t': if i=='Banana':
continue continue
print i print i
O/P: O/P:
P Apple
y Mango
h Papaya
o
n