0% found this document useful (0 votes)
50 views22 pages

Unit 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views22 pages

Unit 3

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Unit-3

Overview of Programming: Structure of a Python Program, Elements of Python Introduction to Python:


Python Interpreter, Using Python as calculator, Python shell, Indentation. Atoms, Identifiers and keywords,
Literals, Strings, Operators (Arithmetic operator, Relational operator, Logical or Boolean operator,
Assignment, Operator, Ternary operator, Bit wise operator, Increment or Decrement operator)
Python Program:
Python is an interpreter, object-oriented, general purpose, dynamically typed and high-level programming
language. Its high-level built in data structures, combined with dynamic typing and dynamic binding; make it
very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect
existing components together.
Python supports modules and packages, which encourages program modularity and code reuse.
The Python interpreter and the extensive standard library are available in source or binary form without charge
for all major platforms, and can be freely distributed.
Python is a popular programming language. It was created by Guido Van Rossum in Netherland and released in
1991.
Use of Python
 web development (server-side),
 software development,
 mathematics,
 System scripting.
What can Python do?
 Python can be used on a server to create web applications.
 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This
means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.
Installation of Python
To install python on windows environment we have to follow the following steps:
1. Open any browser and type ‘download python’ then hit enter
2. Click on the official site of python
3. Click on the download button
4. On the left bottom of the window python is already downloaded and click on that
5. Then out of two options click on install now option
6. Then click on ‘YES’ to give permission for installation.
7. After few a time the installation process completed and then clicks on close button.
How to open to write program:
1. Open command prompt by typing “cmd”
2. To check whether python is installed successfully or not type ‘py’ and then press enter.
Python 3.10.4 indicates successful installation of python.
3. This ‘>>>’ is known as python shell. Here we can write and execute python code.
But here only single statement can be written, a block of code cannot be written for execution.
4. One more thing is there to execute python program that is IDLE means ‘Integrated Development
Learning Environment’
5. Open IDLE, then IDLE Shell will be open , to write multiline program:
Go to file menu and click on new file option or use ‘ctrl + N’ from keyboard
6. Now an editor will be available to write code.
How to execute
1. After writing the code save the file using file extension ‘.py’ with file name
2. Then to execute the code: click on ‘Run’ menu, then click on ‘Run module’ option
or press ‘F5’ from keyboard to execute the program.

Python Interpreter
Python is a high level language. We know that computer understand only machine language or binary language
which is also known as low level language. The job to translate programming code written in high level
language to low level language is done with the help of Translator. The mostly used translators are compiler
and interpreter.
Working of Compiler
Compiler is a special type of software, it first checks the source code of the complete program for the syntax
errors, if no error found in the program code then the source code of the program is converted to the machine
code and finally the executive file of the program is created. The executive file can be executed by the CPU and
can produce desired result as per the program requirements.

Source Code Compiler Machine Code

Working of Interpreter
The Python interpreter first reads the command, then evaluates the command, prints the results, and then again
loops it back to read the next command and because of this only Python is known as REPL i.e., (Read, Evaluate,
Print, Loop).
Interpreter check the code of program line by line if no error is found it is converted into the machine code and
simultaneously gets executed by the CPU.

Program Machine language Computer


Interpreter
Statement statement System
Translation Statement
Execution
An interpreter is a computer program, which coverts each high-level program statement into the machine code.
This includes source code, pre-compiled code, and scripts. Both compiler and interpreters do the same job.
Both compiler and interpreter convert higher level programming language to machine code. However, a
compiler will convert the code into machine code (create an exe) before the program run. Interpreters convert
code into machine code when the program runs.

Python shell
Python provides a Python Shell, which is used to execute a single Python command and display the result.
The three arrow symbols >>> seen in the command prompt is known as the Shell. It is also known as python
REPL (Read, Evaluate, Print, Loop), where it reads the command, evaluates the command, prints the result, and
loop it back to read the next command again.
The Python REPL shows three arrow symbols >>> followed by a blinking cursor. Programmers type commands
at the >>> prompt then hit [ENTER] to see the results. Commands written into the python Shell/ REPL are read
by the interpreter and results of running the commands are evaluated, and then printed to the command window.
After output is printed, the >>> prompt appears on a new line. This process repeats over and over again in
continuous loop.

Python as a Calculator
Python can be used as a calculator to compute arithmetic operations like addition, subtraction, multiplication
and division. Python can also be used for trigonometric calculations and statistical calculations.
Simple calculations can be completed at the Python Prompt.
Let’s try some commands at the Python REPL :

Arithmetic calculation
>>> 5 + 3
8
>>> 8 - 1.5
6.5
>>>5000 / 2500
2.0 // always returns decimal value
>>> 5 * 2
10
>>> 3 ** 2 // the double asterisk symbol ** to raise a number to a power.
9
>>> 2 * 5
10
>>> _ + 1.5 + 1 // the answer of an operation Python saves as an underscore’ _’ to use in
12.5 // our next operation.
Trigonometry calculation
Trigonometry functions such as sine, cosine, and tangent can also be calculated using the Python REPL.
To use Python's trig functions, we need to introduce a new concept: importing modules.
In Python, there are many operations built into the language when the REPL starts. These include + , -, *, / as we saw in
the previous section. However, not all functions will work right away when Python starts.
Suppose we want to find the sin of an angle.
Try the following:
>>> sin(60)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
sin(60)
NameError: name 'sin' is not defined. Did you mean: 'bin'?
This error results because we have not told Python to include the sin function. The sin function is part of
the Python Standard Library. The Python Standard Library comes with every Python installation and includes
many functions, but not all of these functions are available to us when we start a new Python REPL session. To
use Python's sin function, first we have to import the sin function from the math module which is part of the
Python Standard Library.
So to find sin of an angle we have to use the following syntax:
from module import function

To import the sin() function from the math module try:


>>> from math import sin
>>> sin(60)
Op:
-0.3048106211022167

Multiple modules can also be imported at the same time.

We can import more than one function at the same time using the following syntax:
from module import function1, function2, function3

Example:

>>> from math import sin, cos, tan, pi


>>> pi
3.141592653589793
>>> sin(pi/6)
0.49999999999999994
>>> cos(pi/6)
0.8660254037844387
>>> tan(pi/6)
0.5773502691896257
Atom
Atom is a free, open-source, and multi-platform text and source code editor or IDE which
supports NodeJS developed packages and embedded GIT control [GIT is a flexible source control tool]. Most of the
extending packages are freely available and developed by open-source communities. Atom IDE is based on
Electron Framework (previously called Atom Shell). The electron framework allows the developers to use the
desktop application on multiple platforms such as Linux, MacOS, and Windows, with the help of NodeJS and
Chromium. Atom IDE is written in Less and CoffeeScript, developed and maintained by GitHub.
Atom Text Editors is also known as Hackable Text Editor for the Twenty-First Century by its developers and is
fully customizable in HTML, JavaScript, and CSS.
Code Execution in Atom Python
Generally, we use the command prompt or terminal to execute Python programs. However, Atom provides a
plugin known as platformio-ide-terminal in order to execute the python code. We can set up this plugin by
navigating to the File in the Menu bar. Go to Settings. Click on Install Tab. Now, in the search bar, search and
install the platformio-ide-terminal plugin. We can use the above method in order to install other packages,
plugins as well as themes.
Structure of a Python Program
The typical structure of a python program include 3 parts
Import statements // import statements are used to include library files to the python program
Function definitions //This section include the definitions of various functions written in a Python Program
Program statements // this section include the set of statements for solving the given problem.

Python Statement
Instructions that a Python interpreter can execute are called statements.
For example: a = 1, is an assignment statement.
if statement, for statement, while statement, etc. are other kinds of statements.
 We can make a statement extend over multiple lines with the line continuation character (\).
For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation.
 In Python, line continuation is implied inside parentheses ( ), brackets [ ], and braces { }.
For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly.
Same is the case with [ ] and { }.
For example:
colors = ['red',
'blue',
'green']
 We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Indentation
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a statement. The
statements with the same indentation belong to the same group.
Python indentation uses to define the block of the code.
The other programming languages such as C, C++, and Java use curly braces {}, whereas Python uses an
indentation.
Indentation uses at the beginning of the code and ends with the unintended line.
That same line indentation defines the block of the code (body of a function, loop, etc.)
for i in range(5):
print(i)
if(i == 3):
break
To indicate a block of code we indented each line of the block by the same whitespaces.
For Example
a=2
print(a)
if a==3 :
print(“hello world”)
print(“HELLO WORLD”)
else :
print(“ bye world”)
print(“ BYE WORLD”)
Python Comments
Python Interpreter ignores comments.
Comments are very important while writing a program.
Comments are for programmers to better understand a program.
For example,
We might forget the key details of the program we just wrote in a month's time. So taking the time to explain
these concepts in the form of comments is always fruitful.

In Python, we use the hash (#) symbol for single-line cmment


It extends up to the newline character.
.#This is a comment
print('Hello')
Multi-line comments
We can have comments that extend up to multiple lines.
 One way is to use the hash(#) symbol at the beginning of each line. For example:
#This is a long comment
#and it extends
#to multiple lines
 Another way of doing this is to use triple quotes, either ''' or """.

These triple quotes are generally used for multi-line strings. But they can be used as a multi-line comment as
well.

Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""

Elements of Python
Identifier
Identifier is a name given to various programming elements such as a variable, function, class,
module or any other object.
Following are the rules to create an identifier.
 The allowed characters are a-z, A-Z, 0-9 and underscore (_)
 It should begin with an alphabet or underscore
 It should not be a keyword
 It is case sensitive
 No blank spaces are allowed.
 It can be of any size
 Valid identifiers examples : si, rate_of_interest, student1, ageStudent
Invalid identifier examples: rate of interest, 1student, @age
Keywords
Keywords are the identifiers which have a specific meaning in python, there are 33 keywords in
python. These may vary from version to version.
Keywords are predefined reserved words used in Python programming that have special meaning to the compiler.
We cannot use a keyword as a variable name, function name, or any other identifier. They are used to define the
syntax and structure of the python language.
All the keywords except True, False and None are in lowercase and they must be
False None True and as assert beak class continue
def del elif else except finally for from global if
import in is lambda nonlocal not or pass raise
return try while with yield

To get complete list of all the keywords with examples open the link given bellow.
https://www.programiz.com/python-programming/keyword-list
Variables and Types
When we create a program, we often need to store values so that it can be used in a program.
We use variables to store data which can be manipulated by the computer program.
Every variable has:
 Name and memory location where it is stored.
 type or data type
 value
Variable name:
1. Can be of any size
2. Have allowed characters, which are a-z, A-Z, 0-9 and underscore (_)
3. Should begin with an alphabet or underscore
4. Should not be a keyword
It is a good practice to follow these identifier naming conventions:
1. Variable name should be meaningful and short
2. Generally, they are written in lower case letters
Type or data type: specify the nature of variable i.e. what type of values can be stored in
that variable and what operations can be performed. We can check the type of the variable by using ‘type’
command
>>> type(variable_name)

Literals
A literal can be defined as data that is given in a variable or a constant that appear directly in a program and this
value does not change during the Program execution i.e. remains fixed.
Example:
Num=5
Principle_amount= 5000.00
Here 5 and 5000.00 are literals.
Python support the following literals
 Numeric literals
Numeric Literals are immutable. Numeric literals can belong to four different numerical types:
Integers, Long Integers (exists in Python 2.x, deprecated in Python 3.x), Floating point and complex
 String Literals
String literals can be formed by enclosing a text in either single or double quotes to create a string.
 Boolean literals
A Boolean literal can have any of the two values: True or False.
 Special Literals
Python contains one special literal i.e., none. None is used to specify to that field that is not created.
 Collection Literals
Python provides the four types of literal collection such as :
List literals, Tuple literals, Dict literals, and Set literals.
Data Types
Various data types available in python are as follow:
1. Number
2. Sequence
i. String
ii. Lists
iii.Tuples
3. Boolean
4. Sets
5. Dictionaries

1. Number
Number data type stores Numerical Values. These are of three different types:
a) Integer & Long(Long is exists in Python 2.x, deprecated in Python 3.x)
b) Float/floating point
c) Complex
a) Integers are the whole numbers consisting of + or – sign like 100000, -99, 0, 17. While writing a large
integer value
e.g. age=19
salary=20000
b) Floating Point: Numbers with fractions or decimal point are called floating point numbers.
A floating point number will consist of sign (+,-) and a decimal sign(.)
e.g. temperature= -21.9,
growth_rate= 0.98333328
The floating point numbers can be represented in scientific notation such as
-2.0X 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5
c) Complex: Complex number is made up of two floating point values, one each for real and imaginary part.
For accessing different parts of a variable x we will use x.real and x.imag.
Imaginary part of the number is represented by j instead of i, so 1+0j denotes zero imaginary part.
Example
>>> x = 1+0j
>>> print x.real, x.imag
1.0 0.0
2. None
This is special data type with single value. It is used to signify the absence of value/false in asituation. It is
represented by None.
3. Sequence
A sequence is an ordered collection of items, indexed by positive integers.
There are three types of sequence data type available in Python
Those are Strings, Lists & Tuples.
3.1 String: is an ordered sequence of letters/characters. They are enclosed in single quotes (‘’) or double
(“”).
Example
>>> a = 'Ram'
>>>a=”Ram”
3.2 Lists: List is also a sequence of values of any type. Values in the list are called elements /items. The
items of list are accessed with the help of index (index start from 0). List is enclosed in square brackets
([]).
Example
Student = [“Ajay”, 567, “CS”]
3.3 Tuples: Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable i.e. we cannot change the value of items of tuples . Tuples are enclosed in ().
Example
Student = (“Ajay”, 567, “CS”)
4. Sets
Set is an unordered collection of values, of any type, with no duplicate entry. Sets are immutable.
Example
s = set ([1,2,3,4])
5. Dictionaries: Dictionaries store a key – value pairs, which are accessed using key. Dictionary is enclosed in
curly brackets.
Example
d = {1:'a', 2:'b', 3:'c'}
String
Python does not have a character data type, a single character is simply a string with a length of 1.
In computer programming, a string is a sequence of characters.
For example, ‘hello’ is a string containing a sequence of characters: ‘h’ ‘e’ ‘l’ ‘l’ and ‘o’.
Square brackets can be used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.

Python Program for Creation of String:


# Creating a String with single Quotes
print('String with the use of Single Quotes: ')
String = 'Welcome to the Python Programming'
print(String)
# Creating a String with double Quotes
print("\nString with the use of Double Quotes: ")
String = "Welcome to Python Programming"
print(String)
# Creating a String with triple Quotes
print('''\nString with the use of Triple Quotes:''')
String = """Welcome to Python Programming"""
print(String)
# Creating String with triple Quotes allows multiple lines
print("\nCreating a multiline String using triple Quotes: ")
String = ''' Welcome
To
Python Programming'''
print(String)
Access String Characters
We can access the characters in a string in three ways.
• Indexing: One way is to treat strings as a list and use index values to access characters.
• Negative Indexing: Similar to a list, Python allows negative indexing for its strings.
• Slicing: Access a range of characters in a string by using the slicing operator colon (:)
Program to access characters in a string:
string = 'hello'
print(string)
#Access the First character
print("\nFirst character of String is: ")
print(string[0])
#Access the 1st index element
print(string[1])
greet = 'hello'
#Access the Last character
print("\nLast character of String is: ")
print(string[-1])
# Access the 4th last element
print('\nthe 4th last element is: ')
print(string[-4])
# Access character from 1st index to 3rd index
print('\nthe charecters between 1st and 3rd index is: ')
print(string[1:4])
Reversing a Python String
#Program to reverse a string
string = "Hello"
print(string[::-1]) #using Slice operator
# Reverse the string using reversed and join function
string1 = "".join(reversed(string)) # .join() method to merge all of the characters resulting
#from the reversed iteration into a new string.
print(string1)
Updating Entire String:
String = "Python programming"
print("Initial String: ")
print(String)
# Updating a String
String = "Welcome to Python programming"
print("\n Updated String: ")
print(String)
Python String Operations
There are many operations that can be performed with strings which makes it one of the most used data
types in Python.
1. Compare Two Strings
We use the ‘==’ operator to compare two strings. If two strings are equal, the operator returns True.
Otherwise, it returns False.
Example
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
# compare str1 and str2
print(str1 == str2)
# compare str1 and str3
print(str1 == str3)
OP
False
True
2. Join Two or More Strings
In Python, we can join (concatenate) two or more strings using the + operator.

greet = "Hello, "


name = "Jack"
# using + operator
result = greet + name
print(result)
3. String Length
In python, we use the len() method to find the length of a string.
For example,
string = 'Hello'
# count length of greet string
print(len(string))
3. String Membership Test
We can test if a substring exists within a string or not, using the keyword in
Example
print('a' in 'program') # True
print('at' not in 'battle') #False

4. Escape Sequences in Python


The escape sequence is used to escape some of the characters present inside a string.
Suppose we need to include both double quote and single quote inside a string,
Ex:
example = "He said, "What's there?""
print(example) # throws error
But
# escape double quotes
example = "He said, \"What's there?\""
# escape single quotes
example = 'He said, "What\'s there?"'
print(example)

Output: He said, "What's there?"

Python Strings are immutable

In Python, strings are immutable. That means the characters of a string cannot be changed.
Example:
message = 'Helo Everyone'
message[0] = 'E'
print(message)
Traceback (most recent call last):
File "C:/Users/TACT/Desktop/str2.py", line 2, in <module>
message[0] = 'E'
TypeError: 'str' object does not support item assignment

While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be passed
as an index, float or other types that will cause a TypeError.
List
The list is a sequence data type which is used to store the collection of data.
Python Lists are similar to arrays in C. However, the list can contain data of different types. The items stored in
the list are separated with a comma (,) and enclosed within square brackets [].
We can use slice [:] operators to access the data of the list.
The concatenation operator (+) and repetition operator (*) works with the list in the same way as they were
working with the strings.
Lists in Python can be created by just placing the sequence inside the square brackets []
Consider the following example.
list1 = [1, "hi", "Python", 2]
#Checking type of given list
print(type(list1))
#Printing the list
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
# List Concatenation using + operator
print (list1 + list1)
# List repetation using * operator
print (list1 * 3)

Tuple

The Tuple is a sequence data type which is used to store the collection of data.
A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different
data types.
The items of the tuple are separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.
Let's see a simple example of the tuple.
tup = ("hi", "Python", 2)
# Checking type of tup
print (type(tup))
#Printing the tuple
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
# Tuple concatenation using + operator
print (tup + tup)
# Tuple repatation using * operator
print (tup * 3)
# Adding value to tup. It will throw an error.
Set

Python Set is the unordered collection of the data type. It is iterable, mutable (can modify after creation), and
has unique elements. In set, the order of the elements is undefined; it may return the changed sequence of the
element. The set is created by using a built-in function set(), or a sequence of elements is passed in the curly
braces and separated by the comma. It can contain various types of values. Consider the following example.

# Creating Empty set


set1 = set()
set2 = {'James', 2, 3,'Python'}
#Printing Set value
print(set2)
# Adding element to the set
set2.add(10)
print(set2)
#Removing element from the set
set2.remove(2)
print(set2)

Dictionary
Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a hash table where
each key stores a specific value. Key can hold any primitive data type, whereas value is an arbitrary Python
object.
The items in the dictionary are separated with the comma (,) and enclosed in the curly braces {}.
Consider the following example.

d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}


# Printing dictionary
print (d)
# Accesing value using keys
print("1st name is "+d[1])
print("2nd name is "+ d[4])
print (d.keys())
print (d.values())
Operators and Operands
Operators are special symbols which represents specific operations. They are applied on operand(s), which can
be values or variables. Same operator can behave differently on different data types. Operators when applied on
operands form an expression.
Following is the partial list of operators:
a. Arithmetic Operators
b. Relational Operators
c. Logical Operators
d. Bitwise Operators
e. Membership Operator
f. Assignment Operator
g. Identity Operator
Arithmetic Operators:
Arithmetic operators are used to apply arithmetic operation.
Relational Operators:
Relation operators are used to compare two items. The result of relational operator is True or False.
Logical Operators
Logical Operators give the logical relationship based upon the truth table.

AND OR NOT

Value1 Value2 Result Value1 Value2 Result Value Result


False False False False False False True False
False True False False True True False True
True False False True False True
True True True True True True

Bitwise Operators:
Bitwise operators are applied upon the bits.
Example:
Assignment Operators
Assignment operators are used to assign a value to the variable.
Membership Operator

Identity Operator

Increment and Decrement


There is no Increment and Decrement operator in Python.
This may look odd but in Python if we want to increment value of a variable by 1 we write += or x = x + 1 and
to decrement the value by 1 we use -= or do x = x - 1.
Some of the possible logical reasons for not having increment and decrement operators in Python are listed
below.

 Can achieve similar result using += and -=.


 Including ++ and -- will result in the addition of some more opcode to the language which may result
into slower VM engine.
 Common use of ++ and -- is in loop and in Python for loop is generally written as for i in range(0,
10) thus removing the need for a ++ operator.
Ternary operator
The Python ternary operator (or conditional operator), tests if a condition is true or false and, depending on the
outcome, returns the corresponding value — all in just one line of code.

In other words, it’s a compact alternative to the common multiline if-else control flow statements in situations
when we only need to "switch" between two values. The ternary operator was introduced in Python 2.5.

The syntax consists of three operands, hence the name "ternary":


Syntax:
a if condition else b
Here are these operands:

 condition — a Boolean expression to test for true or false


 a — the value that will be returned if the condition is evaluated to be true
 b — the value that will be returned if the condition is evaluated to be false

The equivalent of a common if-else statement, in this case, would be the following:
if condition:
a
else:
b
Let’s look at a simple example:
>>> “Is true” if True else “Is false”
O/P: 'Is true'

You might also like