0% found this document useful (0 votes)
6 views6 pages

Python Programming Language I NCOE

Uploaded by

Roo Anu
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)
6 views6 pages

Python Programming Language I NCOE

Uploaded by

Roo Anu
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/ 6

Python Programming Language

 Python is a high-level, interpreted, interactive and object oriented programming language.


 Python is Interpreted: This means that code is translated at runtime by the interpreter.
 Python is Interactive: This means that you can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented: This means that Python supports Object-Oriented technique of programming that
encapsulates code and data within objects.
Python 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.
 Class names start with an uppercase letter and all other identifiers with a lowercase letter.

Reserved Words:
The following list shows the reserved words in Python. These reserved words may not be used as constant or
variable or any other identifier names. Keywords contain lowercase letters only.

and not or break for class continue


global def if return del import elif
in while else is

Comments in Python:
A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and up to the physical
line end are part of the comment, and the Python interpreter ignores them.
# Created by Saman Perera

Operators in Python
Python language supports following type of operators.
 Arithmetic Operators
 Comparison Operators
 Logical (or Relational) Operators
 Assignment Operators
 Bitwise Operators

Python Arithmetic Operators:

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus - Divides left hand operand by right hand operand and returns remainder
** Exponent - Performs exponential (power) calculation on operators
// Floor Division - The division of operands where the result is the quotient in which the digits
after the decimal point are removed.

1 Prepared by Sisira Palihakkara


Python Comparison Operators:
Operator Description Example
== equal to
!= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to

Python Assignment Operators:


Operator Description Example
= Simple assignment operator c=a+b
+= Add AND assignment operator c += a
-= Subtract AND assignment c -= a
*= Multiply AND assignment c *= a
/= Divide AND assignment operator c /= a
%= Modulus AND assignment c %= a
**= Exponent AND assignment c **= a
//= Floor Division and assignment c //= a
Python Bitwise Operators:
Bitwise operator works on bits and performs bit by bit operation.

Operator Description Example


& Binary AND Operator. 240 & 63
| Binary OR Operator.
^ Binary XOR Operator.
~ Binary Ones Complement.
<< Binary Left Shift Operator.
>> Binary Right Shift Operator.

Python Logical Operators:


Operator Description Example
and Logical AND operator. mark=-10
mark>=0 and mark<=100
or Logical OR Operator. mark<0 or mark>100
not Logical NOT Operator. age=15
not age>20

2 Prepared by Sisira Palihakkara


Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation
~ complement
* / % // Multiply, divide, modulo and floor division
+ - Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
== != Equality operators
= += *= ……….. Assignment operators
not or and Logical operators

Python Variables

 Variables are reserved memory locations to store values.


 When you create a variable you reserve some space in memory. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory.
 By assigning different data types to variables, you can store integers, decimals, or characters in these
variables.

Assigning Values to Variables:


 Python variables do not have to be explicitly declared to reserve memory space.
 The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.

Examples:
counter = 100
miles = 1000.0
name = "Saman"

Multiple Assignments:
You can also assign a single value to several variables simultaneously. For example:
a = b = c = 10
Here all three variables are assigned to the same memory location.
You can also assign multiple objects to multiple variables. For example:

a, b, c = 1, 2.5, "ICT"
a,b=b,a

3 Prepared by Sisira Palihakkara


Standard Data Types:
The data stored in memory can be of many types. Python has some standard types that are used to define the
operations possible on them and the storage method for each of them. Python has five standard data types:
 Numbers
 String
 List
 Tuple
 Dictionary

Numbers (Numeric data type)


There are 3 types of numbers
Integers Floats Complex
Decimal 19 25.125 25+15j
Binary 0b11011
Octal 0o312 3.75e+15 3.75X1015
Hexa 0xF45A
1.25e-10  1.25X10-10

Python Strings:
 Strings in Python are identified as a contiguous set of characters in between quotation marks.
 Python allows for either pairs of single (‘) or double quotes (“).
 Each character is identified by an unique integer called index starting from 0
st=’computer’
c o m p u t e r
0 1 2 3 4 5 6 7
.. … … … -4 -3 -2 -1
 Subsets of strings can be taken using the slice operator ( [ ] and [ : ] ) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
 The plus ( + ) sign is the string concatenation operator.
 The asterisk ( * ) is the repetition operator.

Lists
 Lists are the most versatile of Python's compound data types.
 A list contains items separated by commas and enclosed within square brackets ([]).
list1=*10,5.25,4+3j,’ICT’,*4,7++
 Each item is identified by a list index

10 5.25 4+3j ‘ICT’ [4,7]


0 1 2 3 4
.. … … -2 -1

 All the items belonging to a list can be of different data type.


 The values stored in a list can be accessed using the slice operator ( [ ] and [ : ] ) with indexes.
 The plus ( + ) sign is the list concatenation operator, and the asterisk ( * ) is the repetition operator.

Lists are mutable objects. Once we defined a list we can modify it.

Python Tuples:
 A tuple is another sequence data type that is similar to the list.
 A tuple consists of a number of values separated by commas enclosed within parentheses.
 Tuples can be thought of as read-only lists because they cannot be updated.
 Tuples are immutable objects.
data=(5,5.25,’DBMS’,*4,7+,(3,5))

4 Prepared by Sisira Palihakkara


Python Dictionary:
 Python 's dictionaries consist of key-value pairs.
 Keys can be numbers or strings.
 Values, on the other hand, can be any Python object.
 Dictionaries are enclosed by curly braces ( { } ) and values can be assigned and accessed using square braces (
[] ).
 Dictionaries have no concept of order among elements. The elements are simply unordered.
data=,‘Saman’:56, ‘Ruwan’:60-

Data Type Conversion:


Sometimes you may need to perform conversions between the built-in types. To convert between types you simply
use the type name as a function. There are several built-in functions to perform conversion from one data type to
another. These functions return a new object representing the converted value.

Function Description

int(x [,base]) Converts x to an integer. base specifies the base if x is a string.


float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
chr(x) Converts an integer to a character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.

Built-in List Methods


Methods with Description
list.append(obj) Appends object obj to list

list.count(obj) Returns count of how many times obj occurs in list


list.extend(seq) Appends the contents of seq to list

list.index(obj) Returns the lowest index in list that obj appears

list.insert(index, obj) Inserts object obj into list at offset index

list.pop(obj=list[-1]) Removes and returns last object or obj from list


list.remove(obj) Removes object obj from list

list.reverse() Reverses objects of list in place


list.sort([func]) Sorts objects of list, use compare func if given

5 Prepared by Sisira Palihakkara


Built-in Dictionary Methods

Methods with Description

dict.clear() Removes all elements of dictionary dict

dict.copy() Returns a shallow copy of dictionary dict

dict.get(key, default=None) For key key, returns value or default if key not in dictionary
dict.items() Returns a list of dict's (key, value) tuple pairs

dict.keys() Returns list of dictionary dict's keys

dict.update(d) Adds dictionary dict2's key-values pairs to dict

dict.values() Returns list of dictionary values

Write the return value of following function calls

bin(255) list(range(5))
bin(255)[2:] list(range(1,5))

chr(65) list(range(5,0,-1))
chr(3461) list(range(20,0,-5))

chr(0x0d85) list(range(5,1))

float('0025.3600') str(25)
float('002.536e+5') str(0b1111)

hex(255) str(2.5e+3)

hex(0b01111110) str(0b1111)[-1]*3

int('0001230') int(str(0b1111)[-1])*5
int('123',16) sum([5,6,7,2])

int('1111',2) sum({1:2,3:4})
len('computer') tuple('ICT')
len([5,6,7,9]) type(2.0)

list('ICT') type([2])

list({1:2,3:4}) type((2,))

oct(255) ord('A')

oct(0b11111) list(range(5))

6 Prepared by Sisira Palihakkara

You might also like