Unit-1 Program Notes
Unit-1 Program Notes
PYTHON
Python is a popular programming language. It was created by Guido van Rossum, and released
in 1991.
FEATURES OF PYTHON
1. Easy
When we say the word ‘easy’, we mean it in different contexts.
a. Easy to Code
As we have seen in earlier lessons, Python is very easy to code. Compared to other popular
languages like Java and C++, it is easier to code in Python. Anyone can learn Python syntax in
just a few hours.
b. Easy to Read
Being a high-level language, Python code is quite like English. Looking at it, you can tell what
the code is supposed to do. Also, since it is dynamically-typed, it mandates indentation. This
aids readability.
2.Free and Open-Source
Firstly, Python is freely available. You can download it from the Python Website.
3.High-Level
It is a high-level language. This means that as programmers, we don’t need to remember the
system architecture. Nor do we need to manage the memory. This makes it more programmer-
friendly and is one of the key python features.
4.Interpreted
If you’re familiar with any languages like C++ or Java, you must first compile it, and then run
it. But in Python, there is no need to compile it. Internally, its source code is converted into an
immediate form called bytecode. So, all you need to do is to run your Python code without
worrying about linking to libraries, and a few other things.
5.Object-Oriented
A programming language that can model the real world is said to be object-oriented. It focuses
on objects and combines data and functions. Contrarily, a procedure-oriented language
revolves around functions, which are code that can be reused. Python supports both procedure-
oriented and object-oriented programming which is one of the key python features.
6.Extensible
If needed, you can write some of your Python code in other languages like C++. This makes
Python an extensible language, meaning that it can be extended to other languages.
7.Large Standard Library
Python downloads with a large library that you can use so you don’t have to write your own
code for every single thing. There are libraries for regular expressions, documentation-
generation, and a lot of other functionality.
8.Dynamically Typed
Python is dynamically-typed. This means that the type for a value is decided at runtime, not in
advance. This is why we don’t need to specify the type of data while declaring it.
APPLICATION OF PYTHON
Desktop GUIs
Software Development
Web and Internet Development
Business Applications
BitTorrent, YouTube, Dropbox, Cinema4D are a few globally used applications based on
Python
LIMITATIONS
Parallel processing can be done in Python but not elegantly as done in some other
languages (like JavaScript)
Being an interpreted language, Python is slow as compared to C/C++.
It has limited commercial support point
Python is slower than C/C++ when it comes to computation of heavy tasks and
development applications.
There are so many Python IDEs available but few of them are listed below,
PyCharm - It is the most widely used IDE and available in both paid version and free open-
source as well. It is a complete python IDE that is loaded with a rich set of features like auto
code completion, quick project navigation, fast error checking and correction, remote
development support, database accessibility, etc.
Spyder - Spyder is an open-source that has high recognition in the IDE market and most
suitable for data science. The full name of Spyder is Scientific Python Development
Environment. It supports all the significant platforms Linux, Windows, and MacOS X. It
provides a set of features like localized code editor, document viewer, variable explorer,
integrated console, etc. and supports no. of scientific modules like NumPy, SciPy, etc.
Jupyter Notebook- Jupyter is one of the most used IPython notebook editors that is used across
the Data Science industry. It is a web application that is based on the server-client structure and
allows you to create and manipulate notebook documents. It makes the best use of the fact that
python is an interpreted language.
Thonny- Thonny is another IDE which is best suited for learning and teaching programming.
It is a software developed at the University of Tartu and supports code completion and highlight
syntax errors.
Microsoft Visual Studio - Microsoft Visual Studio is an open-source code editor which was
best suited for development and debugging of latest web and cloud projects. It has its own
marketplace for extensions.
IDENTIFIER
Identifier is a group of characters and it is used for naming the variable, function, list, etc.
Python is a case sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python.
Example
x= 5
y= "John"
print(x)
print(y)
Output
5
John
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) Output # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
You can get the data type of a variable with the type() function.
Example
type('Hello’)
Output
<class ‘str’>
INDENTATION
Python does not use braces ({}) to indicate blocks of code for class and function definitions or flow
control. Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces
in the indentation is variable, but all statements within the block must be indented the same amount.
For example-
if True:
print ("True")
else:
print ("False")
if True:
print ("Answer")
print ("True")
else:
print "(Answer")
print ("False")
Thus, in Python all the continuous lines indented with the same number of spaces would form a block.
LINE CONTINUATION CHARACTER
Statements in Python typically end with a new line. Python, however, allows the use of the line
continuation character (\) to denote that the line should continue.
For example
total = item_one + \
item_two + \
item_three
The statements contained within the [], {}, or () brackets do not need to use the line
continuation character.
For example
days = ['Monday', 'Tuesday', 'Wednesday',
'Thursday', 'Friday']
DIFFERENT QUOTATION
Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals. The
triple quotes are used to span the string across multiple lines.
For example
1. ‘ram’
2. “ram”
3. “‘ ram
is
good ”’
COMMENTS
A hash sign (#) that is not inside a string literal is the beginning of a comment. All characters
after the #, up to the end of the physical line, are part of the comment and the Python interpreter
ignores them.
#!/usr/bin/python3
# First comment
print ("Hello, Python!") # second comment
OUTPUT
Hello, Python!
You can type a comment on the same line after a statement or expression
Example
name = "Madisetti" # This is again comment
Python have multiple-line commenting feature. ‘’’ ‘’’is used for multi line comments.
Example
‘’’This is a comment.
This is a comment, too.
This is a comment, too. I said that already’’’
Example :
Consider the following script test.py-
#!/usr/bin/python3
import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))
Now run the above script as follows –
$ python test.py arg1 arg2 arg3
This produces the following result
Number of arguments: 4 arguments.
Argument List: ['test.py', 'arg1', 'arg2', 'arg3']
MULTIPLE ASSIGNMENT
Python allows you to assign a single value to several variables simultaneously.
For example
a=b=c=1
Here, an integer object is created with the value 1, and all the 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, "john"
Here, two integer objects with values 1 and 2 are assigned to the variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
DATA TYPES USED IN PYTHON
A data type is a classification of data which tells the compiler or interpreter how the
programmer intends to use the data. The data stored in memory can be of many types. For
example, a person's age is stored as a numeric value and his or her address is stored as
alphanumeric characters. Python has various standard data types that are used to define the
operations possible on them and the storage method for each of them.
Python has following data types-
Numbers
String
List
Tuple
Dictionary
Boolean
Numbers :
Number data types store numeric values. Number objects are created when you assign a value
to them. For example
var1 = 1
var2 = 10
Python supports three different numerical types –
int (signed integers)
float (floating point real values)
complex (complex numbers)
Strings:
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows either pair of single or double quotes. 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 to the end. The plus (+) sign is the string concatenation operator and
the asterisk (*) is the repetition operator.
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
This will produce the following result
Hello World!
H
Llo
llo World!
Hello World!Hello World!
Hello World!TEST
Lists:
Lists are the most versatile of Python's compound data types. A list contains items separated
by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays
in C. One of the differences between them is that 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 starting at 0 in the beginning of the list and working their way to end -1. The
plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.
For example-
#!/usr/bin/python3
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3 rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
This produces the following result-
['abcd', 786, 2.23, 'john', 70.200000000000003]
Abcd
[786, 2.23]
[2.23, 'john', 70.200000000000003]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']
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. Unlike lists, however, tuples are enclosed within parenthesis. The
main difference between lists and tuples is- Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot
be updated. Tuples can be thought of as read-only lists.
For example-
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3 rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
This produces the following result-
('abcd', 786, 2.23, 'john', 70.200000000000003)
Abcd
(786, 2.23)
(2.23, 'john', 70.200000000000003)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')
Dictionary:
Python's dictionaries are kind of hash-table type. They work like associative arrays or hashes
found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type,
but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python
object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]).
For example-
dict = {} dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
This produces the following result
This is one
This is two
{'dept': 'sales', 'code': 6734, 'name': 'john'}
['dept', 'code', 'name']
['sales', 6734, 'john']
Boolean
In programming you often need to know if an expression is True or False. You can evaluate
any expression in Python, and get one of two answers, True or False. When you compare two
values, the expression is evaluated and Python returns the Boolean answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output
True
False
False
TYPE CONVERSION
The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion. Python has two types of type conversion.
Implicit Type Conversion
Explicit Type Conversion
Implicit Type Conversion
In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.
For Example
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
Output
Num_new=124.23
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Python Arithmetic Operators
Assume variable a holds the value 10 and variable b holds the value 21, then Operator
Description Example
PROGRAMS
1.Write a python program to exchange (swapping) the values of two numbers without
using a temporary variable.
a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: "))
a,b=b,a
print('a is:',a,'b is:',b)
OUTPUT
Enter value of first variable: 3
Enter value of second variable: 5
a is: 5 b is: 3
2.Write a Python program to exchange (swapping) the values of two numbers with using
a temporary variable.
a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: "))
c=a
a=b
b=c
print('a is:',a,'b is:',b)
OUTPUT
Enter value of first variable: 2
Enter value of second variable: 7
a is: 7 b is: 2
OUTPUT
Enter the temperature in celcius:50
Temperature in fahrenheit is: 122.0
4.Write a Python program to read two numbers and print their quotient and remainder.
a=int(input("Enter the first number: "))
b=int(input("Enter the second number: "))
quotient=a//b
remainder=a%b
print("Quotient is:",quotient)
print("Remainder is:",remainder)
OUTPUT
Enter the first number: 10
Enter the second number: 20
Quotient is: 0
Remainder is: 10
5. Write a Python program to find the area of a triangle given all three sides.
import math
a=int(input("Enter first side: "))
b=int(input("Enter second side: "))
c=int(input("Enter third side: "))
s=(a+b+c)/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
print("Area of the triangle is: ",round(area,2))
OUTPUT
Enter first side: 5
Enter second side: 6
Enter third side: 7
Area of the triangle is: 14.7
6.Write a Python program to read height in centimeters and then convert the height to
feet and inches
cm=int(input("Enter the height in centimeters:"))
inches=0.394*cm
feet=0.0328*cm
print("The length in inches",round(inches,2))
print("The length in feet",round(feet,2))
OUTPUT
Enter the height in centimeters:54
The length in inches 21.28
The length in feet 1.77
7. Write a Python program to compute simple interest given all the required values.
principle=float(input("Enter the principle amount:"))
time=int(input("Enter the time(years):"))
rate=float(input("Enter the rate:"))
simple_interest=(principle*time*rate)/100
print("The simple interest is:",simple_interest)
OUTPUT
Enter the principle amount:100.53
Enter the time(years):2
Enter the rate:5.3
The simple interest is: 10.656179999999999