1 Introduction
1 Introduction
1
Python | CCIT
Table of Contents
Introduction ........................................................................................................................................................... 3
Python ................................................................................................................................................................. 3
History ................................................................................................................................................................ 3
Features .............................................................................................................................................................. 4
General Format .................................................................................................................................................. 5
print .................................................................................................................................................................... 6
Data Types ............................................................................................................................................................. 8
Variables .............................................................................................................................................................. 8
Data types ........................................................................................................................................................... 8
Identifier ............................................................................................................................................................. 9
Keywords ............................................................................................................................................................ 9
Numbers ........................................................................................................................................................... 10
String ................................................................................................................................................................. 11
Boolean ............................................................................................................................................................. 11
Operators ............................................................................................................................................................. 12
Unary Operators ............................................................................................................................................... 12
Arithmetic Operators ....................................................................................................................................... 12
Relational Operators ........................................................................................................................................ 13
Logical Operators .............................................................................................................................................. 13
Assignment Operators ...................................................................................................................................... 14
Bitwise Operators ............................................................................................................................................. 15
Membership Operators .................................................................................................................................... 15
Operators Precedence ...................................................................................................................................... 16
Multiple Assignments ....................................................................................................................................... 17
Multiple Statement .......................................................................................................................................... 17
Mult-Line Statement ........................................................................................................................................ 17
Comments ........................................................................................................................................................ 18
Type Casting ..................................................................................................................................................... 19
read input ............................................................................................................................................................ 20
input function ................................................................................................................................................... 20
2
Python | CCIT
Introduction
Python
Python is an easy to learn, powerful programming language. It has efficient
high-level data structures and a simple but effective approach to object-
oriented programming.
Python elegant syntax and dynamic typing, together with its interpreted
nature, make it an ideal language for scripting and rapid application
development in many areas on most platforms.
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.
History
Python was conceived in the late 1980s by Guido
van Rossum at Centrum Wiskunde & Informatica
(CWI) in the Netherlands as a successor to ABC
programming language, which was inspired by
SETL, capable of exception handling and interfacing
with the Amoeba operating system. Its
implementation began in December 1989.
Python 2.0 was released on 16 October 2000, with
many major new features, including a cycle-detecting garbage collector and
support for Unicode.
Python 3.0 was released on 3 December 2008. It was a major revision of the
language that is not completely backward-compatible.
3
Python | CCIT
Features
Easy to Learn
Python is easy to learn as compared to other programming languages. Its
syntax is straightforward and much the same as the English language.
There is no use of the semicolon or curly-bracket, the indentation defines the
code block. It is the recommended programming language for beginners.
Open Source
Python is freely available for everyone. It is freely available on its official
website www.python.org.
It has a large community across the world that is dedicatedly working towards
make new python modules and functions. Anyone can contribute to the
Python community.
Platform Independent
Python code can written in one computer and executed in another.
This is possible because python source code is compiled into platform
independent byte code instead of platform dependent m/c code like C/C++.
Embeddable
The code of the other programming language can use in the Python source
code. We can use Python source code in another programming language as
well. It can embed other language into our code.
4
Python | CCIT
Interpreted
Python is an interpreted language.
Interpreter converts source code into byte code, which creates file with
extension .pyc that is executed with the help of PVM.
Import Statement
Python provides us many library classes and functions which are defined in
different modules.
If we want to use them then we have to import them by using import
statement.
5
Python | CCIT
Global Declaration
In this section we can define variables, functions, classes, Objects etc.
Elements defined in this section are accessible anywhere within the program.
Function print
The print() function prints the specified message to the screen, or other
standard output device.
The message can be a string, or any other object, the object will be converted
into a string before written to the screen.
Syntax:
print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False)
Arguments Discerption
objects Object to the printed. * indicates that there may be more than one object
separator Optional. objects are separated by separator. Default value: ' '
end Optional. end is printed at last Default is '\n'.
file Optional. Must be an object with write(string) method. If omitted it, sys.stdout will be
used which prints objects on the screen.
flush Optional. If True, the stream is forcibly flushed. Default value: False
For Example:
To print string
print("Welcome to Python")
>>>Welcome to Python
a="Shree"
b=420
c="Mumbai"
print(a,b)
print(c)
>>>Shree 420
>>>Mumbai
7
Python | CCIT
Variables
A variable is a location used to store data in the memory. It is helpful to think of
variables as a container that holds data which can be changed later throughout
programming. In Python, we don't need to specify the type of variable because
Python is a dynamically-typed. It automatically decides the datatype depending on
type of value.
Syntax:
Variable_Name = Value ;
For Example:
A=27
B=”CCIT”
C=True
Data Types
Variables can store data of different types, and different types can do different
things. Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of
these classes. There are various data types in Python. Some of the important types
are listed below.
Identifiers
Python Identifier is the name we give to identify a variable, function, class, module
or other object. That means whenever we want to give an entity a name, that’s
called identifier.
Rules:
Identifier must start with a letter or the underscore character
Next can be alphabets digits or underscores.
Variable names are case-sensitive.
Language keywords are not allowed.
No max limit.
Keywords
Python keywords are the words that are reserved. That means you can’t use them
as name of any entities like variables, classes and functions. So you might be thinking
what these keywords are for. They are for defining the syntax and structures of
Python language.
You should know there are 33 keywords in Python programming language. Also
keywords in Python is case sensitive. So they are to be written as it is. Here is a list
of all keywords in python programming.
false none in while assert
def import try as finally
if return and except nonlocal
raise true else lambda yield
del elif is with pass
break not class grom
for or continue global
9
Python | CCIT
Numbers
Data types that store numeric values are called Number. If you change the value of
a number data type, this results in a newly allocated object. So you can call numbers
immutable. We can simply create a number object by assigning some value to a
variable.
Int
Integer, is a whole number, positive or negative, without decimals, of
unlimited length (from python 3.0 ).
For ex:
1234, −24, 0, 99999999999999
0o177, 0x9ff, 0b101010
Float
Float, or "floating point number" is a number, positive or negative, containing
decimal point.
For ex:
1.23, 1.
3.14e-10, 4E210, 4.0e+210
Complex
Complex numbers are written with a "j" as the imaginary part.
For ex:
3+4j, 3.0+4.0j, 3J
10
Python | CCIT
String Datatype
The string is a sequence of characters. Python supports Unicode characters.
Generally, strings are represented by either single or double quotes. Python treats
single quotes the same as double quotes.
String Quotes Example
Single quotes 'Welcome to CCIT'
Double quotes "Welcome to CCIT"
Triple quotes '''Welcome to
CCIT Amravati'''
"""Welcome to
CCIT Amravati"""
Triple quotes
Triple quotes are used for multiline string.
Boolean Datatype
Booleans represent one of two values: True or False. In programming you often
need to know if an expression is True or False. You can evaluate any expression in
Python, and get one of two answers, True or False.
Boolean Datatype True and False
11
Python | CCIT
Operators
An operator accepts one or more inputs in the form of variables or expressions,
performs a task (such as comparison or addition), and then provides an output
consistent with that task.
Unary Operator
Unary operators require a single variable or expression as input. You often use
these operators as part of a decision-making process. For example, you might want
to find something that isn’t like something else.
Arithmetic Operator
Computers are known for their capability to perform complex math. However,
the complex tasks that computers perform are often based on much simpler math
tasks, such as addition.
Relational Operator
The relational operators compare one value to another and tell you when the
relationship you’ve provided is true.
Logical Operator
The logical operators combine the true or false value of variables or
expressions so that you can determine their resultant truth value.
13
Python | CCIT
Assignment Operator
The assignment operators place data within a variable. Python offers a number
of other interesting assignment operators that you can use. These other assignment
operators can perform mathematical tasks during the assignment process, which
makes it possible to combine assignment with a math operation.
14
Python | CCIT
Bitwise Operator
A bitwise operator would interact with each bit within the number in a specific
way. When working with a logical bitwise operator, a value of 0 counts as false and
a value of 1 counts as true.
Membership Operator
The membership operators detect the appearance of a value within a list or
sequence and then output the truth value of that appearance.
15
Python | CCIT
Operator precedence
When you create simple statements that contain just one operator, the order
of determining the output of that operator is also simple. However, when you start
working with multiple operators, it becomes necessary to determine which operator
to evaluate first.
Operator Description
() You use parentheses to group expressions and to override the
default precedence so
that you can force an operation of lower precedence (such as
addition) to take precedence over an operation of higher
precedence (such as multiplication).
** Exponentiation raises the value of the left operand to the power of
the right operand.
~ + - Unary operators interact with a single variable or expression.
* / % // Multiply, divide, modulo, and floor division.
+ - Addition and subtraction.
>> << Right and left bitwise shift.
& Bitwise AND.
^ | Bitwise exclusive OR and standard OR
<= < > >= Comparison operators.
== != Equality operators.
= %= /= Assignment operators.
//= -= +=
*= **=
In Membership operators.
not in
not or and Logical operators
16
Python | CCIT
Multiple Assignments
Python allows us to assign values to multiple variables in a single statement.
Syntax:
var1,var2,var3.. = value1,value2,value3..
For Example:
a,b,c = 2,3,4
Multi-Line Statements
Explicit line continuation
In Python, 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:
S=1+2+3+\
4+5+6+\
7+8+9
Implicit line continuation
This is explicit line continuation. In Python, line continuation is implied inside
parentheses ( ), brackets [ ] and braces { }.
For Example:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
17
Python | CCIT
Multiple Statements
We can put multiple statements in a single line using semicolons
a,b=5,7 ; a,b=b,a ; print(a,b)
Comments
In Python there are two types of comments- Single line comments and multiple lines
comments. Single line commenting is commonly used for a brief and quick comment
(or to debug a program, we will see it later). On the other hand we use the multiple
lines comments to note down something much more in details or to block out an
entire chunk of code.
Single line comments
Python single line comment starts with hashtag symbol with no white spaces
(#) and lasts till the end of the line.
For Example:
# This is a comment
# Print "Welcome !" to console
Multi-line comments
Python multi-line comment is a piece of text enclosed in a delimiter (""") on
each end of the comment. Quotes can be single or double
For Example:
'''This is a
multi-line comment.
We are printing welcome '''
18
Python | CCIT
Type Casting
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python provides type conversion
functions to directly convert one data type to another data type.
Functions
bin(value)
Converts an integer to a binary string
bool(value)
Converts an argument to a Boolean value
complex(value)
Returns a complex number constructed from arguments
float(value)
Returns a floating-point object constructed from a number or string
hex(value)
Converts an integer to a hexadecimal string
int(value)
Returns an integer object constructed from a number or string
oct(value)
Converts an integer to an octal string
ord(value)
Returns integer representation of a character
str(value)
Returns a string version of an object
19
Python | CCIT
Input Function
Python has an input function which lets you ask a user for some text input. You call
this function to tell the program to stop and wait for the user to key in the data. The
program will resume once the user presses the ENTER or RETURN key. This function
is use to read user input.
Note: input() returns the string that is given as user input. It will return entered value
as string.
Syntax:
Variable = input("Message");
Examples:
Program to read 2 numbers and find their sum
a=input("Enter a no ")
Enter a no 2
b=input("Enter a no ")
Enter a no 3
c=int(a)+int(b)
Result is 5
print("Result is ",c)
20
Python | CCIT
WAP to read a radius of circle and find its area and circumference
r=int(input("Enter Radius ")) Enter Radius 5
a=3.14*r**2 Area is 78.5
c=2*3.14*r Circumference is 31.4
print("Area is ",a)
print("Circumference is ",c)
WAP to read length and breadth of rectangle and find its area and perimeter.
l=float(input("Enter length ")) Enter length 5
b=float(input("Enter breadth ")) Enter breadth 10
a=l*b Area is 50.0
p=2*(l+b) Perimeter is 30.0
print("Area is ",a)
print("Perimeter is ",a)
21
Python | CCIT
22