Fundamentals of Python
Fundamentals of Python
PythonCharacter
Set
Is a set of valid characters that python can recognize. A
character represent letters, digits or any symbol. Python
support UNICODE encodingstandard. Following are the
Pythoncharacter set
Lette : A-Z, a-
rs z
Special
Digits symbols:space +-*/()~`!@#$%^
: 0-9 & [{]};:‟”,<.>/?
White spaces: Blank space, Enter, Tab
Keywords
Identifiers(Name)
Literals
Operators
Punctuators
KEYWORDS
Keywords are the reserved words and have special
meaning for python interpreter. Every keyword is
assigned specific work and it canbe usedonly for that
purpose.
A partial list of keywords in Python is
VINODKUMARVERMA,
PGT(CS),KVOEFKANPUR&
SACHIN BHARDWAJ, PGT(CS),KVNO.1
IDENTIFIERS
Are the names given to parts of program variables,
different objects, classes, like
functions etc.
Identifier forming rules of Python are:
Isan arbitrarily long sequenceof letters and digits
It mustnot be a keyword
allowed.
Space not allowed
The following are some valid identifiers
GradePay File_12_2018 JAMES007
GRADEPAY _ismarried _to_updat
e
String Size
“\\" 1
“abc" 3
“\ab" 2
“Meera\‟s Toy” 11
“Vicky‟s” 7
You can check these size using len() function of Python. For example
>>>len("abc") and press enter, it will show the size as 3
Size of
String
For multiline strings created with triple quotes : while calculating size the
EOL character as the end of line is also counted in the size. For
example, if you have created String Address as:
>>> Address="""Civil lines
Kanpur"""
>>> len(Address)
18
For multiline string
created with
single/double
quotes the EOL is
not counted.
>>> data="ab\
bc\
cd"
>>> len(data)
Numeric
Literals
Thenumericliterals in Python canbelong to any
ofthe following numerical types:
1) Integer Literals:it contain at least one digit and must
not contain decimal point. It may contain (+) or (-)
sign.
Typesof IntegerLiterals:
a) Decimal : 1234, -50, +100
b)Octal : it starts from symbol 0o (zero followed by
letter ‘o’)
Fore.g. 0o10 represent decimal 8
Numeric
Literals
>>> num= 0o10
>>> print(num)
It will print the value 8
<class 'tuple'>
Boolean
Literals
A Boolean literals in Python is used to represent one of the two
Boolean values i.e. Trueor False
These are the only two values supported for Boolean Literals For
e.g.
>>> isMarried=True
>>> type(isMarried)
<class 'bool'>
Special Literals
None
Python hasone special literal, which is None. It indicate absence
of value. In other languages it is knows as NULL. It is also used to
indicate the end of lists in Python.
>>> salary=None
>>> type(salary)
<class 'NoneType'>
Complex
Numbers
Complex: Complex number in python is made up of two floating point values, one
each for real and imaginary part. For accessing different parts of variable (object)
will
x; weuse x.real and x.image. Imaginary part of number is represented by
the “j”
instead of “I”, so 1+0j denotes zero imaginary.
part.
Example
>>> x = 1+0j
>>> print x.real,x.imag
1.0 0.0
Example
>>> y = 9-5j
>>> print y.real, y.imag
9.0 -5.0
Conversion from one type to another
Python allows converting value of one data type to another data type. If it
is done by the programmer then it will be known as type conversion or
type casting and if it is done by compiler automatically then it will be
known as implicit type conversion.
Example of Implicit type conversion
>>> x = 100
>>> type(x)
<type 'int'>
>>> y = 12.5
>>> type(y)
<type 'float'>
>>> x=y
>>> type(x)
<type 'float'> # Here x isautomatically converted to float
Conversion from one type to
another
Explicit type conversion
To perform explicit type conversion Python provide functions like
int(), float(), str(), bool()
>>> a=50.25
>>> b=int(a)
>>> print b
50
Here 50.25 is converted toint value 50
>>>a=25
>>>y=float(a)
>>>print y
25.0
Simple Input and
Output
In python we can take input from user using the built-in function
input().
Syntax
variable = input(<message to display>)
Note: value taken by input() function will always be of String
type, so by
default you will not be able to perform any arithmetic operation on
variable.
>>> marks=input("Enter your marks ")
Enteryour marks100
>>> type(marks)
<class 'str'>
Here you can see even we are entering value100 but it will be treated as
string and will not allow any arithmetic operation
Reading / Input of
Numbers
Now we are aware that input() function value will
always be of string type, but what to do if we
want number to be entered. The solution to this
problem is to convert values of input() to numeric
type using int() or float() function.
Possiblechancesof error while
taking input as numbers
1. Entering float value while converting
to int
>>> num1=int(input("Enter marks "))
Entermarks100.5
Traceback (most recent call last):
File "<stdin>", line 1, in
<module>
ValueError: invalid literal for int()
with base 10: '100.5‘
Example 2
>>> percentage=float(input("Enterpercentage"))
Enter percentage100 percent Traceback (mostrecent calllast):
File"<stdin>", line1, in<module>
ValueError:couldnotconvertstringtofloat:„100 percent'
Program
1
Opena new scriptfile and type thefollowing
code:
num1=int(input("Enter Number 1 "))
num2=int(input("Enter Number 2 "))
num3= num1+ num2
print("Result
=",num3)
Operator Purpose
+ Unary plus
- Unary minus
~ Bitwise
complement
Not Logical negation
Typesof
Operators
Binary Operators: are operator that require
those operand to s are
two some
operators:
operate upon. Following Binary
1. Arithmetic
OperatorsOperator Action
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
** Exponent
// Floor division
Exampl
e>>> num1=20
>>> num2=7
>>> val = num1% num2
>>> print(val)
6
>>> val = 2**4
>>> print(val)
16
>>> val =
num1/ num2
>>>
print(val)
2.857142857
142857
>>> val =
num1/ /
num2
Bitwise
operator
Operator Purpose Action
& Bitwise AND Return1 if Bitwise operator works on
both inputs the binary value of
are 1 number not on the actual
value. For example if 5 is
^ Bitwise XOR Return 1, if the passed to these
number of 1 in operator it will work on
input isinodd
101 not on 5. Binaryof
| Bitwise OR Return1 if 5 is 101, and return the
any input is result in decimal not in
1 binary.
Exampl
e
Binary of 12 is1100 and 7 is0111,
soapplying& 1100
0111
-------
Guessthe output with
0100 Which isequal to decimal value 4
| and ^ ?
Let usseeone practical example, Tocheck whether entered number isdivisible of 2 (or in
a power of 2 or not) like 2, 4, 8, 16, 32 and soon
Tocheck this, noneed of loop, simplyfindthebitwise&ofnandn-1, if theresultis0 it meansit
isinpowerof 2 otherwise not
Identity Operators
Operators Purpose
is Isthe Identity same?
is not Isthe identity not same?
Relational
Operators
Operators Purpose
< Lessthan
> Greater than
<= Lessthan or Equal to
>= Greater than or Equal to
== Equal to
!= Not equal to
Logical
Operators
Operators Purpose
and Logical AND
or Logical OR
not Logical NOT
Assignment
Operators
Operators Purpose
= Assignment
/= Assign quotient
+= Assign sum
-= Assign difference
*= Assign product
**= Assign Exponent
//= AssignFloordivision
Membership
Operators
Operators Purpose
in Whether variable
in sequence
not in Whether variable not
in sequence
Punctuato
rs
Punctuatorsare symbolsthat are usedin
programming languages to organize
sentencestructure, and indicate the rhythm and
emphasisof expressions,statements, and program
structure.
Commonpunctuatorsare: „“ # $ @ []{}=:;(),.
Barebones of Python
Program
It meansbasicstructureof a Python
program
Takea look of following code:
#This program showsa program‟s component
#
Definition of function SeeYou() follows
Comments
def SeeYou():
print(“This is my function”)
Function
#Main program
A=10
Statement
B=A+20
C=A+B Expressions
Inline
if(C>=100) #checking
Comment
conditionprint(“Value isequals or more than
s
100”)
else: print(“Value Bloc
Indentation
print(“Welcome to python”)
Theabovestatementcallprintfunction
When an expression isevaluated a statement is executed
i.e. someaction takes place.
a=100
b= b+ 20
Comment
s
Commen are additional information written in
ts which is executed a
program bynotInterpreter. by interpreter
information
ignored statements used, program
regarding Comment i.e.
flow,etc. contains
Commentsin Python begins from #
area=
Examplelength*breadth #
Multiline comment calculatingareaofrectangle
Example 1 (using #)
# Programname:area
ofcircle
# Date:20/07/18
#Language:Python
Comment
s
Multiline comment(using“ “ “) triple
quotes
Example
““ “
Programname:swappingoftwonumber
Dat : 20/07/18
e :byusingthirdvariabl
””” Logic e
Function
s
Function is a block of code that has name and can be reu
specifying its name in the program where needed. It is create
def keyword.
Example
defdrawline():
print(“======================“)
print(“WelcometoPython”)
drawline()
print(“Designed by ClassXI”)
drawline()
Block and Indentation
Group of statement is known as block like
function, conditions or loop etc.
For e.g.
def area():
a = 10
b=5
c=
a*b
Indentation means
extra space before
writing any statement.
Variables
Variables are named temporary location used to store values
which can be further used in calculations, printing
result etc. Every variable must have its own Identity, type
and value.
Variable in python is created by assigning value of
simply desired type to them.
Fore.g
Num= 100
Name=“James”
Variables
Note: Python variables are not storage containers like ot
programming language. Letus analyze by example.
In C++, if we declare a variable radius:
radius= 100
[suppose memory address is 41260]
Now
we again assign new value to radius
radius= 500
Now the memory address will
be still same only
value will change
Variables
Now let us take example of Python:
radius = 100 [memory address 3568]
Now you can see that In python, each time you assign
new value to variable it will not use the same memory
address and new memory will be assigned to variable.
In python the location they refer to changes every time
their value change.(This rule is not for all types of
variables)
LvaluesandRvalues
Lvalue : that on the hand Side of
expression comes Left
Assignment. that on the hand Side of
Rvalue : comes Right
expression
Assignment
Lvalue refers to object to which you can assign value. It
refers to memory location. It can appear LHS or RHS of
assignment
Rvalue refers to the value we assign to any variable.
it can appear on RHS of assignment
Lvalues and Rvalues
For example (valid useof Lvalue and Rvalue)
x = 100
y = 200
Examples
:
Multiple Assignments
x,y,z = 10,20,30 #Statement
z,y,x = x+1,z+10,y-10 1
print(x,y,z) #Statement
Output will 2
be 10 40 11
Now guessthe output of following codefragment
x,y = 7,9
y, z =x-2, x+10
print(x,y,z)
Multiple Assignments
Let us take another example
y, y = 10, 20
x= “KVians” int:100
x
string:KVians
Caution with Dynamic
Typing
Always ensure correct operationduring dynamic
typing. If types are not used correctly
Python may raise an error.
Take an example x
= 100
y= 0
y= x/
2
print(y)
x='Exam'
y= x/
2 #
Determining type of
variable
Python provides function to check the datatype
type() variables. of
>>> salary=100
>>> type(salary)
<class 'int'>
>>> salary=2000.50
>>> type(salary)
<class 'float'>
>>> name="raka"
>>> type(name)
<class 'str'>
Output through
print()
Python allows to display output using print().
Syntax:
print(message_to_print[,sep=“string”,end=“string”])
Example 1
print(“Welcome”)
Example 2
Age=20
print(“Your age
is“, Age)
Output through
print()
Example 3
r = int(input("Enter Radius "))
print("Area of circle is ",3.14*r*r)
Name="James"
Salary=20000
Dept="IT"
print("Name
is",Name,end='@') print(Dept)
print("Salary is ",Salary)
Justa
minute…
WAP to obtain temperature in Celsiusand convert it
into Fahrenheit.
What will be the
output of following
code: x, y
= 6,8
x,y = y, x+2
print(x,y)
What will be the
output of
following code: