Anda di halaman 1dari 11

Lesson 2: Python Language Basics

Topics
1. What is Python Syntax?
2. Take care of Indentation
3. How to make Comment
4. Python Keywords
5. What is Variable and Value?
6. What are Python Data Types?
7. Operators in Python
8. Operator precedence in Python
9. Python Statement & Expressions
10. How to input value from Keyboard in Python?

1. What is Python Syntax?


The syntax of the Python programming language is the set of rules that tells programmers how a Python program will be
written by them and interpreted by the runtime system. Python syntax was designed to be a highly readable language and easy.
In this lesson we will see what the basic blocks of Python program are and how Python code is structured, we must know these
2 points before starting Python coding.

2. Take care of Indentation


One of the most remarkable difference between Python and other most common programming languages like C, C++, C#, Java
will be encounter programmers is that in Python indentation is very important and there are no braces to indicate blocks of
code for class and function definitions or flow control. There are no end/begin delimiters like {}.
Python uses whitespace to delimit program blocks or we can say grouping of statements are done on basis of their indentation.
Statements at same indentation are grouped together in a single block. It is recommended to use 4 spaces instead of tabs.
Because whitespace is significant, remember that spaces and tabs don't mix, so use only one or the other when indenting your
programs.
See the different version of Python Code using white space (1 white space is represented by 1 . (dot):
Version 1
Correct Forms
print ("Anne was here")
print ("again at work")
print ("having fun with Python")
if True:
....print "True"
else:
....print "False"

http://cbsecsnip.in

Wrong Forms
print ("Anne was here")
..print ("again at work")
print ("having fun with Python")
if True:
....print "Answer"
else:
...print "Answer"

Page 1 of 11

Code Example 1
# Note: Don't try to understand logic or different functions used. Just make sure you understood various blocks even if
they are without braces.
# Calculates average score of a class
# initialization phase
totalScore = 0
# sum of scores
numberScores = 0
# number of scores entered
# processing phase
score = input( "Enter score, (Enter -9 to end): " )
# get one score
score = int( score )
# convert string to an integer
while score != -9:
totalScore = totalScore + score
numberScores = numberScores + 1
score = input( "Enter score, (Enter -9 to end): " )
score = int( score )
# termination phase
if numberScores != 0: # division by zero would be a run-time error
average = float( totalScore ) / numberScores
print ("Class average is", average)
else:
print ("No scores were entered")
Statements in Python typically end with a new line. Python also allow the use of the line continuation character (\) to denote
that the line should continue. For example:
total = item_one + \
item_two + \
item_three
Significance of white space
Only the indentation level of the statements is significant (i.e. the whitespace at the very left of the statements). Everywhere
else, whitespace is not significant and can be used as programmers like. Blank lines can be inserted anywhere. Also, the exact
amount of indentation doesn't matter, but all statements within the block must be indented the same amount.

3. How to make Comment


Comments are text in your program that the Python interpreter ignores.Comments help other people understand how the
program works. Python has two ways to put comment in code -

Single-line Comment: # marks start of single line comment that must not be inside a string literal. All characters after the #
and up to the physical line end are part of the comment, and the Python interpreter ignores them. Example
def getline():
return sys.stdin.readline()
# Get one line and return it

Multi-line Comments: Comments can be break up into multiple lines by inserting a multi-line string with """ as the
delimiter one each end. Example

def getline():
return sys.stdin.readline()

http://cbsecsnip.in

"""this function
gets one line
and returns it"""

Page 2 of 11

4. Python Keywords
Keywords in Python are reserved words that cannot be used as ordinary identifiers. They must be spelled exacty as they are
written.
We can view the list of available keyword in Python by this way
>>> import keyword
>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with',
'yield']
Above list may change version to version of Python.
and
break
def
else
False (added in 3.x)
from
import
lambda
not
print (changed to a built-in function in 3.x)
True (added in 3.x)
with

as
class
del
except
finally
global
in
None (added in 3.x)
or
raise
try
yield

assert
continue
elif
exec (changed to a built-in function in 3.x)
for
if
is
nonlocal (added in 3.x)
pass
return
while

5. What is Variable and Value?


Computer programs consist of data and code. In order to make code able to be used for more than a single set of data,
computer programs use variables, or containers for data. These containers are technically called data structures because they
allow the data to be structured in different ways. Variables are reserved memory locations to store values. This means that
when variable is created some space in memory is allotted to a container for holding the value.
Points to be noted regarding variable

Variables in Python beginning in a letter or underscore but can be alphanumeric. Valid variable name can be
>>>bool = True
>>>name = "Craig"
>>>age = 26
>>>_pi = 3.14159
>>>Session2013_14=Python Programming
The operand to the left of the = operator is the name of the variable, and the operand to the right of the = operator is
the value stored in the variable.

Variable names are case sensitive.


Variables do not need to be declared. The declaration happens automatically when you assign a value to a variable
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved
memory.
Python allows you to assign a single value to several variables simultaneously.
Example 1 >>> a=b=c=100
Example 2 >>> a,b,c = 100,200,Vishal

http://cbsecsnip.in

Page 3 of 11

In example 2 two integer variables with values 100 and 200 are assigned to variables a and b, and one string variable with the
value "Vishal" is assigned to the variable c.
Therefore, by assigning different data types to variables, we can store integers, decimals, or characters in these variables.

6. Python Data Types

Python has a rich set of data types for variables:


Numeric Type: There are four distinct numeric types - plain integers, long integers, floating point numbers, and complex
numbers.
Type
Size
Example
integer
32 bits
>>> x = 5
>>> type(x)
<type 'int'>
long integer
>>> x = 187687654564658970978909869576453
>>> type(x)
<type 'long'>
float
64 bits
>>> x = 1.34763
>>> type(x)
<type 'float'>
complex
>>> x = 5 + 2j
>>> type(x)
<type 'complex'>
Sequence Types: strings, lists, tuples are 3 three commonly used data types which comes under sequence types.
Sequential data types contain multiple pieces of data, each of which is numbered, or indexed. Each piece of data inside a
sequence is called an element.
Sequential data types are that which can manipulate the whole sequence, chunks of the sequence, or individual
elements inside the sequence.

String: String is a data type representing textual data in computer programs. Strings in python can be created using single

quotes, double quotes and triple quotes. When we use triple quotes, strings can span several lines without using the escape
character. Example of different types of string formation is given below
>>> a="cbse cs n ip"
>>> a
'cbse cs n ip'
>>> b='cbse cs n ip'
>>> b
'cbse cs n ip'
>>> c="""name
of
web site is
cbse cs n ip
"""
>>> c
'name\nof\nweb site is\ncbse cs nip\n'

In Python facility of concatenating more than String is also present, we can concatenate strings by using + sign like this
>>> d="for Cbse students"
>>> c+d
#concatenating c and d using + sign
'name\nof\nweb site is\ncbse cs nip\nfor Cbse students
Special characters can be inserted by using the escape character \.
Some commonly used escape sequences are
\\ for a \ in string

http://cbsecsnip.in

Page 4 of 11

\' for ' in a string


\" for " in a string
\n for a newline
\r for carriage return
\t for tab
Example of escape sequence:
>>> s='Line containing \' and \\ in itself'
>>> s
"Line containing ' and \\ in itself"
In the next example, we will see what will happen if we do string multiplication
>>> a="xyz"
>>> a * 3
'xyzxyzxyz'
# string is repeating three times
Get the length of a string
>>> str="Get the length of this string"
>>> len(str)
29
Guess what will be the output of this code snippet?
>>> a="xyz"
>>> b="abc"
>>> str1=a+" "+b*3
>>> a+" "+b*3
>>> len(str1)
Output?????

List: A list is a mutable (can change) sequence data type, elements in a list can be added or removed due to its mutable feature.
List can contain mixed data types which means list elements don't have to be of the same type.
A list contains items separated by commas and enclosed within square brackets []. List elements are numbered internally
starting from 0. There can have nesting of lists one inside other
>>> l = [1,2,3,4,"abc",2.34,[10,11]]
>>> l[0]
1
>>> l[4]
'abc'
>>> l[6]
[10, 11]
>>> l[6][0]
10
Add element in an existing list
>>> l.append('Vishal')
>>> l
[1, 2, 3, 4, 'abc', 2.34, [10, 11], 'Vishal']
Remove element from list
>>> del l[0]
>>> l
[2, 3, 4, 'abc', 2.34, [10, 11], 'Vishal']
Slicing elements of list

http://cbsecsnip.in

Page 5 of 11

>>>l[1:4]
[3,4,'abc']

Tuple: A tuple in Python is much like a list except that it is immutable (unchangeable) once created. Tuple can be index, slice
and concatenate, but one cannot append or alter the values of the tuple after it has been initialized. Tuples are created using
round brackets.
>>> t = (1,2,3,4,'abc',2.34,(10,11))
>>> t[0]
1
>>> t[4]
'abc'
>>> t[6]
(10,11)
Mapping Type: A mapping object maps hashable values to arbitrary objects. Mappings are mutable objects. There is
currently only one standard mapping type, the dictionary.

Dictionary: Dictionary comes under Mapping data type. In a dictionary, we have an 'index' of words and for each of them a
definition. The word is called a 'key', and the definition a 'value'. Dictionary is the Python term for an associative array. It is like
a list, a series of values in two dimensions. Dictionary gives one a way of accessing the values by a key, and keys are unique. A
dictionary is mutable but does not have any defined sequence. Key can be any integer or string and Value can be any item.
For initializing a dictionary, we have to put the sets of keys and values in curly braces. Each key-value pair is separated from the
others by a comma and for each pair, the key and value are separated by a colon.
Syntax for creating dictionary-> >>> d = {'key1':'value1','key2':'value2',.... }
#Create dictionary
>>> phonebook={'Andrew Parson':8806336, 'Emily Everett':6784346, 'Peter
Power':7658344, 'Lewis Lame':1122345}
#Show dictionary phonebook
>>>phonebook
{'Andrew Parson':8806336, 'Emily Everett':6784346, 'Peter Power':7658344, 'Lewis
Lame':1122345}
#Display keys and its respective values of all the items from dictionary
>>> phonebook.items()
[('Emily Everett', 6784346), ('Andrew Parson', 8806336), ('Lewis Lame', 1122345),
('Peter Power', 7658344)]
#Display the key of value from dictionary
>>> phonebook.keys()
['Emily Everett', 'Andrew Parson', 'Lewis Lame', 'Peter Power']
#Display the value of lists from dictionary
>>> phonebook.values()
[6784346, 8806336, 1122345, 7658344]
#Display the value of a specific key
>>> phonebook.pop('Andrew Parson')
8806336
#Add a new numbers to the phonebook
>>> phonebook['Gingerbread Man'] = 1234567
>>> phonebook

http://cbsecsnip.in

Page 6 of 11

{'Andrew Parson':8806336, 'Emily Everett':6784346, 'Peter Power':7658344, 'Lewis


Lame':1122345, 'Gingerbread Man': 1234567}
#Remove item from dictionary
>>> del phonebook['Peter Power']
>>> phonebook
{'Andrew Parson':8806336, 'Emily Everett': 6784346, 'Lewis Lame': 1122345,
'Gingerbread Man': 1234567}

Sets: A set stores multiple items, which can be of different types, but each item in a set must be unique. Use of sets is to find
unions, intersections, differences, and so on. Unlike sequence objects such as lists and tuples, in which each element is
indexed. Basic uses include membership testing and eliminating duplicate entries.
Operations on sets
#Creating set
>>> s1=set(['a', 'i', 'e', 'u', 'o'])
>>> s2=set(['m', 'w', 'd', 'i', 't', 'o'])
>>> print
set(['a',
>>> print
set(['d',

s1
'i', 'e', 'u', 'o'])
s2
'i', 'm', 'o', 't', 'w'])3

#Add single member in set


>>> s1.add(32)
>>> print s1
set(['a', 32, 'e', 'i', 'o', 'u'])
#Add group of members in set
>>> s1.update([26, 9, 14])
>>> print s1
set(['a', 32, 'e', 'i', 9, 'o', 'u', 14, 26])
#Different types of Membership Testing
>>> 32 in s1
True
>>> 'o' in s1
True
>>> 35 not in s1
True
>>> 32 not in s1
False
>>> 'w' in s1
False
#Intersection Operation
>>> s1 & s2
OR
set(['i', 'o'])

>>> s1.intersection(s2)

#Union Operation
>>> s1 | s2
OR
>>> s1.union(s2)
set(['a', 'e', 'd', 'i', 'm', 'o', 'u', 't', 'w'])
#Difference Operation
>>> s1 - s2
OR

http://cbsecsnip.in

>>> s1.difference(s2)

Page 7 of 11

set(['a', 'u', 'e'])


#Symmetric Difference
>>>s1 ^ s2
OR
>>> s1.symmetric_difference(s2)
set(['a', 'e', 'd', 'w', 'u', 'm', 't'])

None: Python has a special value called None. It is generally used to represent a null value.

#Checking whether x contain any value or not


>>>x=None
# initializing x with None (nothing/null)
>>> if x:
# checking if x contain any value then this will return TRUE
print("X is having Value")
#if TRUE then this line will display
else:
print("X is empty")
#if FALSE then this line will display
X is empty

#Output

>>> x=10
# initializing x with 10
>>> if x:
# checking if x contain any value then this will return TRUE
print("X is having Value")
#if TRUE then this line will display
else:
print("X is empty")
#if FALSE then this line will display
X is having Value

#Output

7. Operators in Python
An operator is a special symbol which indicates a certain process to carry out. The operators are used to process data which we
technically termed as operand.
An operator may have one or two operands. An operand is one of the inputs (arguments) of an operator. Those operators that
work with only one operand are called unary operators. Those who work with two operands are called binary operators.
In Python programming language, we have several types of operators:

Arithmetic: The math symbols we're all familiar with as well as some less-well known ones. Python understands a variety of
math symbols. Table shown below contain the different types of operators with examples
Assume variable x holds 10 and variable y holds 20 then:
Operator

+
*
/
%
**

Description
Addition
Subtraction
Multiplication
Division
Modulus
Exponent

Example

x + x will give 30
x y will give -10
x * y will give 200
y / x will give 2
y % x will give 0
x**y will give 10 to the power 20 output -> 100000000000000000000L

Relational: A relational operator relates the values between two operands and gives either True or False as the result after

evaluation.

The following table shows a list of comparison operators.


Operator
<

Description
less than

http://cbsecsnip.in

Example
x < y will return True

Page 8 of 11

<=
==
>
>=
!=
<>

less than or equal


equal
greater than
greater than or equal
not equal
not equal

x <= y will return True


x == y will return False
x > y will return False
x >= y will return False
x != y will return True
x <> y will return True

Logical or Boolean: Python has three logical operators and, or and not. These are also called as Boolean operators

Python tests an expression with and and or operators from left to right and returns the last value tested. With Boolean
operators we perform logical operations. These are most often used with if and while keywords.

The logical and operator evaluates to True only if both operands are True. See the example how and operator evaluates
the expression:
>>> True and True
True
>>> True and False
False
>>> False and True
False
>>> False and False
False
The logical or operator evaluates to True, if either of the operands is True. If one of the sides of the operator is True, the
outcome of the operation is True. See the example how or operator evaluates the expression:
>>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
Logical not Operator also called as the negation operator. Use to reverses the logical state of its operand. If a condition is
true then Logical NOT operator will make false.
>>> x=4
>>> y=3
>>> not x<y
True
>>> not x>y
False

Assignment: The basic assignment operator is equal (=), which assigns the value of its right operand to its left operand. That is,
x = y assigns the value of y to x. The other assignment operators are usually shorthand for standard operations, as shown in the
following table.
Operator

Description

Example

Simple assignment operator, Assigns values from right side operands to left side operand

= will assign value of a+


b into c

+=

This adds right operand to the left operand and assign the result to left operand

c += a is same as c = c + a

-=

This subtracts right operand from the left operand and assign the result to left operand

c -= a is same as c = c - a

*=

This multiplies right operand with the left operand and assign the result to left operand

c *= a is same as c = c * a

/=

This divides left operand with the right operand and assign the result to left operand

c /= a is same as c = c / a

http://cbsecsnip.in

Page 9 of 11

%=

This takes modulus using two operands and assign the result to left operand

c %= a is same as c = c %
a

**=

This performs exponential (power) calculation on operators and assign value to the left
operand

c **= a is same as c = c
** a

8. Operator precedence in Python


Operator Precedence determines in which order operations are evaluated. You can control this with parentheses (). Consider
this:
2

+ 10 * 10 = 120 in normal math. But 2 + (10*10) = 102 because the parentheses gives precedence to the equation
10*10.
Highest precedence
1. ( )
(anything in brackets is done first)
2. **
(exponentiation)
3. -x, +x
(unary plus and minus)
4. *, /, %
(binary arithmetical operators)
5. +, (binary plus and minus)
6. relational operators: <, >, <=, >=, !=, ==
7. logical not
8. logical and
9. logical or
Lowest precedence

9. Python Statement & Expressions


Statement: A statement is an instruction that the Python interpreter can execute. We have only seen the assignment and print
statement so far. Some other kinds of statements that well see shortly are while statements, for statements, if statements, and
import statements.
Expression: An expression is a combination of values, variables, operators, and calls to functions. Expressions need to be

evaluated. If you ask Python to print an expression, the interpreter evaluates the expression and displays the result. If you type
an expression in interactive mode, the interpreter evaluates it and displays the result.

The evaluation of an expression produces a value, which is why expressions can appear on the right hand side of assignment
statements. A value all by itself is a simple expression.
>>> message = "What's up, Doc?"
>>> message
"What's up, Doc?"

#Assignment Statement, both message and "What's up, Doc?" are expressions

>>> print message


What's up, Doc?

#Print Statement, message is expressions and print is a statement

When the Python shell displays the value of an expression, it uses the same format you would use to enter a value. In the
case of strings, that means that it includes the quotation marks. But the print statement prints the value of the
expression, which in this case the contents of the string.

10. How to input value from keyboard in Python


Now the time came when we like to take some values from keyboard and based on those values we will do out operation, till
now we were playing with constant (fixed) values like:

http://cbsecsnip.in

Page 10 of 11

>>> 25+25
Or
>>> n1=25
>>> n2=25
>>> n1+n2
Here we problem is whenever we want to do addition of two numbers we have to make changes in our code, this is not Good
Programming. Our program should have capability to accept different values via keyboard as user wants and sum up those
numbers and for this we should not modify our code.
To accomplish the above mentioned task Python have two built-in functions for getting keyboard input: input() and
raw_input() each of these functions allows a prompt to be given to the function between the parentheses.
>>> n = raw_input("Please enter a value: ")
Please enter your name: CBSE CS N IP
>>> n
'CBSE CS N IP'
>>> n = input("Please enter a value: ")
Please enter your name: CBSE CS N IP
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
n = input("Please enter your name: ")
File "<string>", line 1
CBSE CS N IP
^
SyntaxError: unexpected EOF while parsing

# Error Raised because input() expect correct syntax for string

>>> n = input("Please enter a value: ")


Please enter your name: "CBSE CS N IP"
>>> n
'CBSE CS N IP'
Difference between input() and raw_input()
input()
Converts the user input to the right matching python
type (int, str, list, tuple, dict etc.,)
For instance in the statement below:
a = input('Enter a value: ')
print type(a)
if user entered 1 then it is int
if user entered 'Python' then it is str
if user entered [1,2,3] then it is dict
Use when you write program quickly for yourself or
for expert users since you would not need to any type
conversion.
Removed in Python 3
>>> n = input("Please enter a value: ")
Please enter a value: 23
>>> n
23
# value returned as int

raw_input()
Converts the user input always to string.
For instance in the statement below
a = raw_input('Enter a value: ')
print type(a)
Regardless of value entered by the type is always
string
Use when you write program for non expert users
since you can handle exceptions when
converting from string to your expected type.
Renamed as input in Python 3
>>> n = raw_input("Please enter a value: ")
Please enter a value: 23
>>> n
'23'
# value returned as str

Lesson 3 -> Functions in Python Built-In Functions and User Defined Function.
http://cbsecsnip.in

Page 11 of 11