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

Unit 4.python Introduction

This document provides an introduction to Python, a high-level programming language known for its readability and ease of use, making it suitable for beginners. It covers Python's features, applications, and basic programming concepts such as variables, data types, operators, and functions. Additionally, it explains the importance of comments, identifiers, and the different modes of running Python code.
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 views16 pages

Unit 4.python Introduction

This document provides an introduction to Python, a high-level programming language known for its readability and ease of use, making it suitable for beginners. It covers Python's features, applications, and basic programming concepts such as variables, data types, operators, and functions. Additionally, it explains the importance of comments, identifiers, and the different modes of running Python code.
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/ 16

Introduction to Python

Introduction
A programming language is a set of grammatical rules for instructing a computer
to perform specific tasks. Though there are many different programming languages
such as BASIC, Pascal, C, C++, Java, Haskell, Ruby, Python, etc. we will study
about Python in this chapter.

What is a program?
A computer program is a collection of instructions that perform a specific task
which is executed by a computer. It is usually written by a computer program in a
programming language.

What is Python?
Python is an open source and high-level programming language. It is a good
programming language for beginners. Also it was made to be easy-to-read and
powerful. Python is a programming language created 1980s by Guido Van Rossum
when he was working at Centrum Wiskunde and informatics (CWI) in the
Netherlands as a successor to ABC programming language.

The language was released in 1991. It got its name from BBC comedy series from
1970’s –“Monty Python’s Flying Circus”.

It can be follow both procedural and Object Oriented approach of programming.

Why Python for AI?


Artificial intelligence is the trending technology of the future. You can see so
many applications around you. If you as an individual can also develop an AI
application, you will require knowing a programming language. There are various
programming languages like Lisp, Prolog, C++, Java and Python, which can be
used for developing applications of AI.

Out of these, Python gains a maximum popularity because of the following


reasons:

Features in Python
1. Easy to learn and maintain.
2. Free and Open Source.
3. Object-Oriented Language.
4. Large Standard Library.
5. Interpreted Language.
6. Python is integrated language.
7. Portability and compatibility.
8. Extendable.
9. Databases and Scalable.
10. GUI Programming Support

Applications of Python

Python is used for a large number of applications. Some of them are mentioned
below:

Getting started with Python


Python is a cross-platform programming language, meaning, it runs on multiple
platforms like Windows, MacOS, and Linux.
Run in the Integrated Development Environment (IDE)
When we install Python, an IDE named IDLE (Integrated Development and
Learning Environment) is also installed. We can use it to run Python on our
computer.

IDLE (GUI integrated) is the standard, most popular Python development


environment.

IDLE is an acronym of Integrated Development Environment. It lets one edit, run,


browse and debug Python Programs from a single interface. This environment
makes it easy to write Programs.
Python shell can be used in two ways,
1. interactive mode and
2. script mode.
Where Interactive Mode, as the name suggests, allows us to interact with OS;
script mode lets us create and edit Python source file.

Interactive Mode

You can see the above example, Python IDLE Shell account has >>> as Python
prompt, where simple mathematical expressions and single line Python commands
can be written and can be executed simply by pressing enter.

The first expression 3+10 written on the first Python prompt shows 13 as output in
the next line.
The second expression 2+4*10 written on the second Python prompt shows 42 as
output in the next line.

The third statement print("Hello Learner") written on the third Python prompt
shows Hello Learner as output in the next line.

The third statement print("Result:", 40+5*100) written on the fourth Python


prompt shows

Result: as output in the next line.

Script Mode
In script mode, we type Python program in a file and then use the interpreter to
execute the content from the file. Working in interactive mode is convenient for
beginners and for testing small pieces of code, as we can test them immediately.
But for coding more than few lines, we should always save our code so that we
may modify and reuse the code.

Note: Result produced by Interpreter in both the modes, viz., Interactive and script
mode is exactly the same.

To write a Python script/program, we need to open a new file – File >> New File,
type a sequence of Python statements for solving a problem, save it with a
meaningful name –
File>> Save, and finally Run the program to view the output of the program.

Comments
A comment is text that doesn’t affect the outcome of a code; it is just a piece of
text to let someone know what you have done in a program or what is being done
in a block of code.
This is especially helpful when someone else has written a code and you are
analyzing it for bug fixing or making a change in logic, by reading a comment you
can understand the purpose of code much faster than by just going through the
actual code.

Types of Comments in Python


There are two types of comments in Python.
1. Single line comment
2. Multiple line comment
Single line comment
In python we use # special character to start the comment. Let’s take few
examples to understand the usage.

# This is just a comment. Anything written here is ignored by Python

Multi-line comment:
To have a multi-line comment in Python, we use triple single quotes at the
beginning and at the end of the comment, as shown below.

'''
This
Is
A
multi-line
comment
'''

Python Statement
Instructions written in the source code for execution are called statements.

There are different types of statements in the Python programming language like

Assignment statement, Conditional statement, looping statements etc. These help


the user to get the required output.
For example, n = 50 is an assignment statement.

Python Keywords
Keywords are the reserved words in Python used to recognize the structure of the
program. The list of all the keywords is given below.
Python Identifiers
An Identifier is a name given to entities like class, functions, variables, etc. It helps
to differentiate one entity from another.

1. Identifier can be a combination of letter in lowercase (a to z) or uppercase (A to


Z) or digits (0 to 9) or an underscore _.

2. An Identifier cannot start with a digit. For example 1variable is invalid, but
variable1 is perfectly valid.

3. Keywords cannot be used as identifiers.

4. We cannot use special symbols like !, @, $, % etc. in our identifier.

5. Identifier can be of any length.

Variables
A variable is a named location used to store data in the memory. It is helpful to
think of variables as a container that holds data which can be changed later
throughout programming.
For example,
X=42, Y=45
Note:
Assignment operator is used in Python to assign values to variables. For example,
a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.

Constants:
A constant is a type of variable whose value cannot be changed. It is helpful to
think of constants as containers that hold information which cannot be changed
later.

Assigning Value to a constant in Python


In Python, constants are usually declared and assigned on a module. Here, the
module means a new file containing variables, functions etc. which is imported to
the main file. Inside the module, constants are written in all capital letters and
underscores separating the words.

Example : Declaring and assigning value to a constant


Create a info.py
NAME = "Ram"
AGE = 24

Rules and Naming convention for variables and constants


1. Create a name that makes sense. For example, vowel makes more sense than v.
2. If you want to create a variable name having two words, use underscore to
separate them. For example: my_name.
3. Use capital letters possible to declare a constant. For example: PI.
4. Constant and variable names should have a combination of letters in lowercase
(a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_).
For example: CapWords. myName.
5. Never use special symbols like !, @, #, $, %, etc.
6. Don't start a variable name with a digit.

Datatypes
Every value in Python has a datatype. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of
these classes.
There are various data types in Python. Some of the important types are mentioned
below in the image.

long

1) Python Numbers
Number data type stores Numerical Values. These are of three different types:
a) Integer & Long
b) Float / floating point

Integer & Long Integer


Range of an integer in Python can be from -2147483648 to 2147483647, and long
integer has unlimited range subject to available memory.

Integers are the whole numbers consisting of + or – sign with decimal digits like
100000, -99, 0, 17. While writing a large integer value, don’t use commas to
separate digits. Also, integers should not have leading zeros.

Floating Point:
Numbers with fractions or decimal point are called floating point numbers.
A floating-point number will consist of sign (+,-) sequence of decimals digits and a
dot such as 0.0, -21.9, 0.98333328, 15.2963.
These numbers can also be used to represent a number in engineering/ scientific
notation.
-2.0x 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5

2) None
This is special data type with single value. It is used to signify the absence of
value/false in a situation. It is represented by None.
3) Sequence
A sequence is an ordered collection of items, indexed by positive integers. It is a
combination of mutable and non-mutable data types. Three types of sequence data
type available in Python are:
a) Strings
b) Lists
c) Tuples
String
String is an ordered sequence of letters/characters. They are enclosed in single
quotes (‘ ‘) or double (“ “). The quotes are not part of string. They only tell the
computer where the string constant begins and ends. They can have any character
or sign, including space in them.

Lists
List is also a sequence of values of any type. Values in the list are called elements /
items. These are indexed / ordered. List is enclosed in square brackets.
Example: dob = [19,"January",1990]

Tuples
Tuples are a sequence of values of any type, and are indexed by integers. They are
immutable. Tuples are enclosed in ().
Example: t = (5,'program',2.5)

4) Sets
Set is an unordered collection of values, of any type, with no duplicate entry.
Example: >>>
a = {1,2,2,3,3,3} >>> a {1,2,3}

5) Mapping
This data type is unordered. Dictionaries fall under Mappings.
Dictionaries Dictionary is an unordered collection of key-value pairs. It is
generally used when we have a huge amount of data. Dictionaries are optimized
for retrieving data. We must know the key to retrieve the value.
In Python, dictionaries are defined within braces {} with each item being a pair in
the form key: value. Key and value can be of any type.
Example
>>> d = {1:'Ajay','key':2}
>>> type(d)
<class ‘dict’>

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:

Python Comparison Operators


Comparison operators are used to compare the values.It either returns True or False
according to the conditions
Python Assignment Operators
Assignment operators are used to assign values to variables:
Python Logical Operators
Logical operators are used to combine conditional statements:

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:

Python Membership Operators

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


object:
Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Python Output Using print() function


We use the print() function to output data to the standard output device (screen).
We can also output data to a file.
An example is given below.
a = "Hello World!"
print(a)
The output of the above code will be: Hello World!
print("My name is :",a)
The output of the above code will be: My name is : Hello World!
User input
In all the examples till now, we have been using the calculations on known values
(constants). Now let us learn to take user’s input in the program. In python, input()
function is used for the same purpose.
Type Conversion
The process of converting the value of one data type (integer, string, float, etc.) to
another data type is called type conversion. Python has two types of type
conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion, Python automatically converts one data type to another
data type. This process doesn't need any user involvement.

The output of the above program:

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required
data type. We use the predefined functions like int(), float(), str(), etc to perform
explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes)
the data type of the objects.
The output of the above program

id() Function:
id() is an inbuilt function in Python. All objects in Python have its own unique id.
Syntax : id(object)
Returns the identity of object. It is the address of object in memory.
It will be unique and constant throughout the lifetime of object.
Example:-
type() Function:
type() is an inbuilt function in Python.
The type() function returns the type of the specified object
Syntax : type(object) type(name, base, dict)
Example 1 : If a single argument (object) is passed to type() built-in, it returns
type of the given object.

You might also like