0% found this document useful (0 votes)
3 views

Unit-1 Program Notes

The document provides an overview of Python, highlighting its features such as ease of coding, being free and open-source, high-level, interpreted, and object-oriented. It discusses Python's applications, limitations, development cycle, and various Integrated Development Environments (IDEs) available for Python programming. Additionally, it covers fundamental concepts like identifiers, variables, data types, and basic syntax rules in Python.

Uploaded by

mrai48851
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-1 Program Notes

The document provides an overview of Python, highlighting its features such as ease of coding, being free and open-source, high-level, interpreted, and object-oriented. It discusses Python's applications, limitations, development cycle, and various Integrated Development Environments (IDEs) available for Python programming. Additionally, it covers fundamental concepts like identifiers, variables, data types, and basic syntax rules in Python.

Uploaded by

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

UNIT-I

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.

THE PROGRAMMING CYCLE FOR PYTHON


Python's development cycle is dramatically shorter than that of traditional tools. In Python,
there are no compile or link steps -- Python programs simply import modules at runtime and
use the objects they contain. Because of this, Python programs run immediately after changes
are made. And in cases where dynamic module reloading can be used, it's even possible to
change and reload parts of a running program without stopping it at all. Because Python is
interpreted, there's a rapid turn around after program changes. And because Python's parser is
embedded in Python-based systems, it's easy to modify programs at runtime.
Development Cycle
PYTHON IDE
IDE stands for Integrated Development Environment is defined as a coding tool that helps to
automate the process of editing, compiling, testing, etc. in a Software Development Life Cycle
(SDLC) and it provides ease to the developer to run, write and debug the code.
It is specially designed for software development that consists of several tools which is used
for developing and testing the software.

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.

Rule 1 Name consist of alphanumeric, numbers or special symbols or combination of these.


Example - abc _abc a,b 1ab a12 for if a_b a b

Rule 2 Name must start with either alpha or _


Example- abc _abc

Rule 3 No special symbol other than _ is allowed


Example- abc _abc

Rule 4 Keywords are not allowed like for , if, etc.


VARIABLE
Variables are containers for storing data values. Python has no command for declaring a
variable. A variable is created the moment you first assign a value to it. Variables do not need
to be declared with any particular type, and can even change type after they have been set.

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

However, the following block generates an error

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

MULTIPLE STATEMENTS IN A SINGLE LINE


The semicolon ( ; ) allows multiple statements on a single line to separate multiple statements.
Example
a=5
b=6
c=a+b
This can be written by using multiple statement in a single line
a=5; b=6; c=a+b

MULTIPLE STATEMENT GROUPS AS SUITES IN PYTHON


Groups of individual statements, which make a single code block are called suites in Python. Compound
or complex statements, such as if, while, def, and class require a header line and a suite. Header lines
begin the statement (with the keyword) and terminate with a colon ( : ) and are followed by one or more
lines which make up the suite. For example –
if expression :
suite
elif expression :
suite
else :
suite
COMMAND LINE ARGUMENT
Python provides a getopt module that helps you parse command-line options and arguments.
$ python test.py arg1 arg2 arg3
The Python sys module provides access to any command-line arguments via the sys.argv. This
serves two purposes-

 sys.argv is the list of command-line arguments.

 len(sys.argv) is the number of command-line arguments.


Here sys.argv[0] is the program i.e. the script name.

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

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data type.
<required_datatype>(expression)
Example
num_int = 123
num_str = "456“
num_str = int(num_str)
num_sum = num_int + num_str
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.

DIFFERENT TYPES OF OPERATORS USED IN PYTHON


Python language supports the following types of operators-
 Arithmetic Operators
 Comparison (Relational) Operators

 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

Python Comparison Operators


These operators compare the values on either side of them and decide the relation among them.
They are also called Relational operators. Assume variable a holds the value 10 and variable b
holds the value 20, then
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then
Python Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b =
13; Now in binary format they will be as follows-

Python Logical Operators


The following logical operators are supported by Python language. Assume variable a holds True and
variable b holds False then
Python Membership Operators
Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below Operator Description
Explained below

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below:
PRECEDENCE OF AN OPERATOR
Precedence of an operator means in which order operator is evaluated. The operator that has
high precedence is evaluated first.
Associativity
 Whenever two or more operators have the same precedence, then associativity defines
the order of operations.
 The associativity is the order in which Python evaluates an expression containing
multiple operators of the same precedence.
 Almost all operators except the exponent (**) support the left-to-right associativity.
Example 1:
print(4 * 7 % 3)
o/p ((4*7)%3)
(28%3)
1
Example 2: Right to left
print(2 ** 3 ** 2)
Output
512

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

3.Write a Python program to take the temperature in Celsius and convert it to


Fahrenheit.
celsius=int(input("Enter the temperature in celcius:"))
f=(celsius*1.8)+32
print("Temperature in fahrenheit is:",f)

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

You might also like