You are on page 1of 18

UNIT I

Introduction: History of Python, Need of Python Programming, Applications Basics of Python


Programming Using the REPL(Shell), Running Python Scripts, Variables, Assignment, Keywords,
Input-Output, Indentation.

A. Introduction:
1. Python is a --------------
 Fastest growing language
 Popular programming language
 High salaries for python developers
 High level language and portable
 Object oriented language
 Simple, easy to learn and maintain
 Can develop small and complex applications(AI applications)
 Powerful programming language ( rapid applications)
 Powerful scripting language ( regular expressions, pattern matching)

History of Python:
• 1991 – version 0.9.0- OOPS
• Version 1.0- function programming tools like maps, reduce..etc
• Version 2.0- garbage collector.
• Garbage collector deallocates memory which has been previously allocated.
• It enhances the usage of memory efficiently.
• Version 3.0- some syntax has been altered from version 2.0.

Python is popular :
• Free
• Easy ( simple syntax)
• High level
• Cross platform (Windows, Mac, Linux, Raspberry pi ... etc.)
• Huge community
• Large eco system ( integrated development environment)

We can use python in different area’s :


• Used on a server to create web applications
• database systems
• Used to Used to create software applications
• Connect to handle big data and perform complex mathematical operations
• Used for rapid prototyping , production- ready software development

Features of Python:
a. Readable: Python is a very readable language.
b. Easy to Learn: Learning python is easy as this is a expressive and high level programming
language, which means it is easy to understand the language and thus easy to learn.
c. Cross platform: Python is available and can run on various operating systems such as Mac,
Windows, Linux, Unix etc. This makes it a cross platform and portable language.
d. Open Source: Python is a open source programming language

e. Large standard library: Python comes with a large standard library that has some handy
codes and functions which we can use while writing code in Python.
f. Free: Python is free to download and use. This means you can download it for free and use it
in your application. Python is an example of FLOSS (Free/Libre Open Source Software), which means
you can freely distribute copies of this software, read its source code and modify it.
g. Supports exception handling: If you are new, you may wonder what an exception is. An
exception is an event that can occur during program exception and can disrupt the normal flow of
program. Python supports exception handling which means we can write less error prone code and can
test various scenarios that can cause an exception later on.
h. Advanced features: Supports generators and list comprehensions. We will cover these features
later.
i. Automatic memory management: Python supports automatic memory management which
means the memory is cleared and freed automatically. You do not have to bother clearing the memory.

Install and Run Python:


 Installing Python
 Download the latest version of Python.
 Run the installer file and follow the steps to install Python During
the install process, check Add Python to environment variables. This will add Python to environment
variables, and you can run Python from any part of the computer. Also, you can choose the path
where Python is installed.

Installing Python on the computer

Once you finish the installation process, you can run Python.

a) Run Python in Immediate mode

Once Python is installed, typing python in the command line will invoke the interpreter in
immediate mode. We can directly type in Python code, and press Enter to get the output.
Try typing in 1 + 1 and press enter. We get 2 as the output. This prompt can be used as a
calculator. To exit this mode, type quit() and press enter.

Running Python on the Command Line


b. Run Python in the Integrated Development Environment (IDE)

Python IDLE:

Every Python installation comes with an Integrated Development and Learning Environment, which
you’ll see shortened to IDLE or even IDE. These are a class of applications that help you write
code more efficiently. While there are many IDEs for you to choose from, Python IDLE is very
bare-bones, which makes it the perfect tool for a beginning programmer.
Python IDLE comes included in Python installations on Windows and Mac. If you’re a Linux user, then
you should be able to find and download Python IDLE using your package manager. Once you’ve
installed it, you can then use Python IDLE as an interactive interpreter or as a file editor.
IDE is a piece of software that provides useful features like code hinting, syntax highlighting and
checking, file explorers, etc. to the programmer for application development.
By the way, when you install Python, an IDE named IDLE is also installed. You can use it to run
Python on your computer. It's a decent IDE for beginners.
When you open IDLE, an interactive Python Shell is opened.

c. Python IDLE
Now you can create a new file and save it with .py extension. For example, hello.py
Write Python code in the file and save it.
To run the file, go to Run > Run Module or simply click F5.

Running a Python program in IDLE

The First Program:

>>> print('Hello, World!')


This is an example of a print statement
the result is the words Hello, World!
The quotation marks in the program mark the beginning and end of the text to be displayed; they don’t
appear in the result.
The parentheses indicate that print is a function.

The shell is the default mode of operation for Python IDLE. When you click on the icon to open the
program, the shell is the first thing that you see:

This is a blank Python interpreter window. You can use it to start interacting with Python immediately.
You can test it out with a short line of code:

Here, you used print() to output the string "Hello, from IDLE!" to your screen. This is the most basic
way to interact with Python IDLE. You type in commands one at a time and Python responds with the
result of each command.

Next, take a look at the menu bar. You’ll see a few options for using the shell:

You can restart the shell from this menu. If you select that option, then you’ll clear the state of the
shell. It will act as though you’ve started a fresh instance of Python IDLE. The shell will forget about
everything from its previous state:
In the image above, you first declare a variable, x = 5. When you call print(x), the shell shows the
correct output, which is the number 5. However, when you restart the shell and try to
call print(x) again, you can see that the shell prints a traceback. This is an error message that says the
variable x is not defined. The shell has forgotten about everything that came before it was restarted.
You can also interrupt the execution of the shell from this menu. This will stop any program or
statement that’s running in the shell at the time of interruption. Take a look at what happens when you
send a keyboard interrupt to the shell:

A KeyboardInterrupt error message is displayed in red text at the bottom of your window. The program
received the interrupt and has stopped executing.

How to Work With Python Files


Python IDLE offers a full-fledged file editor, which gives you the ability to write and execute Python
programs from within this program. The built-in file editor also includes several features, like code
completion and automatic indentation, that will speed up your coding workflow. First, let’s take a look
at how to write and execute programs in Python IDLE.
Opening a File
To start a new Python file, select File → New File from the menu bar. This will open a blank file in the
editor, like this:
Executing a File or Running python Scripts
To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run → Run
Module from the menu bar. Either option will restart the Python interpreter and then run the code that
you’ve written with a fresh interpreter. The process is the same as when you run python3 -i
[filename] in your terminal.

How to Debug in IDLE


If you want to run your code with the built-in debugger, then you’ll need to turn this feature on. To do
so, select Debug → Debugger from the Python IDLE menu bar. In the interpreter, you should
see [DEBUG ON] appear just before the prompt (>>>), which means the interpreter is ready and
waiting.
When you execute your Python file, the debugger window will appear:

In this window, you can inspect the values of your local and global variables as your code executes.
This gives you insight into how your data is being manipulated as your code runs.
You can also click the following buttons to move through your code:

 Go: Press this to advance execution to the next breakpoint. You’ll learn about these in the next
section.
 Step: Press this to execute the current line and go to the next one.
 Over: If the current line of code contains a function call, then press this to step over that
function. In other words, execute that function and go to the next line, but don’t pause while executing
the function (unless there is a breakpoint).
 Out: If the current line of code is in a function, then press this to step out of this function. In
other words, continue the execution of this function until you return from it.
We have four checkboxes in the debug window:

1. Globals: your program’s global information


2. Locals: your program’s local information during execution
3. Stack: the functions that run during execution
4. Source: your file in the IDLE editor
When you select one of these, you’ll see the relevant information in your debug window.

Using the REPL(Shell):

Python Interpreter: Shell/REPL

 Python is an interpreter language. It means it executes the code line by line. Python provides a
Python Shell, which is used to execute a single Python command and display the result.
 It is also known as REPL (Read, Evaluate, Print, Loop), where it reads the command,
evaluates the command, prints the result, and loop it back to read the command again.
 To run the Python Shell, open the command prompt or power shell on Windows and terminal
window on mac, write python and press enter. A Python Prompt comprising of three greater-
than symbols >>> appears, as shown below.

Now, you can enter a single statement and get the result. For example, enter a simple expression like
2+3 or etc…,, press enter and it will display the result in the next line, as shown below.
Execute Python Script:

As you have seen above, Python Shell executes a single statement. To execute multiple statements,
create a Python file with extension .py, and write Python scripts (multiple statements).

For example, enter the following statement in a text editor such as Notepad.

print ("This is Python Script.")


print ("Welcome to Python")

Save it as myPythonScript.py, navigate the command prompt to the folder where you have saved
this file and execute the python myPythonScript.py command, as shown below. It will display the
result.

Thus, you can execute Python expressions and commands using Python REPL to quickly execute
Python code.

Applications of python:
 Web development
 Machine learning
 Data analytics
 Scripting
 Game development
 Embedded application development
 Desktop applications

Execution of Python code:


Procedure:

 Step 1: The python compiler reads a python source code or instruction. Then it verifies that
the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters an
error, it immediately halts the translation and shows an error message.
 Step 2: If there is no error, i.e. if the python instruction or source code is well-formatted then
the compiler translates it into its equivalent form in an intermediate language called “Byte
code”.
 Step 3: Byte code is then sent to the Python Virtual Machine(PVM) which is the python
interpreter. PVM converts the python byte code into machine-executable code. If an error
occurs during this interpretation then the conversion is halted with an error message.

Basic coding skills

1. 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 which will be discussed later.

2. Multi-line statement

In Python, the end of a statement is marked by a newline character. But 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

3. Python Indentation

Most of the programming languages like C, C++, and Java use braces { } to define a block of code.

Python, however, uses indentation.

A code block (body of a function, loop, etc.) starts with indentation and ends with the first unindented

line. The amount of indentation is up to you, but it must be consistent throughout that block.

Generally, four whitespaces are used for indentation and are preferred over tabs. Here is an example.
for i in range(1,11):
print(i)
if i == 5:
break
Run Code

The enforcement of indentation in Python makes the code look neat and clean. This results in Python

programs that look similar and consistent.

Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes the

code more readable. For example:

if True:
print('Hello')
a=5

and

if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
Incorrect indentation will result in IndentationError.

4. Python Comments

Comments are very important while writing a program. They describe what is going on inside a

program, so that a person looking at the source code does not have a hard time figuring it out.

You might forget the key details of the program you 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 to start writing a comment.

It extends up to the newline character. Comments are for programmers to better understand a

program. Python Interpreter ignores comments.


#This is a comment
#print out Hello
print('Hello')
Run Code

5. 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 commenting 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"""
B. Built in functions:

Python Output function:

 The print() function to output data to the standard output device (screen). We can also output data to a
file
 print() function:The print() function prints the given object to the standard output device (screen) or
to the text stream file.
 syntax of print() is:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Parameters in print():
 objects - object to the printed. * indicates that there may be more than one object
 sep - objects are separated by sep. Default value: ' '
 end - end is printed at last by default it has \n
 file - must be an object with write(string) method. If omitted it, sys.stdout will be used which prints
objects on the screen.
 flush - A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False

Example 1:

print('This sentence is output to the screen')

Output: This sentence is output to the screen

Example 2:
a=5
print('The value of a is', a)

Output:The value of a is 5

Example 3:

print("Python is fun.")
a=5
# Two objects are passed print("a =", a)
b=a
# Three objects are passed print('a =', a, '= b')
Output:

Python is fun. a= 5
a=5=b

Case 1: print without any arguments


print(‘ Engineering College’)
print () # we have not passed any argument by default it takes new line and create one line blank
space
print(‘Computer Science Engineering’)

Output:
Engineering College
Computer Science Engineering

Case 2: print function with string operations (with arguments)


1. Print(‘helloworld’) Output: helloworld

2. print(‘hello\nworld’) Output: hello


world
3. print(‘hello\tworld’) Output: hello world

4. # string concatenation both objects are string only

print(‘tec’ + ‘cse’) Output: teccse


print(‘tec’ , ‘cse’) Output: tec cse

5. # repeat string into number of times

print(5*’cse’) Output: csecsecsecsecse


print(2*'cse\n') Output:
cse

print(5*'cse\t') Output: csecse cse cse cse cse

cse
Case 3 : print function with any number of arguments
cse
1. (a) print(‘values are :’,10,20,30) Output: values are : 10 20 30
(b) a,b,c=10,20,30 cse
print(‘values are:’,a,b,c) Output: values are : 10 20 30

2. print function with “sep” attribute: This is used to separate objects

By default, value of sep is empty space(sep=’’)


>>>print('values are:',10,20,30,sep=":") Output: values are::10:20:30
>>>print('values are:',10,20,30,sep="--") Output: values are:--10--20—30

Case 4: print statement with end attribute

 The end key of print function will set the string that needs to be appended when printing is done.
 By default, the end key is set by newline character (By default, attribute end =’\n’ in print
function). So after finishing printing all the variables, a newline character is appended. Hence, we get
the output of each print statement in different line. But we will now overwrite the newline character
by any character at the end of the print statement.

Example-1:
 print('Tirumala') # in this statement by default end =’\n’ so it takes new line
 print('rajani') # in this statement by default end =’\n’ so it takes new line
 print('devansh') # in this statement by default end =’\n’ so it takes new line

Output:
Tirumala
Rajani
devansh

Note: when you observe output 1st print statement prints output Tirumala and immediately takes new
line character and execute 2nd print statement and followed.

Example-2:
 print ('Tirumala’, end='$')
 print ('rajani' ,end='*')
 print('devansh')

Output:
Tirumala$rajani*devansh

Case 5: print function with sep and end attribute

Example
 print(19,20,30,sep=':',end='$$$')
 print(40,50,sep=':')
 print(70,80,sep=':',end='&&&')
 print(90,100)

Output: 19:20:30$$$40:50
70:80&&&90 100

C. Output Formatting:
 There are several ways to present the output of a program, data can be printed in a human- readable
form, or written to a file for future use. Sometimes user often wants more control the formatting of
output than simply printing space-separated values. There are several ways to format output.

1. Formatting output using String modulo operator (%):

Syntax: print (‘formatted string’ %( variable list))

The % operator can also be used for string formatting. string modulo operator ( % ) is still available
in Python(3.x) and user is using it widely.

Example 1
# Python program showing how to use string modulo operator (%) to print fancier output # print
integer and float value
print ("CSE: % 2d, Portal: % 5.2f"%(1, 05.333)) # print integer value
print ("Total students: % 3d, Boys: % 2d"%(240, 120)) # print octal value
print ("% 7.3o"%(25)) # print exponential value
print ("% 10.3E"%(356.08977))

Output :
CSE: 1, Portal: 5.33
Total students: 240, Boys: 120
031
3.561E+02

Example 2
(a) a=6
print(‘a value is =%i’ %a)
Output: a value is =6 (b) a=6;b=7;c=8
print('a value is =%i and b=%f and c=%i' %(a,b,c))
Output: a value is =6 and b=7.000000 and c=8

2. print function with replacement operator {}or format function


str.format() is one of the string formatting methods in Python3, which allows multiple
substitutions and value formatting. This method lets us concatenate elements within a string through
positional formatting.

Example:1
Name= ‘John’ Salary=’1000’
print(‘hello my name is {} and my salary is {}’.format(Name,Salary))
Output: hello my name is John and my salary is 1000
Example:2
name='John' salary=1000
print('hello my name is "{}" and my salary is "{}"'.format(name,salary))
Output: : hello my name is "John" and my salary is "1000"
*********we can also use index values and print the output*********

Example: 3
name='John' salary=1000
print('hello my name is "{0}" and my salary is "{1}"'.format(name,salary))
Output: hello my name is "John" and my salary is "1000"

Example: 4
print('hello my name is "{0}" and my salary is "{1}"'.format(salary,name))
Output: hello my name is "1000" and my salary is "john"

***** **** we can also use variables in the reference operator*********


Example: 5
print ('hello my name is "{n}" and my salary is "{s}"‘. format (n=name, s=salary))
Output: hello my name is "john" and my salary is "1000"

Example: 6
print ('hello my name is "{n}"and my salary is { s}'.format(s=salary,n=name))
Output: hello my name is "john" and my salary is "1000"

D. Reading Input from the Keyboard:

In python input() is used to read the input from the keyboard dynamically. By default, the value of the
input function will be stored as a string

Syntax: Variable name =input(‘prompt’)

Example:
name =input("Enter Employee Name ")
salary =input("Enter salary ")
company =input("Enter Company name ")
print("\n")
print("Printing Employee Details") print("Name","Salary","Company")
print(name, salary, company)

Output:
Enter Employee Name Jon Enter salary 12000
Enter Company name Google

Printing Employee Details Name Salary Company Jon 12000 Google


Accept an numeric input from User: To accept an integer value from a user in Python. We need to
convert an input string value into an integer using a int() function.

Example: first_number = int(input("Enter first number "))

We need to convert an input string value into an integer using a float() function.

Example:
# program to calculate addition of two input numbers
first_number=int(input("Enter first number "))
second_number=int(input("Enter second number "))
print("First Number:",first_number)
print("Second Number:",second_number)
sum1 =first_number+second_number
print("Addition of two number is: ", sum1)

Output:

Enter first number 23


Enter second number 25
First Number: 23
Second Number: 25
Addition of two number is: 48

Get multiple input values from a user in one line: In Python, we can accept two or three values from
the user in one input() call.
Example: In a single execution of the input() function, we can ask the user hi/her name, age, and
phone number and store it in three different variables.
name, age, phone =input("Enter your name, Age, Percentage separated by space ").split() print("\n")
print("User Details: ", name, age, phone)

Output:
Enter your name, Age, Percentage separated by space John 26 75.50 User Details: John 26 75.50

E. Variable:
a) Need for variable:
1. Anything we write in code(software) is processed and stored in the memory (hardware)
2. The memory address are not easy to deal with and remember,as it consist of billions of binary
and hexadecimal numbers
3. so,in order to reuse a wvalue ,we need to have a reference for it
4. Variables are just the way we communicate with the memory to fetch the data

Explanation:
3+4 will be stored at some random memory address
Where as x=3+4 will be stored at random memory address but it will be assigned at reference
name x

b) Naming a variable:

1. It is a good practice to name your variables meaningfully name instead x,y,z


2. You cant use python reserved keywords to name variables
3. For example:
if,for,while and many more…..,
4. Python is case sensitive,so x is different and X different
5.Never use the characters I (lower case letter ),O (uppercase letter OH),or I(uppercase letter
eye)
As a single char variable names

Exercise :
>>>5+8
>>> 13
>>>x=5+8
>>>print(x)
>>>13
>>>ram sita =223 this is wrong format
>>>ram_sita=223 we can use underscore to give space for variable names

c) Rules for Naming variables:

 Names are case sensitive and cannot start with a number.


 Must start with letter or under score
 They can contain letters, numbers, and underscores.
 bob Bob _bob _2_bob_ bob_2 BoB
 A variable name cant contain spaces,punctutaion,or special characters except under score
 A variable name should not be a keyword
 There are some reserved words or keywords:
 and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from,
global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while

You might also like