0% found this document useful (0 votes)
72 views13 pages

Getting Started With Python

Notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
72 views13 pages

Getting Started With Python

Notes
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 13

Getting started with Python

Program: A program is an ordered set of instructions to be executed by a computer to


carry out a specific task.
The language used to specify these set of instructions to the computer is called a
programming language.
Python uses interpreter to convert its instructions into machine language understood
by the computer. An interpreter processes the program statements one by one that is
line by line and then executes them. This process is continued until the whole program
is executed successfully.
A compiler translates the entire source code into object code. Any error in the source
code would be displayed at the bottom.
Features of Python:
• Python is a high-level language. It is a free and open-source language.
• It is an interpreted language as Python programs are executed by an interpreter.
• Python programs are easy to understand as they have clearly defined syntax and
simple structure.
• Python is case sensitive. Ex: NUMBER, Number, number are noy the same.
• They are portable and platform independent which means it can be run on diff
operating systems and hardware platforms.
• It has a rich library of predefined functions.
• It is also helpful in web development. Many popular web services and
applications are built by Python.
• It uses indentation for blocks and nested blocks.
Working with Python: To write and execute a Python program, we need to have a
Python interpreter also called as Python shell installed in our computer or we can use
any online Python interpreter.
The symbol >>> called Python prompt indicates that the interpreter is ready to take
instructions. We can type the commands or statements in the prompt to execute them
using a Python interpreter.
Execution Modes: There are two ways to use the Python interpreter- Interactive mode
Script mode
Interactive mode: It allows execution of individual statements. We have to write the
Python statements on the >>> prompt directly. When we press enter key the
interpreter executes the statement and display the result. But in interactive mode we
cannot save the statements for future use. We have to retype the statements to run
them again.

1
Script mode: In script mode we can write a python program in a file and save it and
then use the interpreter to execute it. Python files are saved with extension .py.
To execute the program, we have to either type the filename as prog5.py or open the
program from IDLE. After saving the file we should click Run module from the menu.
The output appears on shell.

Python Keywords: Keywords are reserved words with specific meaning to the Python
interpreter. As Python is case sensitive keywords must be written exactly as it is
defined.
Ex: None, False, class, etc.

Identifiers: Identifiers are names used to identify a variable, function or other entities
of a program.
The rules for naming an identifier in Python are:
• The name should begin with a capital letter or small letter or an underscore
sign_. This maybe followed by any combination of characters a-z, A-Z, 0-9 or
underscore. But identifier cannot start with a digit.
• It can be of any length. But it is preferred to be short and meaningful.
• It shouldn’t be a keyword defined by Python.
• Special symbols like !,@, #,$, %, etc shouldn’t be used in identifiers.
Ex to calculate average of 3 subject marks are: avg=(marks1+marks2+marks3)/3
To calculate area of a rectangle:
Area=length*breadth

Variables: Variables are names given to a memory location to store a value known as
object. Value of a variable can be a string written within ‘ ‘ single quotes or “ “ double
quotes. (Ex: ‘Global citizen’ or ‘b’) , numeric, or any combination of alphanumeric
characters( CD67). Numeric values shouldn’t be written without “ “ or ‘ ‘ .
In Python we can use assignment statements = to create new variables and assign
specific values to them.
Ex: gender =’M’
Message= “ Keep Smiling”
Price=678.9
Variable declaration is implicit in Python, which means variables are automatically
declared and created when they are assigned a value for the first time.
Variables must be assigned values before they are used in expressions or it will lead to
an error in the program.
Wherever a variable name occurs in an expression, the interpreter replaces it with the
value of that particular variable.

2
Comments: Comments start with # (Hash) symbol. Any statement written with a # is
treated as a comment and interpreter ignores it while executing the statement.
Comments are written to make the source code easier for user or non programmer to
understand. Comments are used to give meaning and purpose of source code. For large
and complex software, a program written by one programmer is required to be used
or maintained by another programmer. In such a situation documentation also called
as comments are needed to understand the working of the program.

Everything is an Object: Python treats every value that is data item whether numeric,
string or other type as an object. Every object assigned has a unique identity which
remains for the lifetime of that object.
Id() is a function that returns the identity of an object that is the memory address of
the object.
Ex: >>>num1=20
>>>id(num1)
1433920578 # memory address
>>>num2=20-10
>>>id(num2)
143392078
Memory address is same because value of num1 and num2 is same that is 10.

Data types: Data type identifies the type of data values also called as data item a
variable can hold and the operations that can be performed on that data.
Data types in Python are:
• Numbers-Integer- Boolean
Float
Complex
• Sequence-Strings
Lists
Tuples
• Sets
• None
• Mapping-Dictionaries

Number: Number data type stores numerical value only. It is further classified as
int, float and complex. Integer has subtype as Boolean data type. It consists of true
or false where true is non-zero, not null, not empty. Boolean false has value zero.
Int data type holds negative and positive no’s such as -1,-6, 0, 10, 3, etc.
Float data type holds negative and positive no’s with decimal pt such as -2.04, 4.0,
12.45

3
Complex data type holds complex no’s such as 3+4i, 2-2i
Ex:
>>>num1=10
>>>type(num1)
<class int>
>>> var1=true
>>> type(var1)
<class ‘bool’>
Variables of simple data types like integer, float, complex, Boolean hold a single
value. Such variables are not useful to hold a long list of information like names of
month in a year, names of students in a class, etc.
To store long list of information, Python provides data types like tuples, lists,
dictionaries and sets.

Sequence: It is an ordered collection of data items where each data item is indexed
by an integer. There 3 types of sequence data types- strings, lists and tuples.

String: It is a group of characters and these characters maybe alphabets, digits,


special characters including spaces. Strings should be enclosed within single quotes
‘ ‘ or double quotes “ “. Ex: ‘Hello’ or “Hello”.
The quotations are not part of the string. They are used to mark the beginning and
end of the string for interpreter.
>>> Str1= ”Hello friend”
>>>Str2=’567’
Here 567 cannot be used for numerical operations as it is a string.

Lists: Lists is a sequence of items separated by commas and the items are enclosed
within [ ] square brackets.
>>>list1=[5, 7.8, “New Delhi”, “20c”, 45]
>>>print(list1)
[5, 7.8, “New Delhi”, “20c”, 45 ]

Tuple: Tuple is a sequence of items separated by commas and the items are
enclosed within ( ) parenthesis. Once created we cannot change the tuple values.
>>> tuple1=(10,20,”Apple”, 7.8, ‘A’)
>>>print(tuple1)
(10,20,”Apple”, 7.8, ‘A’)

Sets: Sets is an ordered collection of items separated by commas and the items are
enclosed within { } curly brackets. Once created we cannot change the set values.

4
>>>Set1={ 10,2.0, 3.14, “B’lore”}
>>>print(Set1)
{ 10,2.0, 3.14, “B’lore”}
Sets eliminate duplicate that is repeated items.
>>>Set2={1,2,3,1}
>>>print(Set2)
{1,2,3}

None: None is a special data type with a single value. It signifies the absence of a value
in a situation. It is neither false nor zero.
>>>myvar=None
>>>print(myvar)
None

Mapping: Mapping is an unordered data type in Python. There is one standard


mapping data type in Python called dictionary.
Dictionary: It holds data items in Key-value pairs. Items in a dictionary are enclosed in
curly brackets { }. Dictionary provide faster access to data. Every key is separated from
its value by a : colon.
The keys are usually strings and their values can be any data type.
>>>Dict1={‘Fruit’:’Apple’, ‘Climate’:’Rainy’, ‘Price in Kg’: 120}
>>> print(Dict1)
{‘Fruit’: ’Apple’, ‘Climate’: ’Rainy’, ‘Price in Kg’: 120}
>>>print(Dict1[‘Price in Kg’])
120

Mutable and Immutable data type: Sometimes we may require to change or update
the values of certain variables used in a program. But certain data types in Python does
not allow to change the value once a variable of that type is created and assigned
values.
Variables whose values can be changed after they are created and assigned values are
called mutable.
Variables whose values cannot be changed after they are created and assigned values
are called immutable.
When an attempt is made to update the value of an immutable variable, the old
variable is destroyed and a new variable is created by the same name in memory.
Immutable Datatypes Mutable Datatypes
Integers Lists
Float Dictionary
Boolean

5
Complex
Strings
Tuples
Sets

Deciding usage of Python Data types: Lists are used when need a simple iterable
collection of data that may need frequent modifications.
Ex: To store names of students of a class as it is easy to update the list when a new
student joins or leaves the course.
Tuples are used when the elements are unique. It avoids duplicacy of data.
Dictionaries are used when data is being constantly modified or we need a lookup
based on a custom key or we need a logical association b/w the key: value pair.
Ex: a mobile phone book is a good application of dictionary.

Operators: An operator is used to perform mathematical or logical operations on


values. The values that the operators work on are called operands.
Ex: In expression 10+num, 10 and num are operands. + is the operator.
Python supports several types of operators and they are: Arithmetic operators
Relational operators
Assignment operators
Logical operators
Identity operators
Membership operators

Arithmetic Operators:
• + add Operator is used to add two numeric values on either side of the operator.
E.g.: >>>num1=7
>>>num2=6
>>>num1+num2
13
This operator can also be used to two add strings called as concatenation.
>>>str1= ”Hello”
>>>str2= “India”
>>>str1+str2
“HelloIndia”
• - minus operator is used to subtract the rt operand from the lt operand.
>>>num1=8
>>>num2=9
>>>num1-num2
-1
• * multiplication operator is used to multiply 2 values on both side of the
operator.

6
>>>num1=6
>>>num2=5
>>>num1*num2
30
It is also used to repeat the value or item if the first operand is a string and 2 nd
operand is a integer value.
>>>str1=”India”
>>>str1* 2
“IndiaIndia”
• / division operator is used to divide the left operand by the right operand and
gives quotient.
>>>num1=8
>>>num2=5
>>>num1/num2
1.6
• % modulus operator is used to give remainder after the division. The lt operand
is divided by the rt operand.
>>>num1=8
>>>num2=5
>>>num1%num2
3
• // floor operator divides the lt operand by the rt operand and returns quotient
by removing the decimal part. It is also called integer division.
>>>num1=8
>>>num2=5
>>>num1//num2
1
• ** performs exponential calculations on operands. That is the operand on the
lt is raised to the power by operand on the rt.
>>>num1=5
>>>num2=2
>>>num1**num2
25

Relational operator: These operators compares the values of the operands and returns
true or false.
• == double equal to operator tests whether the 2 operands values are equal.
Returns true if they are equal, false if they are not equal.
>>>num1=5
>>>num2=8
>>>num1==num2
False
>>>str1=”India”

7
>>>str2=”India”
>>>str1==str2
True
• != not equal to operator tests whether the 2 operands values are not equal.
Returns true if they are not equal, false if they are equal.
>>>num1=7
>>>num2=6
>>>num1!=num2
True
>>>str1=”India”
>>>str2=”India”
>>>str1!=str2
False
• > greater than operator tests the whether lt operand value is greater than the
rt operand value and returns true otherwise returns false.
>>>num1=7
>>>num2=6
>>>num1>num2
True
>>>str1=”India”
>>>str2=”Gate”
False
• < less than operator tests whether the lt operand value is less than the rt
operand value and returns true otherwise returns false.
>>>num1=5
>>>num2=7
>>>num1<num2
True
>>>str1=”good”
>>>str2=”night”
>>>str1<str2
False
• >= greater than equal to operator checks whether the lt operand value is greater
than or equal to the value of the rt operand. Returns true if the condition is
satisfied else false.
>>>num1=56
>>>num2=56
>>>num1>=num2
True
>>>num1=36
>>>num2=45
>>>num1>=num2
False

8
• <= less than equal to operator checks whether the lt operand value is less than
or equal to the value of the rt operand. Returns true if the condition is satisfied
else false.
>>>num1=34
>>>num2=56
>>>num1<=num2
True
>>>num1=45
>>>num2=45
>>>num1<=num2
True

Assignment Operators: These operators either assigns value or changes the value of
the operand to the lt.
• = equal to operator assigns value of the rt operand to the lt operand.
>>>num1=5
>>>num2=num1
>>>num2
5
>>>country=’India’
>>>country
‘India’
• += plus equal to operator adds the value of the rt operand to the value of the lt
operand and assigns the result to the lt operand. i.e. X+=Y is same as X=X+Y
>>>num1=4
>>>num2=5
>>>num1+=num2
>>>num1
9
>>>num2
5
>>>str1=’Hello’
>>>str2=’India’
>>>str1+=str2
>>>str1
’HelloIndia’
• -= minus equal to operator subtracts the value of the rt operand from the value
of the lt operand and assigns the result to the lt operand. i.e. X-=Y is same as
X=X-Y
>>>num1=4
>>>num2=5
>>>num1-=num2
>>>num1

9
-1
• *= multiply equal to operator multiplies the value of the rt operand with the
value of the lt operand and assigns the result to the lt operand. i.e. X*=Y is same
as X=X*Y
>>>num1=4
>>>num2=5
>>>num1*=num2
>>>num1
20
>>>str1=”India”
>>>str1*=2
>>>str1
“IndiaIndia”
• /= divide equal to operator divides the value of the lt operand by the value of
the rt operand and assigns the result to the lt operand. i.e. X/=Y is same as
X=X/Y
>>>num1=4
>>>num2=2
>>>num1/=num2
>>>num1
2.0
• %= modulus equal to operator divides the lt operand by the rt operand and
assigns the remainder to the lt operand. i.e., X%=Y is same as X=X%Y
>>>num1=5
>>>num2=2
>>>num1%=num2
>>>num1
1
• //= It performs floor division using 2 operands and assigns the result to the lt
operand. i.e., X//=Y is same as X=X//Y
>>>num1=5
>>>num2=2
>>>num1//=num2
>>>num1
2
• **= It performs exponential calculation on operands and assigns value to the lt
operand. i.e., X**=Y is same as X=X**Y
>>>num1=5
>>>num2=2
>>>num1**=num2
>>>num1
25

10
Logical Operators: The 3 logical operators are (and, or, not) which has to be written in
lowercase only. The logical operator evaluates to either true or false based on the
logical operands on either side. By default all values are true, except None, False, 0,
empty collections like “”,(),{},[] and few other special values
• and operator returns true if both the operands are true else returns false.
>>>True and True
True
>>>num1=10
>>>num2=30
>>>bool(num1 and num2)
True (because both variables have a value)
>>>num1=0
>>>num2=10
>>>bool(num1 and num2)
False (because num1 is 0)
>>>True and False
False
>>>False and False
False
• or operator returns true if one of the two operands is true, else returns false
>>>True or True
True
>>>num1=10
>>>num2=30
>>>bool(num1 or num2)
true
>>>True or False
False
>>>False or False
False
• not is used to reverse the logical state of its operand.
>>>num1=10
>>>bool(num1)
True
>>>not num1
>>>bool(num1)
false

Identity Operators: Identity operator is to determine whether value of a variable is of


a certain type or not. Identity operators can also be used to determine whether two
variables are referring to the same object(value) or not.
There are two identity operators- is, is not.

11
• is: Evaluates to true if variables on either side of the operator points to the same
memory location and false otherwise.
var1 is var2 result is true if id(var1) is equal to id(var2). Id() gives memory
address of a variable.
>>>num1=5
>>>type(num1) is int
True
>>>num2=num1
>>>id(num1)
1433920576
>>>id(num2)
1433920576
>>>num1 is num2
True
• is not: Evaluates to false if the variables on either side of the operator point to
the same memory location and true otherwise.
var1 is not var2 result is true if id(var1) is not equal to id(var2).
>>>num1 is not num2
False

Membership operators: Membership operators are used to check if a value is a


member of the given sequence or not.
• in: Returns true if the variable or value is found in the specified sequence and
false otherwise.
>>>a={1,2,3}
>>>2 in a
True
>>>’1’ in a
False
• not in: Returns true if the variable or value is not found in the specified
sequence and false otherwise.
>>>a={1,2,3}
>>>10 not in a
True
>>>1 not in a
False.
To be continued
Likely questions:
1. What are the features of python?
2. Write a note on executive modes.
3. Write the rules of identifiers.
4. Write a note on variables, comments.
5. Explain data types of python.

12
13

You might also like