0% found this document useful (0 votes)
4 views13 pages

Chap 1

This document provides an introduction to Python, detailing its history, features, and applications. Python, created by Guido van Rossum in 1991, emphasizes code readability and is known for its simplicity and versatility across various domains such as web development, machine learning, and data science. It also covers essential concepts like keywords, identifiers, data types, operators, and popular libraries used in Python programming.

Uploaded by

Tharun Tharun
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)
4 views13 pages

Chap 1

This document provides an introduction to Python, detailing its history, features, and applications. Python, created by Guido van Rossum in 1991, emphasizes code readability and is known for its simplicity and versatility across various domains such as web development, machine learning, and data science. It also covers essential concepts like keywords, identifiers, data types, operators, and popular libraries used in Python programming.

Uploaded by

Tharun Tharun
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/ 13

CHAPTER-1

INTRODUCTION TO PYTHON
History, Features and Applications of python:
Python is a widely-used general-purpose, high-level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code.
In the late 1980s, history was about to be written. It was that time when working on Python
started. Soon after that, Guido Van Rossum began doing its application-based work in
December of 1989 at Centrum Wiskunde & Informatica (CWI) which is situated in
the Netherlands. It was started firstly as a hobby project because he was looking for an
interesting project to keep him occupied during Christmas. The programming language in
which Python is said to have succeeded is ABC Programming Language, which had
interfacing with the Amoeba Operating System and had the feature of exception handling. He
had already helped to create ABC earlier in his career and he had seen some issues with ABC
but liked most of the features. After that what he did was really very clever. He had taken the
syntax of ABC, and some of its good features. It came with a lot of complaints too, so he
fixed those issues completely and had created a good scripting language that had removed all
the flaws. The inspiration for the name came from BBC’s TV Show – ‘Monty Python’s
Flying Circus’, as he was a big fan of the TV show and also, he wanted a short, unique and
slightly mysterious name for his invention and hence he named it Python! He was the
“Benevolent dictator for life” (BDFL) until he stepped down from the position as the leader
on 12th July 2018. For quite some time he used to work for Google, but currently, he is
working at Dropbox.
The language was finally released in 1991. When it was released, it used a lot fewer codes to
express the concepts, when we compare it with Java, C++ & C. Its design philosophy was
quite good too. Its main objective is to provide code readability and advanced developer
productivity. When it was released, it had more than enough capability to provide classes
with inheritance, several core data types exception handling and functions.

Features of python:

1) Easy to Learn and Use

Python is easy to learn as compared to other programming languages. Its syntax is


straightforward and much the same as the English language. There is no use of the semicolon
or curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.

2) Expressive Language

Python can perform complex tasks using a few lines of code. A simple example, the hello
world program you simply type print("Hello World"). It will take only one line to execute,
while Java or C takes multiple lines.
3) Interpreted Language

Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language

Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.

5) Free and Open Source

Python is freely available for everyone. It has a large community across the world that is
dedicatedly working towards make new python modules and functions. Anyone can contribute
to the Python community. The open-source means, "Anyone can download its source code
without paying any penny."

6) Object-Oriented Language

Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.

7) Extensible

It implies that other languages such as C/C++ can be used to compile the code and thus it can
be used further in our Python code. It converts the program into byte code, and any platform
can use that byte code.

8) Large Standard Library

It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.

9) GUI Programming Support

Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.

10) Integrated

It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line
by line like C,C++ Java. It makes easy to debug the code.
11) Embeddable

The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language
into our code.

12) Dynamic Memory Allocation

In Python, we don't need to specify the data-type of the variable. When we assign some value
to the variable, it automatically allocates the memory to the variable at run time. Suppose we
are assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.

Applications of python:
 Web Development.
 Game Development.
 Machine Learning and Artificial Intelligence.
 Data Science and Data Visualization.
 Desktop GUI.
 Web Scraping Applications.
 Business Applications.
 Audio and Video Applications.

Keywords and Identifiers:


Keywords are predefined, reserved words used in Python programming that have special
meanings 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 written as
they are. The list of all the keywords is given below.

False await Else import pass

None break Except in raise

True class Finally is return

And continue For lambda try

As def From nonlocal while

assert del Global not with


async elif If or Yield

Identifiers:
Identifiers are the name given to variables, classes, methods, etc. For example,
language=python
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are built-in to
Python.
example,
continue=’python’

Rules for Naming an Identifier

 Identifiers cannot be a keyword.


 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter or _.
The first letter of an identifier cannot be a digit.
 It's a convention to start an identifier with a letter rather _.
 Whitespaces are not allowed.
 We cannot use special symbols like !, @, #, $, and so on.

Statements and Expressions:


A statement in Python is used for creating variables or for displaying values. A statement in
Python is not evaluated for some results.
Ex: x=25
Expressions:
The expression in Python produces some value or result after being interpreted by the Python
interpreter. An expression in Python is evaluated for some results.
Ex: x=25+10 or x=a+b
Operators: Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical
operations:

+,-,*,/,%,**(exponent),//(floor division)

Python Assignment Operators

sAssignment operators are used to assign values to variables:

=,+=,-=,==,*=,/=,**=,//=

Python Comparison Operators

Comparison operators are used to compare two values:

==,<,>,<=,>=,!=

Python Logical Operators

Logical operators are used to combine conditional statements:

and: Returns True if both statements are true

or: Returns True if one of the statements is true

not: Reverse the result, returns False if the result is true

Python Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:

is- Returns True if both variables are the same object

is not- Returns True if both variables are not the same object
Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

in- Returns True if a sequence with the specified value is present in the object

not in- Returns True if a sequence with the specified value is not present in the object.

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

&,|,~(not),^(XOR),<<( Zero fill left shift), >>( Signed right shift)

Operator Precedence

Operator precedence describes the order in which operations are performed.

() parenthesis

** Exponentiation

=, -, ~ unary plus, unary mins, bitwise NOT

*, /, //, %

+,- addition and subtraction

<<, >> bitwise left and bitwise right shift

& bitwise and

| bitwise or

^ bitwise xor

== != > >= < <= is is not in not in comparison,identity and membership operators

and, or, not logical operators


Data types:

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Indentation: indentation is a way of telling a Python interpreter that the group of statements
belongs to a particular block of code.

Comments: Comments can be used to explain Python code.


Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating a comment: Comments starts with a #, and Python will ignore them:

#This is a comment
print("Hello, World!")

Console input and output:

Console (also called Shell) is basically a command line interpreter that takes input from the
user i.e one command at a time and interprets it. If it is error free then it runs the command
and gives required output otherwise shows the error message. A Python Console looks like
this.

Accepting Input from Console User enters the values in the Console and that value is then
used in the program as it was required. To take input from the user we make use of a built-
in function input().

# input
input1 = input()
# output
print(input1)

1. Typecasting the input to Integer: There might be conditions when you might
require integer input from the user/Console, the following code takes two
input(integer/float) from the console and typecasts them to an integer then prints the
sum.
# input
num1 = int(input())
num2 = int(input())
# printing the sum in integer
print(num1 + num2)

2. Typecasting the input to Float: To convert the input to float the following code
will work out.
# input
num1 = float(input())
num2 = float(input())
# printing the sum in float
print(num1 + num2)

3. Typecasting the input to String: All kinds of input can be converted to string type
whether they are float or integer. We make use of keyword str for typecasting.
we can also take input string by just writing input() function by default it makes the input
string
# input
string = str(input())
# output
print(string)
# Or by default
string_default = input()
# output
print(string_default)

Python Convert Float to Int


Here, we are Converting Float to int datatype in Python with int() function.
# Python program to demonstrate
# type Casting
# int variable
a = 5.9
# typecast to int
n = int(a)
print(n)
print(type(n))

Python Convert Int to Float


Here, we are Converting Int to Float in Python with the float() function.
# Python program to demonstrate
# type Casting
# int variable
a=5
# typecast to float
n = float(a)
print(n)
print(type(n))

Python Convert int to String


Here, we are Converting int to String datatype in Python with str() function.
# Python program to demonstrate
# type Casting
# int variable
a=5
# typecast to str
n = str(a)
print(n)
print(type(n))

Python Convert String to float


Here, we are casting string data type into float data type with float() function.
Python program to demonstrate type Casting

# string variable
a = "5.9"
# typecast to float
n = float(a)
print(n)
print(type(n))

Python Convert string to int


Here, we are Converting string to int datatype in Python with int() function. If the given
string is not number than it will through error.
# string variable
a = "5"
b = 't'
# typecast to int
n = int(a)
print(n)
print(type(n))
print(int(b))
print(type(b))

libraries in python: A Python library is a collection of related modules. It contains bundles


of code that can be used repeatedly in different programs. It makes Python Programming
simpler and convenient for the programmer. As we don’t need to write the same code again
and again for different programs. Python libraries play a very vital role in fields of Machine
Learning, Data Science, Data Visualization, etc.
1. TensorFlow: This library was developed by Google in collaboration with the
Brain Team. It is an open-source library used for high-level computations. It is
also used in machine learning and deep learning algorithms. It contains a large
number of tensor operations. Researchers also use this Python library to solve
complex computations in Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s
why it is used in data analysis. It is also an open-source library and plots high-
defined figures like pie charts, histograms, scatterplots, graphs, etc.
3. Pandas: Pandas are an important library for data scientists. It is an open-source
machine learning library that provides flexible high-level data structures and a
variety of analysis tools. It eases data analysis, data manipulation, and cleaning of
data. Pandas support operations like Sorting, Re-indexing, Iteration,
Concatenation, Conversion of data, Visualizations, Aggregations, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly
used library. It is a popular machine learning library that supports large matrices
and multi-dimensional data. It consists of in-built mathematical functions for easy
computations. Even libraries like TensorFlow use Numpy internally to perform
several operations on tensors. Array Interface is one of the key features of this
library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source
library used for high-level scientific computations. This library is built over an
extension of Numpy. It works with Numpy to handle complex computations.
While Numpy allows sorting and indexing of array data, the numerical data code
is stored in SciPy. It is also widely used by application developers and engineers.
6. Scrapy: It is an open-source library that is used for extracting data from
websites. It provides very fast web crawling and high-level screen scraping. It can
also be used for data mining and automated testing of data.
7. Scikit-learn: It is a famous Python library to work with complex data. Scikit-
learn is an open-source library that supports machine learning. It supports
variously supervised and unsupervised algorithms like linear regression,
classification, clustering, etc. This library works in association with Numpy and
SciPy.
8. PyGame: This library provides an easy interface to the Standard Directmedia
Library (SDL) platform-independent graphics, audio, and input libraries. It is used
for developing video games using computer graphics and audio libraries along
with Python programming language.
9. PyTorch: PyTorch is the largest machine learning library that optimizes tensor
computations. It has rich APIs to perform tensor computations with strong GPU
acceleration. It also helps to solve application issues related to neural networks.
10. PyBrain: The name “PyBrain” stands for Python Based Reinforcement
Learning, Artificial Intelligence, and Neural Networks library. It is an open-
source library built for beginners in the field of Machine Learning. It provides fast
and easy-to-use algorithms for machine learning tasks. It is so flexible and easily
understandable and that’s why is really helpful for developers that are new in
research fields.
Importing python libraries:

Multiple interrelated modules are stored in a library. And whenever we need to use a
module, we import it from its library. In Python, it’s a very simple job to do due to its easy
syntax. We just need to use import.

# Importing math library


import math
A = 16
print(math.sqrt(A))

Control flow statements: control statements are the statements which controls the flow of
execution.

if statement
The if statement is the most simple decision-making statement. It is used to decide whether
a certain statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
if-else: if a condition is true it will execute a block of statements and if the condition is
false it won’t. if the condition is false, we can use the else statement.

Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Nested-If Statement:
Nested if statements mean an if statement inside another if statement. Yes, Python allows us
to nest if statements within if statements. i.e., we can place an if statement inside another if
statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

If-elif-else ladder: The if statements are executed from the top down. As soon as one of the
conditions controlling the if is true, the statement associated with that if is executed, and the
rest of the ladder is bypassed. If none of the conditions is true, then the final else statement
will be executed.
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

program to illustrate if-elif-else ladder


i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")
Loop: loop is a block of statements executed until the condition becomes false.
While Loop
is used to execute a block of statements repeatedly until a given condition is satisfied. And
when the condition becomes false, the line immediately after the loop in the program is
executed.
Syntax:
while expression:
statement(s)

Python program to illustrate while loop


count = 0
while (count < 3):
count = count + 1
print("Hello world")

For Loop: are used for sequential traversal. For example: traversing a list or string or array
etc.
Syntax:
for iterator_var in sequence:
statements(s)
Program to illustrate
# Iterating over range 0 to n-1
n=4
for i in range(0, n):
print(i)

break statement: used to skip parts of the current loop or break out of the loop completely.
for i in range(5):
if i == 3:
break
print(i)

Continue statement: The continue keyword is used to end the current iteration in a for
loop (or a while loop), and continues to the next iteration.

for i in range(9):
if i == 3:
continue
print(i)

exit(): exit() function is used to exit from the program

You might also like