PYTHON PROGRAMMING (1)
PYTHON PROGRAMMING (1)
Python Introduction
• An interpreted , interactive, dynamically typed, object-
oriented ,cross platform, high level and open source
programming language.
• Created in early 90's by Guido von Rossum at Stichting
Mathematisch Centrum in the Netherlands.
• The name comes from the Monty Python .
• There is a big community of Python programmers, with
conferences and magazines:
http://pycon.org/
• Web site: www.python.org.
• Useful as a scripting language
• script: A small program meant for one-time use
Targeted towards small to medium sized projects.
Used by:
if import in is
yield
• Printing all the keywords with the help of
kwlist
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print(keyword.kwlist)
Python Character Set
• A character set is a set of valid characters
acceptable by a programming language in
scripting. In this case, we are talking about the
Python programming language. So, the Python
character set is a valid set of characters
recognized by the Python language. These are
the characters we can use during writing a
script in Python. Python supports all ASCII /
Unicode characters that include:
• Alphabets: All capital (A-Z) and small (a-z)
alphabets.
• Digits: All digits 0-9.
• Special Symbols: Python supports all kind of
special symbols like, ” ‘ l ; : ! ~ @ # $ % ^ ` & * ( ) _
+–={}[]\.
• White Spaces: White spaces like tab space, blank
space, newline, and carriage return.
• Other: All ASCII and UNICODE characters are
supported by Python that constitutes the Python
character set.
Identifiers in Python
• An identifier is a name given to entities like class, functions,
variables, etc. It helps to differentiate one entity from
another.
Rules for writing identifiers
• Identifiers can be a combination of letters in lowercase (a
to z) or uppercase (A to Z) or digits (0 to 9) or an
underscore _. Names
like myClass, var_1 and print_this_to_screen, all are valid
example.
• An identifier cannot start with a digit. 1variable is invalid,
but variable1 is a valid name.
• Keywords cannot be used as identifiers.
• We cannot use special symbols like !, @, #, $, % etc. in
our identifier.
• An identifier can be of any length.
• Python is a case-sensitive language. This
means, Variable and variable are not the same.
• Always give the identifiers a name that makes sense.
While c = 10 is a valid name, writing count = 10 would
make more sense, and it would be easier to figure out
what it represents when you look at your code after a
long gap.
• Multiple words can be separated using an underscore,
like this_is_a_long_variable
Python Statement
• Instructions that a Python interpreter can execute are called
statements. For example, a = 1 is an assignment
statement. if statement, for statement, while statement, etc. are
other kinds of statements which will be discussed later.
Multi-line statement
• In Python, the end of a statement is marked by a newline character.
But we can make a statement extend over multiple lines with the
line continuation character (\). For example:
• a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation.
• In Python, line continuation is implied inside
parentheses ( ), brackets [ ], and braces { }. For
instance, we can implement the above multi-line
statement as:
• a = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9)
• Here, the surrounding parentheses ( ) do the line
continuation implicitly. Same is the case with [ ] and { }.
For example:
• colors = ['red', 'blue', 'green']We can also put multiple
statements in a single line using semicolons, as follows:
• a = 1; b = 2; c = 3
Python Indentation
• Most of the programming languages like C, C++,
and Java use braces { } to define a block of code.
Python, however, uses indentation.
• A code block (body of a function, loop, etc.) starts
with indentation and ends with the first uninde
nted line. The amount of indentation is up to you,
but it must be consistent throughout that block.
• Generally, four whitespaces are used for
indentation and are preferred over tabs.
• Python Comments
• Comments are very important while writing a program.
They describe what is going on inside a program, so
that a person looking at the source code does not have
a hard time figuring it out.
• You might forget the key details of the program you
just wrote in a month's time. So taking the time to
explain these concepts in the form of comments is
always fruitful.
• In Python, we use the hash (#) symbol to start writing a
comment.
• It extends up to the newline character. Comments are
for programmers to better understand a program.
Python Interpreter ignores comments.
• Multiline Comments
We can use “”” for the multi line comments.
Python Built-in Data Types
The data types defined in Python are given
below.
• Numbers
• Sequence Type
• Boolean
• Set
• Dictionary
• Number stores numeric values. The integer,
float, and complex values belong to a Python
Numbers data-type. Python provides
the type() function to know the data-type of
the variable. Similarly,
the isinstance() function is used to check an
object belongs to a particular class.
• Python creates Number objects when a
number is assigned to a variable.
a=5
print("The type of a", type(a))
The type of a <class 'int'>
b = 40.5
print("The type of b", type(b))
The type of b <class 'float'>
c = 1+3j
print("The type of c", type(c))
print(" c is a complex number", isinstance(1+3j,complex))
#isinstance(object,type)
The type of c <class 'complex'>
c is complex number: True
3 types of Numeric data
• Int - Integer value can be any length such as
integers 10, 2, 29, -20, -150 etc. Python has no
restriction on the length of an integer. Its value
belongs to int
• Float - Float is used to store floating-point
numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto 15 decimal points.
• complex - A complex number contains an
ordered pair, i.e., x + iy where x and y denote the
real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
Sequence Type
• Creating String
• Strings in Python can be created using single
quotes or double quotes or even triple quotes.
Accessing elements of String
• In Python, individual characters of a String can
be accessed by using the method of Indexing.
indexing starts with 0 index, first element will
store at oth position Indexing allows negative
address references to access characters from
the back of the String, e.g. -1 refers to the last
character, -2 refers to the second last
character and so on.
2) List
• Lists are just like the arrays, declared in other
languages which is a ordered collection of
data. It is very flexible as the items in a list do
not need to be of the same type.
Creating List
• Lists in Python can be created by just placing
the sequence inside the square brackets[].
1-List = [‘hellothere']
print("\nList with the use of String: ")
print(List)
o/p-List with the use of String: [‘hellothere’]
Creating Tuple
• In Python, tuples are created by placing a sequence of values
separated by ‘comma’ with or without the use of parentheses for
grouping of the data sequence. Tuples can contain any number of
elements and of any datatype (like strings, integers, list, etc.).
• Note: Tuples can also be created with a single element, but it is a
bit tricky. Having one element in the parentheses is not sufficient,
there must be a trailing ‘comma’ to make it a tuple.
• Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
Initial empty Tuple: ()
- Subtraction Subtracts right hand operand from left hand operand. a – b = -20
% Modulus Divides left hand operand by right hand operand and returns remainder a%b=0
** Exponent Performs exponential (power) calculation on operators a**b =30 to the power 10
// Floor Division - The division of operands where the result is the quotient in 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
which the digits after the decimal point are removed. But if one of the
operands is negative, the result is floored, i.e., rounded away from zero
(towards negative infinity) −
Comparison Operators
Operator Description Example
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true. This is similar to != operator.
becomes true.
> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, then condition becomes true.
Assignment Operators
= Assigns values from right side operands to left side operand
c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left
operand
c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result
to left operand
c -= a is equivalent to c = c - a
*= Multiply AND It multiplies right operand with the left operand and assign the result
to left operand
c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to
left operand
c /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left
operand
c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign
value to the left operand
c **= a is equivalent to c = c ** a
//= Floor Division It performs floor division on operators and assign value to the left
operand
c //= a is equivalent to c = c // a
Bitwise Operators
Operator Description Example
a=60 b=13
~ Binary Ones
Complement (~a ) = -61 (means 1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form due to a signed binary
number.
<< Binary Left The left operands value is moved left by the
Shift number of bits specified by the right operand.
a << 2 = 240 (means 1111 0000)
>> Binary Right The left operands value is moved right by the
Shift number of bits specified by the right operand.
a >> 2 = 15 (means 0000 1111)
Logical Operators
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)
3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction
5 >> <<
Right and left bitwise shift
6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators