0% found this document useful (0 votes)
25 views22 pages

1 Introduction

Uploaded by

Manglya Vasule
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views22 pages

1 Introduction

Uploaded by

Manglya Vasule
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Python | CCIT

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.

Rich Library Support


 The Python Standard Library is vary vast.
 Library available for NLP, multi-threading, databases, CGI, email, XML, HTML,
Image , Audio , Video Processing , cryptography, GUI, Networking and many
more.
 Additional libraries can be easily installed and are automatically configured.

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.

General Format of Python Program


Import statement
Global declaration
Statements
----------
---------

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

To print value store in variable and String


A="Python"
print("Welcome to",A)
>>>Welcome to Python
6
Python | CCIT

To print value store in variable


A="Ram"
B="Seeta"
print(A , B)
>>>Ram Seeta

To print separator String


A="Ram"
B="Seeta"
print(B,A,sep="->")
>>>Seeta->Ram

To print separator String


a="Shree"
b=420
c="Mumbai"
print(a,b,c,sep="\n")
>>>Shree
>>>420
>>>Mumbai

To print function end argument.

a="Shree"
b=420
c="Mumbai"
print(a,b)
print(c)
>>>Shree 420
>>>Mumbai

To print function end argument.


a="Shree"
b=420
c="Mumbai"
print(a,b,end=' ')
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.

Text Type String

Numbers Integer , Float, complex

Sequence Types List, Tuple ,Sets

Mapping Type Dictionary


Boolean Type Bool

Binary Types Bytes, Bytearray


8
Python | CCIT

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.

Python supports three different Number data types:

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

Prefix Description Base Example


0b or 0B Binary Number 2 0b0101 , 0b0011
0o or 0O Octal Number 7 0o134, 0o017
Nothing Decimal Number 10 12, 34 , -5
0x or 0X Hexadecimal Number 16 0x9ff , 0x1AC

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"""

Single and Double quotes


Single and double quotes are used for single line string.

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.

Operator Description Example


~ Inverts the bits in a number so that all the 0 bits become 1 ~4 => –5
bits and vice versa.
- Negates the original value so that positive becomes negative –(–4) => 4
and vice versa. –4 => –4
+ Is provided purely for the sake of completeness. This +4 => 4
operator returns the same value that you provide as input.

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.

Operator Description Example


+ Adds two values together 5 + 2 => 7
- Subtracts the right operand from the left operand 5 – 2 => 3
* Multiplies the right operand by the left operand 5 * 2 => 10
/ Divides the left operand by the right operand 5 / 2 => 2.5
% Divides the left operand by the right operand and returns 5 % 2 => 1
the remainder
** Calculates the exponential value of the right operand by the 5 ** 2 => 25
left operand
// Performs integer division, in which the left operand is 5 // 2 => 2
divided by the right operand and only the whole number is
returned (also called floor division)
12
Python | CCIT

Relational Operator
The relational operators compare one value to another and tell you when the
relationship you’ve provided is true.

Operator Description Example


== Determines whether two values are equal. 1 == 2 is False
!= Determines whether two values are not equal. 1 != 2 is True
> Verifies that the left operand value is greater than the right 1 > 2 is False
operand value.
< Verifies that the left operand value is less than the right 1 < 2 is True
operand value.
>= Verifies that the left operand value is greater than or equal 1 >= 2 is False
to the right operand value
<= Verifies that the left operand value is less than or equal to 1 <= 2 is True
the right operand value.

Logical Operator
The logical operators combine the true or false value of variables or
expressions so that you can determine their resultant truth value.

Operator Description Example


and Determines whether both operands are true. True and True is True
True and False is False
False and True is False
False and False is False
or Determines when one of two operands is true. True or True is True
True or False is True
False or True is True
False or False is False
not Negates the truth value of a single operand. A not True is False
true value becomes false and a false value not False is True
becomes true.

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.

Operator Description Example


= Assigns the value found in the right operand to A = 2 results in
the left operand. A containing 2
+= Adds the value found in the right operand to the a = 5
value found in the left operand and places the a +=2 results in
result in the left operand. a containing 7
-= Subtracts the value found in the right operand a = 5
from the value found in the left operand and a -=2 results in
places the result in the left operand. a containing 3
*= Multiplies the value found in the right operand by a = 5
the value found in the left operand and places the a *=2 results in
result in the left operand. a containing 10
/= Divides the value found in the left operand by the a = 5
value found in the right operand and places the a /=2 results in
result in the left operand. a containing 2.5
%= Divides the value found in the left operand by the a = 5
value found in the right operand and places the a %=2 results in
remainder in the left operand. a containing 2
**= Determines the exponential value found in the left a = 5
operand when raised to the power of the value a **=2 results in
found in the right operand and places the result in a containing 25
the left operand.
//= Divides the value found in the left operand by the a = 5
value found in the right operand and places the a //=2 results in
integer (whole number) result in the left operand. a containing 2

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.

Operator Description Example


& (and) Determines whether both individual bits within two 0b1100 & 0b0110
operators are true and sets the resulting bit to true = 0b0100
when they are.
| (or) Determines whether either of the individual bits 0b1100 | 0b0110
within two operators is true and sets the resulting bit = 0b1110
to true when one of them is.
^ Determines whether just one of the individual bits 0b1100 ^ 0b0110
(Exclusive or) within two operators is true and sets the resulting bit = 0b1010
to true when one is. When both bits are true or both
bits are false, the result is false.
~ Calculates the one’s complement value of a number. ~0b1100 = –0b1101
(One ~0b0110 = –0b0111
complement)
<< Shifts the bits in the left operand left by the value of 0b00110011 << 2
(Left shift) the right operand. All new bits are set to 0 and all bits = 0b11001100
that flow off the end are lost.
>> Shifts the bits in the left operand right by the value 0b00110011 >> 2
(Right shift) of the right operand. All new bits are set to 0 and all = 0b00001100
bits that flow off the end are lost.

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.

Operator Description Example


in Determines whether the value in the left "CCIT" in "Welcome to
operand appears in the sequence found in the CCIT"
=True
right operand.
not in Determines whether the value in the left "CCIT" not in "Welcome
operand is missing from the sequence found in to CCIT"
=False
the right operand.

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)

Program to read 2 numbers and find their sum


a=int(input("Enter a no "))
Enter a no 2
b=int(input("Enter a no "))
Enter a no 3
c=a+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 a radius of sphere and find its volume


r=int(input("Enter Radius ")) Enter Radius 5
V=4/3*3.14*r**3 Volume is 523.333334
print("Volume is ",V)

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)

WAP to read a number and find its last digit


a=int(input("Enter a Number")) Enter a Number 247
L=a%10 Last digit is 7
print("Last digit is ",L)

21
Python | CCIT

WAP to read 3 integers and find their mean.


a,b,c=input("Enter 3 Nos ").split() Enter 3 Nos 2 3 5
m=(int(a)+int(b)+int(c))/3 Result is 3.3333335
print("Result is ",m)

WAP to read 3 integers and find their mean.


a,b,c,d,e=input("Enter Marks for 5 subjects ").split()
a,b,c,d,e=int(a),int(b),int(c),int(d),int(e)
t=a+b+c+d+e
p=t*100/500
print("Total is",t)
print("Percentage is",p)

Enter Marks for 5 subjects 78 89 64 55 37


Total is 323
Percentage is 64.6

22

You might also like