Lab1 - Introduction To Python
Lab1 - Introduction To Python
Note:
• Maintain discipline during the lab.
• Listen and follow the instructions as they are given.
• Just raise hand if you have any problem.
• Completing all tasks of each lab is compulsory.
• Get your lab checked at the end of the session.
Introduction to Python
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to
be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has
fewer syntactical constructions than other languages.
Python is Interpreted: Python is processed at runtime by the interpreter. You do not need to compile your
program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly to
write your programs.
Python is a Beginner's Language: Python is a great language for the beginner-level programmers and
supports the development of a wide range of applications from simple text processing to WWW browsers to
games.
Python Program
If you are running new version of Python, then you would need to use print statement with parenthesis as in print
("Hello, Python!"). However, in Python version 2.4.x, you do not need the parenthesis. The above line produces the
following result:
Hello, Python!
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, all
the following are legal :
word = 'word'
sentence = "This is a sentence." paragraph = """This
is a paragraph. It is made up of multiple lines and
sentences."""
Comments in Python
A hash sign (#), that is not inside a string literal, begins a comment. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.
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
• Numbers
• String
• List
• Tuple
• Dictionary
Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.
var1 = 1 var2 = 10
Python 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 and working their way from -1 at the end.
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string print
(str[2:5]) # Prints characters starting from 3rd to 5th print
(str[2:]) # Prints string starting from 3rd character print (str
* 2) # Prints string two times print (str + "TEST") # Prints
concatenated string
This will produce the following result
Hello World!
H Llo
llo
World!
Hello World!Hello World!
Hello World!TEST
Python Lists
The list is the most versatile data type available in Python, which can be written as a list of commaseparated values
(items) between square brackets. Important thing about a list is that the items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square brackets.
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment
operator, and you can add to elements in a list with the append() method.
list = ['physics', 'chemistry', 1997, 2000] print
("Value available at index 2 : ", list[2])
list[2] = 2001
print ("New value available at index 2 : ", list[2])
Python 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 parenthesis. The main difference 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.
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple print
(tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times print (tuple +
tinytuple) # Prints concatenated tuple
The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed.
Similar case is possible with lists
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) list = [
'abcd', 786 , 2.23, 'john', 70.2 ] tuple[2] = 1000 #
Invalid syntax with tuple list[2] = 1000 # Valid syntax
with list
Python Dictionary
Python's dictionaries are kind of hash-table type. They consist of key-value pairs. A dictionary key can be almost any
Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).
dict = {}
dict['one'] = "This is one" dict[2]
= "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one'
key print (dict[2]) # Prints value for 2
key print (tinydict) # Prints complete
dictionary print (tinydict.keys()) # Prints all the
keys print (tinydict.values()) # Prints all the
values
IF Statement
The IF statement is similar to that of other languages. The if statement contains a logical expression using which the
data is compared and a decision is made based on the result of the comparison.
if expression:
statement(s)
var1 = 100
if var1:
print ("1 - Got a true expression value")
print (var1)
var2 = 0
if var2:
print ("2 - Got a true expression value")
print (var2)
print ("Good bye!")
IF...ELIF...ELSE Statements
An else statement can be combined with an if statement. An else statement contains a block of code that executes if
the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional
statement and there could be at the most only one else statement following if.
if expression:
statement(s)
else: statement(s)
amount = int(input("Enter amount: "))
if amount<1000:
discount = amount*0.05
print ("Discount",discount)
else:
discount = amount*0.10
print ("Discount",discount)
The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of
the conditions evaluates to TRUE.
Similar to the else, the elif statement is optional. However, unlike else, for which there can be at the most one
statement, there can be an arbitrary number of elif statements following an if.
if expression1:
statement(s) elif
expression2:
statement(s) elif
expression3:
statement(s) else:
statement(s)
amount = int(input("Enter amount: "))
if amount<1000:
discount = amount*0.05
print ("Discount",discount)
elif amount<5000:
discount = amount*0.10
print ("Discount",discount)
else:
discount = amount*0.15
print ("Discount",discount)
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n