0% found this document useful (0 votes)
45 views49 pages

Chapt 1

Uploaded by

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

Chapt 1

Uploaded by

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

Chapter 1

Introduction and syntax of Python Program

Unit outcomes :
1. Identify the given variables , keywords and
constants in python.
2. Use indentation, comments in the given
program.
3. Install the given python IDE and editor.
4. Develop the python program to display the
given text.
Introduction
• Python is a widely used general –purpose, high
level programming language.
• It combines the features of C and Java.
• It was initially designed by Guido van Rossum in
1991 and developed by Python Software
Foundation.
• It was mainly developed for emphasis on code
readability, and its syntax allows programmers
to express concepts in fewer lines of code.
Features of Python
1) Simple and easy to learn
2) Freeware and open source
3) High level programming language
4) Object Oriented
5) Interpreted
6) Platform independent
7) Portability
8) Dynamically Typed
Simple and easy to learn
• Python is a simple programming language.
• When we read Python program,we can feel like
reading english statements.
• The syntaxes are very simple and only 30+
kerywords are available.
• When compared with other languages, we can
write programs with very less number of lines.
Hence more readability and simplicity.
• We can reduce development and cost of the
project.
Freeware and Open Source
• We can use Python software without any
licence and it is freeware.
• Its source code is open, so that we can
customize based on our requirement. Eg:
Jython is customized version of Python to
work with Java Applications.
High level programming language
• Python is high level programming language
and hence it is programmer friendly language.
• Being a programmer we are not required to
concentrate low level activities like memory
management and security etc..
Object Oriented
• Python supports Object-Oriented style or
technique of programming that encapsulates
code within classes and objects.
Interpreted
• Python is an interpreted language i.e. interpreter
executes the code line by line at a time. This makes
debugging easy and thus suitable for beginners.
• Python compiler translates the python program
into an intermediate code called byte code. This
byte code is then executed by PVM.
• Inside PVM an interpreter converts the byte code
instructions into machine code so that processor
will understand and run that machine code to
produce results.
Platform independent
• Like Java programs, Python programs are
also platform independent.
• Once we write a Python program, it can run
on any platform without rewriting once again.
• Python uses PVM to convert python code to
machine understandable code.
Portability
• Python programs are portable. i.e. we can
migrate from one platform to another
platform very easily.
• Python programs will provide same results on
any platform.
Dynamically Typed
• In Python we are not required to declare type for
variables.
• Whenever we are assigning the value, based on
value, type will be allocated automatically.
• Hence Python is considered as dynamically typed
language.
• But Java, C etc are Statically Typed Languages
because we have to provide type at the beginning
only.
• This dynamic typing nature will provide more
flexibility to the programmer.
Python building blocks
1) Identifiers
2) Keywords
3) Indentation
4) Variables
5) Comments
Identifiers
• A Python identifier is a name used to identify a variable, function, class,
module or other object.
• An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $, and %
within identifiers.
• Python is a case sensitive programming language.
• Naming conventions for Python identifiers −
1) Class names start with an uppercase letter. All other identifiers start
with a lowercase letter.
2) Starting an identifier with a single leading underscore indicates that the
identifier is private.
3) Starting an identifier with two leading underscores indicates a strongly
private identifier.
4) If the identifier also ends with two trailing underscores, the identifier is
a language-defined special name.
Keywords

The following list shows the Python keywords. These are


reserved words and you cannot use them as constant or
variable or any other identifier names. All the Python
keywords contain lowercase letters only.
and exec not
assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
Indentation
• Most of the programming languages like C, C++, Java use braces { } to define a block
of code. Python uses indentation.
• Indentation refers to the spaces at the beginning of a code line.
• A code block (body of a function , loop etc.) starts with indentation and ends with
the first unindented 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 is preferred over tabs.
Here is an example.
Script.py
for i in range(1,11):
print(i)
if i == 5:
break
Output
1
2
3
4
5
Variables

• In Python variables are created the moment


you assign a value to it.
• Example :
x=5
y = "Hello, World!“
Python has no command for declaring a
variable.
Comments
• In python, any statement written along with #
symbol is known as a comment.
• The interpreter does not interpret the
comment
• Python supports two types of comments:
1) Single Line Comment:
• In case user wants to specify a single line
comment, then comment must start with #
• Eg: # This is single line comment.
print "Hello Python"
Comments
2) Multi Line Comment:
Multi lined comment can be given inside triple
quotes.
eg: “”” This Is Multi line comment “””
“””This is
multiline
comment”””
print "Hello Python"
Simple Python program to display
welcome message
• Print (“welcome to world of python”)
Data Types in Python
• A data type represents the type of data stored into
a variable or memory. The data types which are
already available in python language are called
Built-in types. Data types which are created by the
programmers are called user defined data types.
Built-in data types
1) None type
2) Numeric types
3) Sequences
4) Sets
5) Mappings
1) None Type
• In python, the ‘None’ type represents an object that
does not contain any value. In java , it is called ‘null’
object.
• In python program, maximum of only one ‘None’
object is provided. Use of none is that it is used
inside a function as a default value of the arguments.
• When calling the function , if no value is passed,
then the default value will be taken as ‘none’.
• In Boolean expressions, ‘none’ data type represents
‘False’.
2) Numeric Types
• These types represents numbers.
• There are three sub types
1. Int
2. Float
3. Complex

Int type represents an integer number. It is a number without


any decimal point or fraction part. For eg. 200,
-50,0,8887600 are integer nos.
How to store integer no into variable?
A=-50
In python there is no limit for the size of an int data type. It can
store very large integer nos conveniently.
Float data type
-> This type represents floating point nos.
(Numbers that contains a decimal point)
->For eg.0.5,-3.4567,290.08,0.001 etc.
-> How to store float no into variable?
num= 55.76
Complex data type
-> A no in the form of a+bj or a+bJ is called
complex no.
-> Here a represents the real part of the no and b
represents the imaginary part of the no.
• The suffix ‘j’ or ‘J’ after ‘b’ indicates the square
root value of -1.
• The parts ‘a’ and ‘b’ may contain integer or
floats.
For eg. 3+5j, 0.2+10.5J, -1 -5.5J
Converting data types explicitly
• Int(x) is used to convert the no x into int type.
Eg. X=15.16
Int (x) #will display 15

• Float(x) is used to convert x into float type.


eg. Num=15
Float(num) # will display 15.0
Converting data types explicitly
• Complex(x) is used to convert x into a complex
no with real part x and imaginary part zero.
Eg. n=10
complex(n) #will display (10+0j)
• Complex(x,y) is used to convert x and y into a
complex no such that x will be the real part and
y will be the imaginary part.
Eg. a=10
b=-5
Complex(a,b) #will display (10-5j)
3) Bool data type
• It represents boolean values true and false.
• Python internally represents true as 1 and
false as 0.
• Blank string “ “ is represented as false
Eg. a=10
b=20
if(a<b) : print (“a is smaller”)
4) Sequences in Python
• A sequence represents a group of elements or
items. For eg. A group of integer nos will form a
sequence.
• There are six types of sequences in Python
1) str
2) bytes
3) bytearray
4) list
5) tuple
6) range
1) str datatype
• In python str represents string data type. String is a
group of characters.
• They are enclosed in single quotes or double quotes.
• str=“welcome” or str=‘welcome’
• We can also write strings inside “”” (triple double
quotes) or ‘’’(triple single quotes) to span a group of
lines including spaces.
• The characters in a string are counted from 0
onwards. Hence str[0] indicates the 0th character or
beginning character in the string.
1) str
• S=‘welcome to core Python’
output
print(s) welcome to core
Python
print (s[0]) w
print (s[3:7]) come # 3rd to 6th
characters
print(s[11:]) core Python #from 11th char till end
print(s[-1]) n # display first char from the end
print (s * n) # * repetition operator repeats the string
2) bytes datatype
• bytes data type represents a group of byte
numbers like an array does.
• Byte no is any positive integer from 0-255
• Byte array can store no.s in the range 0 to 255
and it can’t store negative no.
• We can’t modify any element in the bytes type
array
• Elements=[10,20,0,40,15]
x=bytes(elements)
print(x[0])
3) Bytearray datatype

• bytearray datatype is similar to bytes data


type.
• But bytearray type can be modefied whereas
bytes type array can’t.
• Eg. elements=[10,20,0,40,15]
x=bytearray(elements)
print(x[0])
We can write x[0]=55
x[1]=80
3) list datatype
• Lists in python are similar to arrays in C or Java.
• A list represents a group of elements.
• Differences between list and array
1) A list can store different types of element but
array can store only one type of elements.
2) Lists can grow dynamically in memory but the
size of arrays is fixed and they can’t grow at
runtime.
3) Lists are represented using square brackets[]
and the elements are written in [], separated by
commas.
List
• List =[10,20,15.5,’ajay’,”vijay”]
• Print (list)
• Print (list[0])
• Print (list[1:3])
• Print(list*2)
4) Tuple datatype
• A tuple is similar to list.
• It contains a group of elements which can be
of different types.
• The elements in the tuple are separated by
commas and enclosed in parentheses ().
• But list elements can be modified whereas
tuple elements can not be modified.
• Tuple can be treated as read only list.
Tuple
Eg. Tp= (10,20,15.5,’ajay’,”vijay”)
Print (tp[0])
Print (tp)
Print (tp[0])
Print (tp[1:3])
Print (tp[-2])
Print (tp*3)
5) Range datatype
• Range data type represents a sequence of nos.
• The nos. in the range are not modifiable.
• It is generally used for repeating a for loop for a
specific no. of times.
• Eg r=range(10)
for i in r:print(i)
r= range(30,40,2)
for i in r: print(i)
r= range(40,30,-2)
for i in r: print(i)
Sets data type

• A set is an unordered collection of elements


similar to a set in mathematics.
• The order of elements is not maintained in the
sets. It means the elements may not appear in
the same order as they are entered into the
set.
• A set does not accept duplicate elements
• There are 2 sub types in sets
1) set datatype
2) Frozenset datatype
Set datatype

• To create a set, we should enter the elements


separated by commas inside curly braces { }.
• Sets are unordered , we cant retrieve elements
using indexing or slicing operations.
• s={ 10,20,30,40,50} print (s)
• To create a set of characters we can use foll.
• ch=set(“hello”) print (ch)
• update () method is used to add elements to set.
• s.update ([70,80]) print (s)
• Remove() method is used to remove any particular
element from a set.
• s.remove(50)
frozenset datatype
• It is same as the set datatype.
• The main difference is that the elements in the set
datatype can be modified, whereas the elements of
frozenset can not be modified.
• We can create a frozenset by passing a set to
frozenset() function as follows
• s={10,20,30,40,50,60}
• fs=frozenset(s) Print(fs)
• We can create frozenset by passing a string (a group of
chars) to frozenset() function
• fs=frozenset(“python”) print (fs)
• update() and remove() methods will not work on
frozensets since they can not be modified or updated.
Mapping Types

• A map represents a group of elements in the form


of key value pairs so that when the key is given,
we can retrieve the values associated with it.
• The dict datatype is an example for a map.
• It represents a dictionary that contains pairs of
elements such that the first element represents
the key and next one becomes its value.
• The key and its value should be separated by a
colon (:) and every pair should be separated by a
comma.
• All the elements should be enclosed inside curly
brackets { }.
Mapping
• d = {1 : ‘abc’, 2:’pqr’ , 3: ‘xyz’}
• Print (d)
• Print(d[3])
• Print (d.keys())
• Print(d.values())
• d[2] = ‘lmn’
• del d[3]
Literals in Python
• A literal is a constant value that is stored into a
variable in a program.
• Eg. a=15 here a is variable into which const
value 15 is stored. 15 is called integer literal
• Different types of literals in Python :
1) Numeric literals
2) Boolean literals
3) String literals
Numeric Literals
Literal Name Example

Integer Literal 250,-45

Float Literal 5.65, -42.4, 1.25E4

Hexadecimal Literal 0x5A1C

Octal Literal 0557

Binary Literal 0B110101

Complex Literal 18+3J


Boolean Literals

• These literals are the true or false values stored into


a bool type variable.

String Literals
• A group of characters is called a string literal.
• They are enclosed in single quotes(‘) or double
quotes(“) or triple quotes (‘’’ or “””).
• Single or double quoted strings should end in the
same line as :
• S1=“This is python prog”
• S2=‘Core Python’
• When a string literal extends beyond a single
line, we should go for triple quotes as follows:
• S1= ‘’’ python has
various features
like object oriented,
interpreted, platform
independent’’’
• s2 = “”” python has
various features
like object oriented,
interpreted, platform independent”””
String Literal
• When a string spans more than one line
adding backslash (\) will join the next string to
it.
• Eg. Str =“ This is first \
chapter of Python \
programming “
Escape Characters in Strings
Escape Meaning
character
\ New Line continuation

\\ display a single \

\’ display a single quote

\” display a double quote

\b Backspace

\r Enter

\t Horizontal tab space

\v Vertical tab

\n New line
Determining the datatype of a variable

• type() function can be used to determine the


data type of a variable.
• Eg. A=15
print (type(a))
• ch = ‘A’
print(type(ch))

Naming Conventions in Python

You might also like