Python Fundamentals
Python was created by Guido Van Rossum when he was working at CWI (Centrum
Wiskunde & Informatica) which is a National Research Institute for Mathematics and Computer
Science in Netherlands. The language was released in I991. Python got its name from a BBC
comedy series from seventies- “Monty Python‟s Flying Circus”. Python can be used to follow both
Procedural approach and Object Oriented approach of programming. It is free to use.
Features which make Python so popular are as follows:
1. It is a general purpose programming language which can be used for both scientific
and non scientific programming.
2. It is a platform independent programming language.
3. It is a very simple high level language with vast library of add-on modules.
4. It is excellent for beginners as the language is interpreted, hence gives immediate
results.
5. The programs written in Python are easily readable and understandable.
6. It is suitable as an extension language for customizable applications.
7. It is easy to learn and use.
Python shell can be used in two ways, viz., interactive mode and script mode. Where
Interactive Mode, as the name suggests, allows us to interact with OS; script mode let us
create and edit python source file
To create and run a Python script,
Use following steps in IDLE, if the script mode is not made available by default with IDLE
environment.
1. File -> Open OR File -> New Window (for creating a new script file)
2. Write the Python code as function i.e. Script
3. Save it (Ctrl+S)
4. Execute it in interactive mode- by using RUN option (F5)
^D (Ctrl+D) or quit () is used to leave the interpreter.
^F6 will restart the shel
Python Character Set
A set of valid characters recognized by python. Python uses the traditional ASCII
character set. The latest version recognizes the Unicode character set. The ASCII
character set is a subset of the Unicode character set.
Letters :– A-Z,a-z Digits :– 0-9 Special symbols :– Special symbol available over
keyboard White spaces:– blank space,tab,carriage return,new line, form feed Other
characters:- Unicode
Token:
Smallest individual unit in a program is known as token.
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. punctuators
Keywords/Reserve word of the compiler/interpreter which can’t be used as identifier.
and exec not def import
as finally or del in
assert for pass elif is
break from print else lambda
class global raise except try
continue if return while
with yield
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 special characters
Identifier must not be a keyword of Python.
Python is a case sensitive programming language.Thus, Rollnumber and
rollnumber are two different identifiers in Python.
Some valid identifiers : Mybook, file123, z2td, date_2, _no
Some invalid identifier : 2rno,break,my.book,data-cs
Some additional naming conventions
Class names start with an uppercase letter. All other identifiers start with a
lowercase letter.
Starting an identifier with a single leading underscore indicates that the identifier is
private.
Starting an identifier with two leading underscores indicates a strong private
identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Literals in Python can be defined as number, text, or other data that represent values to
be stored in variables.
Example of String Literals: name =‘Johni’ fname =“johny”
Example of Integer Literals: (numeric literal) age = 22
Example of Float Literals: (numeric literal) height = 6.2
Example of Special Literals: name =none
Escape sequences:
Escape Sequence Description
\\ Backslash (\)
\' Single quote (')
\" Double quote (")
\n ASCII Linefeed (LF)
\t ASCII Horizontal Tab (TAB)
Input and Output
var1=‘Computer '
var2=‘Programming'
print(var1,' and ',var2,' )
Output :- Computer Programming
input() Function In Python allows a user to give input to a program from a keyboard but
returns the value accordingly.
EX 1:
age = int(input(‘enter your age’))
percentage = float(input(‘enter percentage’))
Ex2:
age = int(input(‘enter your age’))
C = age+2 #will not produce any error
NOTE : input() function always enter string value in python 3. so on need
int(),float() function can be used for data conversion.
variable = input(< Prompt to display>)
e.g. name= input(‘What is your name:’)
The input () function always returns a value of string type .If you enter integer value it will
be treated as string .
age= int(input(‘What is your age:’))
type(age) =>> int
print() Function In Python is used to print output on the screen.
Syntax of Print Function
print(expression/variable)
Ex: print(122) print('hello India') print(‘Computer',‘Class')
print(‘Computer',‘Class',sep=
' & ')
print(‘Computer',‘Class',sep=
' & ',end='.')
Output :- 122 Output :-hello India Output :-
Computer Class
Computer & Class
Computer & Class.
Operators can be defined as symbols that are used to perform operations on operands.
Types of Operators:
1. Arithmetic Operators.
2. Relational Operators.
3. Assignment Operators.
4. Logical Operators.
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
1. Arithmetic Operators:
Arithmetic Operators are used to perform arithmetic operations like addition,
multiplication, division etc
Operators Description Example
+ perform addition of two number a+b
- perform subtraction of two number a-b
/ perform division of two number a/b
perform multiplication of two number a*b
*
% Modulus = returns remainder a%b
Floor Division = remove digits after the
// decimal point a//b
Exponent = perform raise to power a**b
**
2. Relational Operators
Relational Operators are used to compare the values.
Operators Description Example
== Equal to, return true if a equals to b a == b
!= Not equal, return true if a is not equals to b a != b
Greater than, return true if a is greater than
> b a>b
Greater than or equal to , return true if a is
>= greater than b or a is equals to b a >= b
< Less than, return true if a is less than b a<b
Less than or equal to , return true if a is less
<= than b or a is equals to b a <= b
3. Assignment Operators:
Used to assign values to the variables.
Operators Description Example
= Assigns values from right side operands to left side operand a=b
+= Add 2 numbers and assigns the result to left operand. a+=b
/= Divides 2 numbers and assigns the result to left operand. a/=b
*= Multiply 2 numbers and assigns the result to left operand. A*=b
-= Subtracts 2 numbers and assigns the result to left operand. A-=b
%= modulus 2 numbers and assigns the result to left operand. a%=b
Perform floor division on 2 numbers and assigns the result to
a//=b
//= left operand.
calculate power on operators and assigns the result to left
a**=b
**= operand.
4. Logical Operators
Logical Operators are used to perform logical operations on the given two variables or
values.
Operators Description Example
and return true if both condition are true x and y
or return true if either or both condition are true x or y
not reverse the condition not(a>b)
a=30
b=20
if(a==30 and b==20):
print('hello')
Output :- hello
5. Identity Operators:
Identity operators in Python compare the memory locations of two objects.
Operators Description Example
returns true if two variables point the same
is a is b
object, else false
returns true if two variables point the different
is not a is not b
object, else false
Ex:
a = 330 b=330
if (a is b):
print('both a and b has same
identity')
else:
print('a and b has different identity') b=99
if (a is b):
print('both a and b has same identity') else:
print('a and b has different identity')
Output :-
both a and b has same identity a and b has different identity
Punctuators:
Used to implement the grammatical and structure of a Syntax.Following are the python
punctuators.
Few puncutuators are ' “ # \ ( ) [ ] { } @ , . : = ;
A python program contain the following components
1.Expression
2.Statement
3.Comments
4.Function
5.Block &n indentation
1.Expression : - which is evaluated and produce result.
Ex: (20 + 4) / 4 , a+(b/2)-3+7
2. Statement :- instruction that does something.
Ex:
a = 20
print("Calling in proper sequence")
Creating a Comment
There are two types of comments in Python.
1. Single line comment
# This is just a comment. Anything written here is ignored by Python
2. Multiple line comment
To have a multi-line comment in Python, we use triple single quotes at the beginning and
at the end of the comment, as shown below.
''' This is a
multi-line
comment '''
Example:
'''We are writing a simple program here
First print statement.
This is a multiple line comment.'''
4.Function: a code that has some name and it can be reused.
Ex: keyArgFunc in above program
#function definition comment
def keyArgFunc(empname, emprole):
print ("Emp Name: ", empname) Function
print ("Emp Role: ", emprole) Indentation
return;
A = 20
print("Calling in proper sequence")
keyArgFunc(empname = "Nick",emprole = "Manager" ) Statements
print("Calling in opposite sequence")
keyArgFunc(emprole = "Manager",empname = "Nick")
5. Block & indentation : Group of statements is block. Indentation at same level
create a block.
Ex: all 3 statement of keyArgFunc function
Python Indentations
Python uses indentation to indicate a block of code.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important
Variables:
Variable is a name given to a memory location. A variable can consider as a container
which holds value. Python is a type infer language that means you don't need to specify
the datatype of variable.Python automatically get variable datatype depending upon the
value assigned to the variable.
Assigning Values To Variable
a = 23
name = ‘python' # String Data Type b = 6.2
sum = None # a variable without value sum = a + b
print (sum)
Multiple Assignment:
Assign a single value to many variables.
a=b=c=1 # single value to multiple variable
a,b = 1,2 # multiple value to multiple variable
a,b = b,a # value of a and b is swaped
Constants
A constant is a type of variable whose value cannot be changed. It is helpful to think of
constants as containers that hold information which can not be changed later.
Nontechnically, you can think of constant as a bag to store some books and those books
can not be replaced once placed inside the bag.
Declaring and assigning value to a constant
Create a constant.py
PI=3.14
GRAVITY=9.8
print(constant.PI)
print(constant.GRAVITY)
1. Python Program to Print Hello world!
#This program prints Hello,world!
print('Hello,world!')
Output
Hello,world!
2. PythonProgram to Add Two Numbers
#This program adds two numbers
num1=1.5
num2=6.3
#Add two numbers
sum=float(num1)+float(num2)
#Display the sum
print('Thesumof2 numbers”, sum)
Output
The sum of 1.5 and 6.3 is 7.8
Data Types
Most of the computer programming language support data type, variables,operator and
expression like fundamentals.Python also support these.
Data Type specifies which type of value a variable can store. type() function
is used to determine a variable's type in Python.
Data Types In Python
Number
String
Boolean
List
Tuple
Set
Dictionary
Number In Python
It is used to store numeric values
Python has three numeric types:
Integers
Floating point numbers
Complex numbers.
1. Integers
Integers or int are positive or negative numbers with no decimal point.
Integers in Python 3 are of unlimited size.
Ex:
a= 100
b= -100
c= 1*20
print(a)
print(b)
print(c)
Type Conversion of Integer
int() function converts any data type to integer.
Ex:
a = "101" # string
b=int(a) # converts string data type to integer.
c=int(122.4) # converts float data type to integer.
print(b)
print(c)
Output :-
101
122
2. Floating point numbers
It is a positive or negative real numbers with a decimal point.
Ex:
a = 101.2
b = -101.4
c = 111.23
d = 2.3*3
print(a)
print(b)
print(c)
print(d)
Output :-
101.2
-101.4
111.23
6.8999999999999995
3. Complex numbers
Complex numbers are combination of a real and imaginary part.Complex
numbers are in the form of X+Yj, where X is a real part and Y is imaginary part.
Ex:
a = complex(5) # convert 5 to a real part val and zero imaginary part
print(a)
b=complex(101,23) #convert 101 with real part and 23 as imaginary part
print(b)
Output :- (5+0j) (101+23j)
2. String In Python
Strings:
A string can hold any type of known characters it means letters numbers and special
characters of any known scripted language. In python 3.x, each character stored in a
string is a Unicode character.
Unicode is a system designed to represent every character from every language.
Following are all legal strings in Python:
“abcd”, “1234”, “$%^&”, ‘????’
3. Boolean In Python
Booleans: - These represent the truth values false and true. The Boolean type is subtype
of plain integer, and Boolean values false and true behave like 0 and 1, respectively. To
get the Boolean equivalent of 0 and 1, you can type bool(0) or bool(1), python will return
false or true respectively .