0% found this document useful (0 votes)
4K views

Python Programming Unit 1 Notes

Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Uploaded by

Atebar Haider
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4K views

Python Programming Unit 1 Notes

Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in the Netherlands.

Uploaded by

Atebar Haider
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Python Introduction

Python is a high-level, interpreted scripting language developed in the late 1980s by Guido van
Rossum at the National Research Institute for Mathematics and Computer Science in the
Netherlands.

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).

Programs written in an interpreted language are passed straight to an interpreter that runs them
directly.

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:

The Python interpreter is developed under an OSI-approved open-source license, making it free to
install, use, and distribute, even for commercial purposes.

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.

GUI Programming Support:

Graphical user interfaces can be developed using Python.

Integrated:

It can be easily integrated with languages like C, C++, JAVA etc.

Large Standard Library:

Python has a large and broad library and provides rich set of module and functions for rapid
application development.

Interacting with Python


A program is a sequence of instructions that specifies how to perform a Computation. The
Computation might be mathematical or working with text.

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

environment. IDLE is an acronym of Integrated Development and Learning Environment.

Interacting with
Python

Using the Python


Interpreter Interactively
Interacting with Python through an
IDE
Running a Python Script from
the Command Line
Running a Python Script from the Command Line
A Python script is a reusable set of code. It is essentially a Python contained in a file. You can run the
program by specifying the name of the script file to the interpreter.

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!

You can give the file path if directory is not same--

C:\>python C:\Users\user\Documents\test\hello.py

Hello, World!

Interacting with Python through an IDE


IDLE (Integrated Development and Learning Environment):

Most Python installations contain a rudimentary IDE called IDLE.

Starting IDLE in Windows

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.

For writing python script, follow the steps given bellow:

• Open a new file by clicking on File->New File

• Write your python code

• Save it as .py extension

• Click on Run->Run Module or press F5

• Output will be shown to the Python Shell


Python Indentation
Indentation refers to the spaces at the beginning of a code line.

Python uses indentation to indicate a block of code.

In C, Java, C# and other language we uses { } to Indicate the Block of Code

if (x < y)
if (x < y):
…. print(1) {
…. print(2) printf(“1”);
…. print(3)
print(4) printf(“2”);
printf(“3”);
}
printf(“4”);

Python will give you an error if you skip the indentation:

The number of spaces is up to you as a programmer, but it has to be at least one.

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.

Comments can be used to make the code more readable.

Comments can be used to prevent execution when testing code.

Comments starts with a # symbol

#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line

print("Hello, World!") #This is a comment

To add a multiline comment you could insert a # for each line

#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.

In Python, there are no compile or link steps.

Because of this, Python programs run immediately after changes are made.

Write / Edit the


Program

Test the Program with Inputs

Output
NO

YES

NO YES
Finish More Inputs

1. Write your Program or Edit.

2. Run Program on some Inputs (Test Case)

3. If Output is not correct go to step 1

4. Repeat the step 2 and 3 for all possible test cases


Elements of Python
A Python program is a sequence of Definitions and Commands (Statements). Commands
manipulateObjects. Each Object is associated with a Type.

Python Statement:

An statement is a syntactic unit of a program that expresses some action to be carried out. A


statement may have internal components (e.g., expressions). Statements are the instructions that a
Python interpreter can execute.

Expression:

Expression in a Python language is a combination of one or more objects, operators,


and functions that the Python interprets and computes to produce another value.

Variables and Types


Data type in any language is a classification that defines the format and type of data. Python uses
objects to capture data, which then can be manipulated by programs to provide information.

Every object has following:

An Identity, - can be known using id (object) function.

(It is the object's address in memory and does not change once it has been created.)

A type – can be checked using type (object) function

A value

>>> x=120
>>>id(x)
1820061472 Identity
>>>type(x)
<class 'int'> Type
>>>x(data type):
Type
120 Value
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.

Python supports 3 types of numeric data.

1.int 2. float 3. complex

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)

Data Type – Number - (int)

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

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:

Prefix Interpretation Base Example

0b (zero + lowercase letter 'b') Binary 2 print(0b10)


0B (zero + uppercase letter 'B')
2

type(0b10)

<class 'int'>

0o (zero + lowercase letter 'o') Octal 8 print(0o10)


0O (zero + uppercase letter 'O')
8

type(0o10)

<class 'int'>

0x (zero + lowercase letter 'x') Hexadecimal 16 print(0x10)


0X (zero + uppercase letter 'X')
16

type(0x10)

<class 'int'>

Data Type – Number - (complex)

Complex numbers are specified as <real part>+<imaginary part>j. For example:

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)
<class 'bool'>
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

The None keyword is used to define a null variable or an object. In Python, None keyword is an


object, and it is a data type of the class NoneType.

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 the same as False.

• None is not 0.

• None is not an empty string.

• 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.

Index starts form 0 in Python.


Python Tuple
Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable.
Tuples once created cannot be modified.
Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically.
It is defined within parentheses () where items are separated by commas.
We can use the slicing operator [] to extract items but we cannot change its value.

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:

int(), float(), str(), list(), tuple() etc.

Conversion from float to int will truncate the value (make it closer to zero).

>>>int(10.6)
10
>>>int(-10.6)
10

Conversion to and from string must contain compatible values.

>>>float('2.5')
2.5
>>>str(25)
'25'
We can even convert one sequence to another.

>>>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.

Python provides a variety of operators described as follows.

o Arithmetic operators

o Comparison operators

o Assignment Operators

o Logical Operators

o Bitwise Operators

o Membership Operators

o Identity Operators
Arithmetic operators

Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication etc.

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

* Multiply two operands x*y

/ 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

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal 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.

For example, 2 is 10 in binary and 7 is 111.


In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)

Operator Meaning Example

& Bitwise AND x& y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x>> 2 = 2 (0000 0010)

<< Bitwise left shift x<< 2 = 40 (0010 1000)


Assignment operators

Assignment operators are used in Python to assign values to variables.

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.

Operator Example Equivatent to

= 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

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

Special operators
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.

Operato
r Meaning Example

is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not 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.

Operato
r Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x


Operator Precedence

The precedence of the operators is important to find out since it enables us to know which operator
should be evaluated first. The precedence table of the operators in python is given below.

Operator Description

** The exponent operator is given priority over all the others used in the

expression.

~+- The negation, unary plus and minus.

* / % // The multiplication, divide, modules, reminder, and floor division.

+- Binary plus and minus

>><< Left shift and right shift

& Binary and.

^| Binary xor and or

<= <>>= Comparison operators (less then, less then equal to, greater then, greater

then equal to).

<> == != Equality operators.

= %= /= //= -= += Assignment operators

*= **=

is is not Identity operators

in not in Membership operators

not or and Logical operators

You might also like