python Course
Features of Python

● High Level
● Object Oriented
● Scalable:
● Extensible
● Portable
● Easy to Learn
● Easy to Read
● Easy to Maintain
● Robust
● Effective as a Rapid Prototyping Tool
● A Memory Manager
● Interpreted and (Byte-) Compiled
Program Output, the print Statement:
● In some languages, such as C, displaying to the screen is accomplished with a function,
e.g., printf(), while with Python and most interpreted and scripting languages, it is a
statement.
● Many shell script languages use an echo command for program output.
print Statement :
>>> myString = 'AIMLDS SECSIOT '
>>> print myString
SECSIOT
>>> myString
'AIMLDS SECSIOT '
The underscore (_) also has special meaning in the interactive interpreter: the last evaluated
expression. So after the code above has executed, _ will contain the string:
>>> _
SECSIOT
● Python's print statement, paired with the string format operator (%), supports string
substitution, much like the printf() function in C:
>>> print ("%s is number %d!" % ("Python", 1) )
Python is number 1!
Input Statement:
user =input('Enter login name: ')
Enter login name: shiva
print("your login is :",user)
your login is : Shiva
num =input('Enter number: ')
Enter number: 1024
print("Doubling your number: %d" % (int(num) * 2))
Doubling your number: 2048
The int() function converts the string num to an integer so that the mathematical operation
can be performed
>>> input
<built-in function input>
Comments:
The hash or pound ( # ) sign signals that a comment begins from the # and continues until the
end of the line.
Single line comment :
>>> # one comment
>>> print ('Hello World!') # another comment
Hello World!
Multi line comments :
We may use hashtags (#) multiple times to construct multiline comment
# This
# Is
# Comment
We can observe that on running this code, there will be no output; thus, we utilize the strings
inside triple quotes(""") as multi-line comments.
Python Docstring :
The strings enclosed in triple quotes that come immediately after the defined function are
called Python docstring. It's designed to link documentation developed for Python modules,
methods, classes, and functions together. It's placed just beneath the function, module, or
class to explain what they perform. The docstring is then readily accessible in Python using
the __doc__ attribute.
Code
1. # Code to show how we use docstrings in Python
2.
3. def add(x, y):
4. """This function adds the values of x and y"""
5. return x + y
6.
7. # Displaying the docstring of the add function
8. print( add.__doc__ )
Output:
This function adds the values of x and y
def foo():
"This is a doc string."
return True
Features Of Python Programming :
1) A simple language which is easier to learn Python has a very simple and elegant syntax. It's much easier to
read and write Python programs compared to other languages like: C++, Java, C#.
2. Versatile Python supports development of a wide range of applications ranging from simple
text processing to WWW browser to games.
3. Free and open-source Python is an open source software. Therefore, anyone can freely distribute
it, read the source code, edit it, and even use the code to write new programs.
4. Portability You can move Python programs from one platform to another, and run it without
any changes. It runs seamlessly on almost all platforms including Windows, Mac OS X and Linux.
5. Extensible and Embeddable Suppose an application requires high performance. You can easily
combine pieces of C/C++ or other languages with Python code. This will give your application high
performance as well as scripting capabilities which other languages may not provide out of the box.
6. A high-level, interpreted language Unlike C/C++, you don't have to worry about difficult tasks like
memory management, garbage collection and so on. Likewise, when you run Python code, it automatically
converts your code to the language your computer understands. You don't need to worry about any lower- level
operations.
7. Large standard libraries to solve common tasks Python has a number of standard libraries which
makes life of a programmer much easier since you don't have to write all the code yourself.
8. Object-oriented Everything in Python is an object. Object oriented programming (OOP) helps you
solve a complex problem very easily With OOP, you are able to divide these complex problems into smaller
sets by creating objects.
Applications of Python
Python is a high level general purpose programming language that is used to develop a wide range of
applications including image processing, text processing, web, and enterprise level applications using
scientific and numeric data from network. Some of the key applications of python includes:
❖ In operations of Google search engine, youtube, etc.
❖ Bit Torrent peer to peer file sharing is written using Python
❖ Intel, Cisco, HP, IBM, etc use Python for hardware testing.
❖ Maya provides a Python scripting API
❖ i–Robot uses Python to develop commercial Robot.
❖ NASA and others use Python for their scientific programming task.
❖ Python is used as an Embedded scripting language.
❖ GUI-based Desktop applications
❖ Games: Python support development of games.
❖ Business applications
❖ Operating systems
❖ Python is used for Network programming.
Interpreter : An interpreter is a program that converts program written in high-level language(Source
code) into machine code understood by the computer. Interpreter executes one statement at a time.
scripting language: A scripting language is a programming language designed for integrating and
communicating with other programming languages. Some of the most widely used scripting languages are
JavaScript, VBScript, PHP, Perl, Python, Ruby, ASP and Tcl. Since a scripting language is normally used
in conjunction with another programming language, they are often found alongside HTML, Java or C++.
First Python Program:
Example: To print a message on the screen
>>> print (“Hello World! ! !”)
Hello World.
Data Types:
Variables can hold values of different types called data types. The standard data types supported by Python
includes
1) Numbers: Number refers Numerical Values. This data type is immutable i.e. its value cannot be
changed. These are of three different types:
a) Integers
b) Float/floating point
c) Complex
a) Integers: Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers
are called long integers. For example, 56958558585855L is a long integer. Note that a long integer must have ‘l’
or ‘L’ as the suffix.
Integers contain Boolean Type which is a unique data type, consisting of two constants, True & False. A Boolean
True value is Non-Zero, Non-Null and Non-empty.
Example
>>> flag = True
>>> type(flag)
<type 'bool'>
b) Floating point numbers: Numbers with fractions or decimal point are called floating point numbers.
Example
y= 12.36
c) Complex Numbers: Numbers of a+bi form are complex numbers.
2) None: This is special data type with single value. It is used to signify the absence of value/false in
a situation. It is represented by None.
3) Sequence:
A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and
non mutable data types. Three types of sequence data type available in Python are Strings, Lists & Tuples.
i) Strings: String is an ordered sequence of letters/characters. String is also defined as a group or set of
characters. They are enclosed in single quotes (‘ ’) or double (“ ”). Strings are immutable data types.
Example
>>> a = 'Ram'
ii) List: List is data type available in python. It is a sequence in which elements are written as a list of
comma separated values between square brackets. List is mutable data type which means the value of its
elements can be changed.
Syntax: list_variable=[var1,var2, ]
Example
rgukt = *“spam”, 20.5,5]
iii) Tuples: Tuples is data type available in python. Tuples are sequence of elements separated by comma
enclosed in parenthesis. They are immutable data type.
Example
my_tuple = (4, 2, 5, 8)
4) Sets: Set is an unordered collection of values, of any type, with no duplicate entry. Sets are immutable.
Example
s = set ([1,2,34])
5) Mapping: This data type is unordered and mutable. A dictionary comes under Mappings.
Dictionary: Dictionary is a data type available in python which store values as a pair of key and value. Each key
is separated from its value by a colon (:), and consecutive items are separated by commas. The entire items in
a dictionary are enclosed in curly brackets {}. Dictionary keys must be of immutable type.
Example: d = {1:'a',2:'b',3:'c'}
Mutable and Immutable Variables
Variable: Variables are reserved memory locations that stores values. Variables play a very important role in
most programming languages, and Python is no exception. You can store any piece of information in a
variable. Variables are nothing but just parts of your computer’s memory where information is stored. To be
identified easily, each variable is given an appropriate name. Every variable is assigned a name which can be
used to refer to the value in the program.
A mutable variable is one whose value may change , whereas in an immutable variable the value cannot be
change.
Example: Initializing values to variables
val= “hello”
num=75
amt=12.65
print (val)
print (amt)
print (num)
Output:
“hello”
75
12.65
Multiple assignments :
Python allows you to assign a single value to several variables simultaneously. For
example: a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same memory
location.
You can also assign multiple objects to multiple variables. For example – Example:
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object
with the value "john" is assigned to the variable
Expression and Statements
An expression is a combination of values, variable and operators that represents a value.
Example:
sum=a+b (Expression)
a and b operands and + is operator.
Operators are the constructs that are used to manipulate the value of operands. Some basic operators include
+, -, *, /.
Operands are the values.
A Python statement is a unit of code that the Python interpreter can execute.
Example of statement are:
>>> x=5
>>> area=x**2 #assignment statement
>>>print x #print statement 5
>>>print area
25
>>> print x, area
525
Value:
In mathematics and computer programming, a value is data element that may be stored in a variable. The
value can be numeric (such as an integer, or a floating point number), or alphanumeric (such as a character, or
a string).
Example: 1, 2.4, “Hello”
Python Identifiers:
Identifier is the name given to entities like class, functions, variables etc. For naming identifier, there are some
basic rules that you must follow. These rules are
⮚ 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 (_).
⮚ Keywords cannot be used as identifiers.
⮚ An identifier cannot start with a digit. 1variable is invalid, but variable1 is valid.
⮚ Identifier names are case sensitive. For example myvar and myVar are not the same.
⮚ Punctuation characters such @,$,£ and % are not allowed within identifiers.
⮚ Does not include space character in the identifier name
Example:
Valid identifier names are: sum, _my_var, num1, r, var_33, first etc Invalid
identifier names are: 1num, my-var, %check, basic sal etc
Comments
Comments are the non-executable statements in a program. They are just added to describe the code of the
program. Comments make the program easily readable and understandable by the programmer as well as
other users who are seeing the code. The interpreter simply ignores the comments.
In python, a has sign (#) symbol writing as a comment.
Example
#This is a comment
#print out Hello
print('Hello')
#program ends here
Multi-line comments
If we have comments that extend multiple lines, We can use triple quotes, either ''' or """.
Example
"""This is also a
perfect example
of multi-line comments"""
Note: A program can have any number of comments.
Keywords in Python
Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any
other identifier. They are used to define the syntax and structure of the Python language. In Python, keywords
are case sensitive. There are 33 keywords in Python. All the keywords except True, False and None are in
lowercase and they must be written as it is.
Indentation:
White space at the beginning of the line is called indentation. These whitespaces or the indentation are very
important in python. Most of the programming languages like C, C++, Java use braces { } to define a block of
code. Python uses indentation.
Leading white space (spaces and taps) at the beginning of each statement, which is used to determine the
group of statement, is known as “indentation”.
Example
If A > B :
print “A is Big” # Block1
else:
print “B is Big” # Block2
In the above example, if statements are a type of code block. If the “if” expression evaluates to true, then
Block1 is executed, otherwise, it executes Block2. Obviously, blocks can have multiple lines. As long as they are
all indented with the same amount of spaces, they constitute one block.
Operators and Operands in Python
Operators: Operators are special symbols that are used to manipulate the value of operands. They are applied
on operand(s), which can be values or variables. Operators when applied on operands form an expression.
Operators are categorized as Arithmetic, Relational, Logical and Assignment.
Operands: Values and variables are known as operands.
Example:
result=a+b
(a, b operands and + is operator)
Python supports different types of operators which are as follows:
1) Arithmetic operators
2) Relational or Comparison operators
3) Logical Operators
4) Assignment Operators
5) Unary Operators
6) Bitwise Operators
7) Membership operators
8) Identity operators
Errors
An error is a term used to describe any issue that arises unexpectedly that cause a computer to not function
properly. There are three types of errors generally occur during running (execution) of a program. They are (i)
Syntax error; (ii) Logical error; and (iii) Runtime error.
(i) Syntax error: Every programming language has its own rules and regulations (syntax). If we overcome
the particular language rules and regulations, the syntax error will appear (i.e. an error of language resulting
from code that does not conform to the syntax of the programming language). It can be recognized during
compilation time.
Example
a = 0
while a < 10
a = a + 1
print a
In the above statement, the second line is not correct. Since the while statement does not end with “:”. This
will flash a syntax error.
(ii) Logical error: Programmer makes errors while writing program that is called “logical error‟. It is an
error in a program's source code that results in incorrect or unexpected result. It is a type of runtime error that
may simply produce the wrong output or may cause a program to crash while running. The logical error might
only be noticed during runtime, because it is often hidden in the source code and are typically harder to find
and debug.
a = 100
while a < 10:
a = a + 1
print a
In the above example, the while loop will not execute even a single time, because the initial value of “a” is 100.
(iii) Runtime error: A runtime error is an error that causes abnormal termination of program during
running time. In general, the dividend is not a constant but might be a number typed by you at runtime. In this
case, division by zero is illogical. Computers check for a "division by zero" error during program execution, so
that you can get a "division by zero" error message at runtime, which will stop your program abnormally. This
type of error is called runtime error.
Example
(a) A=10
B=0
print (A/B)
Comments
Post a Comment