Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

UNIT –1 Introduction

1.1 Introduction
Python is a general purpose high level programming language.
Python is a general purpose, dynamic, high level, and interpreted programming language.
Python is a simple, general purpose, high level, and object-oriented programming language.
Python is recommended as first programming language for beginners.
Python is open source software.

Why the Name Python?


There is a fact behind choosing the name Python. Guido Van Rossum was reading the script of
a popular BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he
decided to select naming Python after the "Monty Python's Flying Circus" for their newly
created programming language.
Python is also versatile and widely used in every technical field, such as Machine
Learning, Artificial Intelligence, Web Development, Mobile Application, Desktop Application,
Scientific Calculation, etc.

1.2 History of Python


 Python laid its foundation in the late 1980s.
 The implementation of Python was started in December 1989 by Guido Van Rossum at
CWI (Centrum Wiskunde & Informatica) in Netherland.
 In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to
alt.sources.
 In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
 In 2000, Python 2.0 added new features such as list comprehensions, garbage collection
systems.
 On December 2008, Python 3.0 (also called "Py3K") was released. It was designed to
rectify the fundamental flaw of the language.

 On October 2020, Python 3.9 was released with new features like Dictionary Merge &
Update Operators, New remove prefix() and remove suffix() string methods, Built-in
Generic types etc.
 Python 3.10 - October 2021, Python 3.11 - October 2022, Python 3.12 - October 2023.
 ABC programming language is said to be the predecessor of Python language, which was
capable of Exception Handling and interfacing with the Amoeba Operating System.
 The following programming languages influence Python:
o ABC language.
o Modula-3
1
1.3 Need of Python Programming (Features of Python Programming)
Following are the major features and applications of Python that has influenced more and more
people to learn Python and gain certification.
1. Data Science: Python is the preferred programming language of most data scientists.
2. Easy to Learn: Python is an easy language to master.
3. Cross-Platform and Open Source: It’s been more than 20 years since this language has
been running cross-platform and open source. Be it Linux, Windows or MacOS, Python code
works on every platform.
4. Versatile Language and Platform: Python remains very relevant today as it can be used in
any operations scenario or software development, be it in managing local and cloud
infrastructure.
5. Vast Libraries: Python is supported by PyPI which has 85,000+ python scripts and
modules accessible to the user.
6. Flexibility: Python has several powerful applications integrated with other programming
languages.
7. High Salary: The salary of Python engineers is comparatively higher as compared to others
in the industry.
8. Scripting and Automation: What most people don’t know about Python is that it can be
used as a scripting language.
9. Artificial Intelligence: Without any dispute, Artificial intelligence is going to lead the
future IT. Python’s libraries such as Keras and TensorFlow enable machine learning
functionality.
10. Computer Graphics: Python can be employed in small, large, online or offline projects. It
is used to develop GUI and desktop applications.
11. Testing Framework: This language is an excellent tool for validating the products or ideas
for established enterprises. Python has numerous built-in testing frameworks that deal with
debugging and rapid workflows.
12. Web Development: Python’s different frameworks support website development. Python
has an array of frameworks for developing websites. Popular frameworks such as Django,
Flask, and Pylons are characterized by faster and stable code; this is because they are written in
Python.

2
1.4 Installation of Python
Installing Python on Windows takes a series of few easy steps.

Step 1 − Select Version of Python to Install


Python has various versions available with differences between the syntax and working of
different versions of the language. We need to choose the version which we want to use or need.
There are different versions of Python 2 and Python 3 available.
Step 2 − Download Python Executable Installer
On the web browser, in the official site of python (www.python.org), move to the Download for
Windows section.
All the available versions of Python will be listed. Select the version required by you and click
on Download. Let suppose, we chose the Python 3.9.1 version.

On clicking download, various available executable installers shall be visible with different
operating system specifications. Choose the installer which suits your system operating system
and download the installer. Let suppose, we select the Windows installer (64 bits).
The download size is less than 30MB.

3
Step 3 − Run Executable Installer
We downloaded the Python 3.9.1 Windows 64 bit installer.
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install
Now.

On clicking the Install Now, The installation process starts.

The installation process will take few minutes to complete and once the installation is successful,
the following screen is displayed.

4
Step 4 − Verify Python is installed on Windows
To ensure if Python is successfully installed on your system. Follow the given steps −
 Open the command prompt.
 Type ‘python’ and press enter.
 The version of the python which you have installed will be displayed if the python is
successfully installed on your windows.

Step 5 − Verify Pip (Preferred Installer Program) was installed


Pip is a powerful package management system for Python software packages. Thus, make sure
that you have it installed.
To verify if pip was installed, follow the given steps −
 Open the command prompt.
 Enter pip –V to check if pip was installed.
 The following output appears if pip is installed successfully.

We have successfully installed python and pip on our Windows system.


5
1.5 Applications of Python Programming using REPL (Shell)

Python’s REPL (Read-Eval-Print Loop) or shell is a command-line interface that allows users to
interact with the Python interpreter in real-time. The REPL is a powerful tool that allows
programmers to write, test, and debug Python code on the fly, without the need for a full-fledged
integrated development environment (IDE). Here are some common applications of Python’s
REPL:

1. Testing Code Snippets: The Python REPL is a great tool for testing small code snippets
or for quickly prototyping an idea. Programmers can write a few lines of code in the shell
and see the output immediately, without having to save and run the code in a separate
file. This makes it easy to experiment with new ideas and test out different approaches to
a problem.
2. Debugging Code: The Python REPL can be used for interactive debugging of Python
code. Programmers can step through their code line by line and examine variables and
objects at each step. This allows them to identify bugs and other issues in their code and
fix them on the fly.
3. Data Analysis: The Python REPL can be used for interactive data analysis and
exploration. Python has several libraries for data analysis, such as Pandas and NumPy,
which allow programmers to manipulate and analyze data in real-time. The REPL can be
used to explore data sets and test out different data analysis techniques.
4. Learning Python: The Python REPL is a great tool for learning Python, especially for
beginners. It allows users to experiment with Python code and see the results
immediately, which can help them understand the language’s syntax and semantics
better. Additionally, the REPL provides feedback on syntax errors and other issues,
which can help beginners, learn faster and avoid common mistakes.
5. Scripting: The Python REPL can be used for scripting, allowing users to write short
scripts and run them in the shell. This is useful for automating repetitive tasks or for
performing quick calculations.

Python’s REPL (Read-Eval-Print Loop) or shell is a powerful tool that allows programmers to
interact with the Python interpreter in real-time. Its versatility makes it useful for a wide range of
applications, from testing code snippets to interactive data analysis and exploration.
Additionally, it is a great tool for learning Python and for scripting simple tasks.

6
1.6 Running Python Scripts
Python programmers must know every possible way to run the Python scripts or code. This is the
only way to verify whether code is working as we want.
Python interpreter is responsible for executing the Python scripts. Python interpreter is a piece of
software which works between the Python program and computer hardware.
The series of ways to run Python scripts
 The operating system command-line or terminal.
 The Python interactive mode.
 The IDE or Text editor
 The file manager of system.

The operating system command-line or Terminal


Run the Python code using a command line because in Python shell once closes the session; lose
the complete code that has written. So it is good to write a Python code using the plain text files.
The text file must save as .py extension. Let's see the following example.

Write the Python print statement and save it as sample.py in working directory. Now, run this
file using the command-line.

Using the Python command line


Open the command line to run a Python script. Need to type the python, followed by the file
name to execute the file. Now, hit the enter key, and if there is no the error in file, see the output
as follows.

7
The Python interactive mode
To run the Python code, use the Python interactive session. Need to start Python interactive
session, just open a command-line or terminal in start menu, then type in python, and press enter
key.
Here is the example of how to run Python code using interactive shell.

It allows us to check every piece of code, and this facility makes it an awesome development
tool. But once close the session it will lose all code that has written.
Below are the few options to exit the interactive mode.
o Type built-in functions quit() or exit(). Or
o Type the enter ctrl+ Z key combination to end the current session of Python interactive
shell.

8
The IDE or Text Editor
The IDE stands for Integrated Development Environment. There are various IDEs
but Pycharm is Python's most popular and useful text editor among them. It is recommended for
developing large and more complex applications. Here are using the Pycharm to run python
script.
Create a new project and then create a new Python file using the .py extension.

Now, click on the green button and it will show the output as follows.

The file manager system


The Python file can run by double-clicking on its icon in a file manager. This process may not be
widely used in the development stage. The file should be associated with the .py or .pyw with the
program python.exe, respectively.

9
1.7 Variables in Python
Python variables are the reserved memory locations used to store values with in a Python
Program.
Variables are containers for storing data values.
Variable acts as an address for where the data is stored in memory.

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example
x=5
y = "John"
print(x)
print(y)
5
John
Variables do not need to be declared with any particular type, and can even change type
after they have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Sally

Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
print(x)
print(y)
print(z)
3
3
3.0

Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for Python variables
 A Python variable name must start with a letter or the underscore character.
 A Python variable name cannot start with a number.
 A Python variable name can only contain alpha-numeric characters and underscores (A-z,
0-9, and _ ).

10
 Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).
 The reserved words (keywords) in Python cannot be used to name the variable in Python.
Example
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:
Example
x, y = "Orange", "Banana"
print(x)
print(y)
Orange
Banana

One Value to Multiple Variables: Assign the same value to multiple variables in one line
Example
x = y = "Orange"
print(x)
print(y)
Orange
Orange

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the
values into variables. This is called unpacking.
Example: Unpack a list
fruits = ["apple", "banana"]
x, y = fruits
print(x)
print(y)
apple
banana

11
Output Variables
The Python print() function is often used to output variables.
Example
x = "Python is awesome"
print(x)
Python is awesome
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
Python is awesome
You can also use the + operator to output multiple variables:
Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Python is awesome

Global Variables
Variables that are created outside of a function are known as global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Python is awesome
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
Python is fantastic
Python is awesome

12
1.8 Assignment Operators
Following are the different types of assignment operators in Python:

1. Simple assignment operator ( = )


2. Add and equal operator ( += )
3. Subtract and equal operator ( -= )
4. Asterisk and equal operator ( *= )
5. Divide and equal operator ( /= )
6. Modulus and equal operator ( %= )
7. Double divide and equal operator ( //= )
8. Exponent assign operator ( **= )
9. Bitwise And Operator ( &= )
10. Bitwise OR Operator ( |= )
11. Bitwise XOR Assignment Operator ( ^= )
12. Bitwise right shift assignment operator ( >>= )
13. Bitwise left shift assignment operator ( <<= )

Operator Example Same As

= x=5 x=5

+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

13
//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

14
1.9 List of Keywords in Python (35 Keywords)

Keyword Description Keyword Description Keyword Description

Represents an
It is a Logical expression that It is a non-local
and False nonlocal
Operator will result in not variable
being true.

It is used to
It is used with It is a Logical
as create an alias finally not
exceptions Operator
name

It is used for It is used to It is a Logical


assert for or
debugging create Loop Operator

pass is used
To import when the user
break Break out a Loop from specific parts of a pass doesn’t
module want any code
to execute

It is used to raise is used to


It is used to
class global declare a global raise raise exceptions
define a class
variable or errors.

Skip the next To create a return is used to


continue iteration of a if Conditional return end the
loop Statement execution

Represents an
It is used to
It is used to expression that
def define the import True
import a module will result in
Function
true.

It is used to test
It is used to Try is used to
del is if two variables try
delete an object handle errors
are equal

15
Keyword Description Keyword Description Keyword Description

To check if a While Loop is


Conditional
value is present used to execute
elif statements, same in while
in a Tuple, List, a block of
as else-if
etc. statements

with statement
It is used in a Used to create an
is used in
else conditional lambda anonymous with
exception
statement function
handling

yield keyword
try-except is
It represents a is used to create
except used to handle None yield
null value a generator
these errors
function

pause execution
Manage multiple
await until the awaited async
tasks at once
task completes

1.10 Input-Output Functions

Python input() Function


Python input() function is used to get input from the user. It prompts for the user input and reads
a line. After reading data, it converts it into a string and returns that.

Syntax
input(prompt)

prompt – A string, representing a default message before the input

print() – print() function is used to display result on the screen (output function Syntax)

Example
x = input('Enter your name:')
print('Hello, ' + x)

Output
Enter your name: King
Hello, King

16
1.11 Indentation in Python
Python indentation refers to adding white space before a statement to a particular block of
code.
In another word, all the statements with the same space to the right belong to the same code
block.
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
The number of spaces is up to you as a programmer, but it has to be at least one.

Example of Python Indentation


 Statement (line 1), if condition (line 2), and statement (last line) belongs to the same block
which means that after statement 1, if condition will be executed and suppose the if
condition becomes False then the Python will jump to the last statement for execution.
 The nested if-else belongs to block 2 which means that if nested if becomes False, then
Python will execute the statements inside the else condition.
 Statements inside nested if-else belong to block 3 and only one statement will be executed
depending on the if-else condition.
Python indentation is a way of telling a Python interpreter that the group of statements belongs
to a particular block of code. A block is a combination of all these statements. Block can be
regarded as the grouping of statements for a specific purpose.
Most programming languages like C, C++, and Java use braces { } to define a block of code.

Example
# Python program showing
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Output
Logging on to geeksforgeeks...
All set !
17
1.12 Differences between C, C++, Java and Python

C C++ JAVA PYTHON

Compiled Compiled Compiled Interpreted Programming


Language Programming Programming Language
language Language

Operator Supports Overloading of the Overloading of the operator


overloading is not Overloading the operator is not is supported
supported. operator supported.

Multiple Allow for both Java provides partial Provides both single as well
inheritance is not single as well as multiple inheritance as multiple inheritance
supported in C. multiple inheritance
options.

Platform-specific Platform dependent Platform-unaffected Platform independent

Threads are Threads are not Multithreading Multithreading is


supported. supported on this capability is built-in. supported.
platform.

A small number Has a small number Many concepts, such It comes with a large
of libraries of library patrons as UI, are supported library set that allows it to
available. by the library. be used for AI, data
science, and other
applications.

Outside of the Outside of the class, Every line of code is Functions and variables can
class, variables variables and contained within a be declared global.
and functions are functions are class.
utilized. utilized.

Have a similar C++ is a computer The Java Program Execution is delayed due to
speed as C++ language that Compiler is a little the employment of an
compiles quickly. slower than the C++ interpreter.
Compiler.

Syntax rules are Syntax rules are Syntax rules are It isn't necessary to use
strictly followed. strictly followed. strictly followed. semicolon ' ;'.

18
Difference between Python, Java and C Program with Example

# Python program to print Hello World

print("Hello World")

Output
Hello World

// Java program to print Hello World

import java.io.*;
class GFG {
public static void main(String[] args)
{
System.out.println("Hello World");
}
}

Output
Hello World

// Simple C program to display Hello World

#include <stdio.h>
int main()
{
printf("Hello World");

return 0;
}
Output
Hello World

19
Unit I Questions

1. State and explain the features of python.


2. Discuss the applications of Python Programming using the REPL (Shell).
3. What is Python script and explain how to Run Python Scripts.
4. Explain significance and use of variables, comments and indentation.
5. What are the different types of assignment operators and give its significance.
6. Explain significance and use of keywords.
7. Explain input and print command in python with suitable example.
8. Compare Java language and Python language.
9. What will be the output of following print statements?
1. print(‘GoodLuck’ *2)
2. print(3-4j + 2+6j)
3. print(‘3-4j’*int(4/2))
10. State which of the following python statements are valid and invalid.
a. x=input(“enter your name”)
b. x=input()
c. x=input(““)
d. x=input(“ ’ “)
e. x=input(2)
f. x=input(“python” + 53)

20

You might also like