Python Programming BCC 302 Unit 1 Notes
Python Programming BCC 302 Unit 1 Notes
The initial version was published at the alt.sources news group in 1991, and version 1.0
was released in 1994.
Python 2.0 was released in 2000, and the 2.x versions were the prevalent releases until
December 2008.
At that time, the development team made the decision to release version 3.0, which
contained significant changes that were not backward compatible with the 2.x versions.
Features of Python
Python is Interpreted:
Many languages are compiled, meaning the source code you create needs to be
translated into machine code (the language of computer’s processor, before it can be
run).
This makes for a quicker development cycle because you just type in your code and run
it, without the intermediate compilation step.
One potential downside to interpreted languages is execution speed. Programs that are
compiled into the native language of the computer processor tend to run more quickly
than interpreted programs.
Python is Free:
Python is Portable:
Because Python code is interpreted and not compiled into native machine instructions,
code written for one platform will work on any other platform that has the Python
interpreter installed.
Expressive Language:
Python language is more expressive means that it is more understandable and readable
Object-Oriented Language:
Python supports object oriented language and concepts of classes and objects come into
existence.
Extensible:
It implies that other languages such as C/C++ can be used to compile the code and
thus it can be used further in our python code.
Integrated:
Python has a large and broad library and provides rich set of module and functions for
rapid application development.
To write and run Python program, we need to have Python interpreter installed in our
computer. IDLE (GUI integrated) is the standard, most popular Python development
Python scripts are just plain text, so you can edit them with any text editor.
Using whatever editor you’ve chosen, create a script file called hello.py containing the
following:
print(“Hello, World!”)
Now save the file, keeping track of the directory or folder you choose to save into.
Now open the Command Prompt and type the command like follow--
C:\Users\user\Documents\test>python hello.py
Hello, World!
C:\>python C:\Users\user\Documents\test\hello.py
Hello, World!
Go to the Start menu and select All Programs or All Apps. There should be a program
icon labeled IDLE (Python 3.x 32-bit) or something similar.
IDLE will open in interactive mode that means you can directly type the python
instructions it will evaluate immediately.
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
if (x < y)
if (x < y):
…. print(1) {
…. print(2)
…. print(3)
printf(“1”);
print(4) printf(“2”);
printf(“3”);
}
printf(“4”);
You have to use the same number of spaces in the same block of code
Python Comments
Comments can be used to explain Python code.
#This is a comment
print("Hello, World!")
#This is
#a comment
#multiline comment
print("Hello, World!")
The Programming Cycle for Python
Python's Programming cycle is dramatically shorter than that of traditional tools.
Because of this, Python programs run immediately after changes are made.
Output
NO
YES
NO YES
More
Finish
Inputs
Python Statement:
Expression:
(It is the object's address in memory and does not change once it has been
created.)
A value
>Type
Value
>
> Identity
x
=
1
Type (data type):
2
0
>
>
>i
Data Type can be one of the following:
Number
Number stores numeric values. Python creates Number objects when a number is
assigned to a variable.
Variables of numeric types are created when you assign a value to them
You can get the data type of any object by using the type() function:
a= 10 Output:
b = 27.88 <class 'int'>
c = 5j <class 'float'>
type(a) <class 'complex'>
type(b)
type(c)
i.e.
x= 1
y= 35656222554887711
z = -3255522
In Python 3, there is effectively no limit to how long an integer value can be. Of course,
it is constrained by the amount of memory your system has, as are all things, but
beyond that an integer can be as long as you need it to be:
The following strings can be prepended to an integer value to indicate a base other than
10:
Interpretatio
Prefix n Base Example
type(0b10)
<class 'int'>
type(0o10)
<class 'int'>
type(0x10)
<class 'int'>
x= 3+5j
y=5j
z = -5j
>>> 2+3j
(2+3j)
>>>type(2+3j)
<class 'complex'>
Boolean Type:
Python 3 provides a Boolean data type. Objects of Boolean type may have one of two
values, True or False (case sensitive).
>>>type((True)
<class 'bool'>
>>>type(False)
Floating-Point Numbers
The float type in Python designates a floating-point number. float values are specified
with a decimal point. Optionally, the character e or E followed by a positive or negative
integer may be appended to specify scientific notation:
>>> 4.2
4.2
>>> type(4.2)
<class 'float'>
>>> 4.
4.0
>>> .2
0.2
>>> .4e7
4000000.0
>>> type(.4e7)
<class 'float'>
>>> 4.2e-4
0.00042
NONE
We can assign None to any variable, but you can not create other NoneType objects.
All variables that are assigned None point to the same object.
Important Point
• None is not 0.
• Comparing None to anything will always return False except None itself.
Python List
List is an ordered sequence of items. It is one of the most used data type in Python and
is very flexible. All the items in a list do not need to be of the same type.
Declaring a list is pretty straight forward. Items separated by commas are enclosed
within brackets [ ].
We can use the slicing operator [ ] to extract an item or a range of items from a list.
Python string
String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
h e l l o w o r l d
0 1 2 3 4 5 6 7 8 9 10
Python Dictionary
Dictionary is an unordered collection of key-value pairs. It is generally used when we
have a huge amount of data. Dictionaries are optimized for retrieving data. We must
know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in the
form key: value. Key and value can be of any type.
We use key to retrieve the respective value. But not the other way around.
Python Set
Set is an unordered collection of unique items. Set is defined by values separated by
comma inside braces { }. Items in a set are not ordered.
We can perform set operations like union, intersection on two sets. Set have unique
values. They eliminate duplicates.
Since, set are unordered collection, indexing has no meaning. Hence the slicing
operator [] does not work.
Type Conversion
We can convert data types by using different type conversion functions like:
Conversion from float to int will truncate the value (make it closer to zero).
>>>int(10.6)
10
>>>int(-10.6)
10
>>>float('2.5')
2.5
>>>str(25)
'25'
>>>set([1,2,3])
{1, 2, 3}
>>>tuple({5,6,7})
(5, 6, 7)
>>>list('hello')
['h', 'e', 'l', 'l', 'o']
Python Operators
Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.
For example:
1. >>>2+3
2. 5
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the
output of the operation.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic operators
Operato
r Meaning Example
x+y
+ Add two operands or unary plus +2
x-y
- Subtract right operand from the left or unary minus -2
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right x/y)
Floor division - division that results into whole number adjusted to the left in the
// number line x // y
** Exponent - left operand raised to the power of right x**y (x to the power y)
Comparison operator
Comparison operators are used to comparing the value of the two operands and returns
boolean true or false accordingly. The comparison operators are described in the
following table.
Operato
r Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y
<= Less than or equal to - True if left operand is less than or equal to the right x <= y
Bitwise operators
Bitwise operators act on operands as if they were string of binary digits. It operates bit
by bit, hence the name.
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
Python language offers some special type of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values
(or variables) are located on the same part of the memory. Two variables that are equal
do not imply that they are identical.
Operat
or Meaning Example
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the x is not
is not same object) True
Membership operators
in and not in are the membership operators in Python. They are used to test whether
a value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operat Exampl
or Meaning e
Operator Description
** The exponent operator is given priority over all the others used in the
expression.
<= <>>= Comparison operators (less then, less then equal to, greater then, greater
*= **=