0% found this document useful (0 votes)
1 views15 pages

Getting Started With Python

This document serves as an introductory guide to Python programming, covering its definition, features, and execution modes. It explains key concepts such as variables, data types, operators, and error handling, providing examples for clarity. Additionally, it discusses the importance of comments and the process of debugging in Python programming.

Uploaded by

mrr1104
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)
1 views15 pages

Getting Started With Python

This document serves as an introductory guide to Python programming, covering its definition, features, and execution modes. It explains key concepts such as variables, data types, operators, and error handling, providing examples for clarity. Additionally, it discusses the importance of comments and the process of debugging in Python programming.

Uploaded by

mrr1104
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

Getting Started with Python

Introduction to Python

An ordered set of instructions to be executed by a computer to carry out a


specific task is called a program, and the language used to specify this set of
instructions to the computer is called a programming language.

A program written in a high-level language is called source code. Python uses an interpreter
to convert its instructions into machine language, so that it can be understood by the
computer. An interpreter processes the program statements one by one, first translating and
then executing. This process is continued until an error is encountered or the whole program is
executed successfully.

Features of Python

 Python is a high level language. It is a free and open source language.


 It is an interpreted language, as Python programs are executed by an interpreter.
 Python programs are easy to understand as they have a clearly defined syntax and
relatively simple structure.
 Python is case-sensitive.
 Python is portable and platform independent.
 Python has a rich library of predefined functions.
 Python is also helpful in web development.
 Python uses indentation for blocks and nested blocks.

Working with Python


To write and run (execute) a Python program, we need to have a Python interpreter installed
on our computer or we can use any online Python interpreter. The interpreter is also called
Python shell.

Execution Modes
There are two ways to use the Python interpreter:

a) Interactive mode

b) Script mode
Interactive Mode

In the interactive mode, we can simply type a Python statement on the python shell
directly. As soon as we press enter, the interpreter executes the statement and displays the
result.

Script Mode
In the script mode, we can write a Python program in a file, save it and then use the interpreter
to execute it. Python scripts are saved as files where file name has extension
“.py”.

Python Keywords

Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and we can use a keyword in our program only for the purpose for which it has
been defined.

Examples: if, elif, and, as, not, or, etc..

Identifiers

Identifiers are names used to identify a variable, function, or other entities in a


program. The rules for naming an identifier in Python are as follows:

i. The name should begin with an uppercase or a lowercase alphabet or an underscore


sign (_).
ii. It can be of any length.
iii. It should not be a keyword or reserved word.
iv. We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

Examples: mark1, age, name, num1, etc..

Variables

Variable in Python refers to an object — an item or element that is stored in the


memory. Value of a variable can be a string, numeric or any combination of
alphanumeric characters. In Python we can use an assignment statement to create
new variables and assign specific values to them. Variable declaration is implicit in Python,
means variables are automatically declared and defined when they are assigned
a value the first time. Variables must always be assigned values before they are
used in expressions as otherwise it will lead to an error in the program.
Example: Write a Python program to find the area of a rectangle given that its length is 10
units and breadth is 20 units.

#To find the area of a rectangle

length = 10

breadth = 20

area = length * breadth

print(area)

Comments
Comments are used to add a remark or a note in the source code. Comments are not executed
by interpreter. They are added with the purpose of making the source code easier
for humans to understand. They are used primarily to document the meaning and purpose
of source code and its input and output requirements, so that we can remember later how it
functions and how to use it. In Python, a comment starts with # (hash sign).

Everything is an Object
Python treats every value or data item whether numeric, string, or other type as an object.
Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime
of that object. This ID points to the memory address of the object. The function id() returns
the identity of an object.
Example:

num1 = 20

print (id(num1))

Output: 1433920576

Data Types
Data type identifies the type of data values a variable can hold and the operations that can be
performed on that data.
Number

Number data type stores numerical values only. It is further classified into three different
types: int, float and complex.

Boolean Data type

Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two
constants, True and False. Boolean True value is non-zero, non-null and non-
empty. Boolean False is the value zero.

type() function
The type() function determines the data type of the variable or value.

Example:

num1 = 10

print(type(num1))

Output: <class ‘int’>


Note: Variables of simple data types like integers, float, boolean, etc., hold single values. But
such variables are not useful to hold a long list of information, for example, names of the
months in a year, names of students in a class, names and numbers in a phone book.

Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
The three types of sequence data types available in Python are Strings, Lists and Tuples.

String

String is a group of characters. These characters may be alphabets, digits or special


characters including spaces. String values are enclosed either in single quotation marks
(e.g., ‘Hello’) or in double quotation marks (e.g., “Hello”).

Note: We cannot perform numerical operations on strings, even when the string contains a
numeric value.

Example:

str1 = 'Hello Friend'

str2 = "452"

List
List is a sequence of items separated by commas and the items are enclosed in square brackets
[ ].

Example:

list1 = [5, 3.4, "New Delhi", "20C", 45]

print(list1)

Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ).
Once created, we cannot change the tuple.
Example:

tuple1 = (10, 20, "Apple", 3.4, 'a')


print(tuple1)

Set

Set is an unordered collection of items separated by commas and the items are enclosed
in curly brackets { }. A set is similar to list, except that it cannot have duplicate entries.
Once created, elements of a set cannot be changed.

Example:

set1 = {10,20,3.14,"New Delhi"}

print(set1)

Note:

#duplicate elements are not included in set

Example:

set2 = {1, 2, 1, 3}

print(set2)

Output: {1, 2, 3}

None
None is a special data type with a single value. It is used to signify the absence of value in a
situation.

Example:

myVar = None

print(myVar)

Output: None

Mapping
Mapping is an unordered data type in Python. Eg. Dictionary
Dictionary

Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in
curly brackets { }. Dictionaries permit faster access to data. Every key is separated from its
value using a colon (:) sign. The key : value pairs of a dictionary can be accessed
using the key. The keys are usually strings and their values can be any data type. In
order to access any value in the dictionary, we have to specify its key in square
brackets [ ].
Example:

dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}

print(dict1)

print(dict1['Price(kg)']) - This print statement will print the value 120 as Price(kg) is the key.

Mutable and Immutable Data Types

Variables whose values can be changed after they are created and assigned are
called mutable. Variables whose values cannot be changed after they are created and
assigned are called immutable. When an attempt is made to update the value of an
immutable variable, the old variable is destroyed and a new variable is created
by the same name in memory.

As an example,

Num1=11

Num2=Num1
Here, Num1 and Num2 points to same memory. Suppose if

Num1=Num2+10, then the value of Num1 changes to 21. Now actually Num1 which was
pointing to 11 will get deleted and it will be pointing to 21 and Num2 will be pointing to 11. i.e
old id of Num1 gets destroyed and it gets a new id.

Operators

An operator is used to perform specific mathematical or logical operation on values.


The values that the operators work on are called operands. For example, in the
expression 10 + num, the value 10, and the variable num are operands and the + (plus) sign is
an operator.

Arithmetic Operators
Relational Operators
Assignment Operators: Assignment operator assigns or changes the value of the variable
on its left.
Logical Operators

Identity Operators
Identity operators are used to determine whether the value of a variable is of a certain type or
not. Identity operators can also be used to determine whether two variables are referring to
the same object or not.
Membership Operators

Membership operators are used to check if a value is a member of the given sequence
or not.

Expressions

An expression is defined as a combination of constants, variables, and operators. An


expression always evaluates to a value.

Examples: 100, 3.0+3.11, “good”+”morning”

Precedence of Operators

Example: 15.0 / 4 + (8 + 3.0)


Statement

In Python, a statement is a unit of code that the Python interpreter can execute.

Example:

x=4 #assignment statement

Cube=x**3 #assignment statement

Print(x) #print statement

Input and Output

In Python, we have the input() function for taking the user input. The input() function
prompts the user to enter data. It accepts all user input as string. The user may enter a
number or a string but the input() function treats them as strings only.

The syntax for input() is: input ([Prompt])


Prompt is the string we may like to display on the screen prior to taking the input, and it is
optional. The input() takes exactly what is typed from the keyboard, converts it into a string
and assigns it to the variable on left-hand side of the assignment operator (=).

print() statement:
Python uses the print() function to output data to standard output device — the screen. The
print() outputs a complete line and then moves to the next line for subsequent output.

The syntax for print() is: print(value [, ..., sep = ' ', end = '\n'])

sep: The optional parameter sep is a separator between the output values. We can use
a character, integer or a string as a separator. The default separator is space.

end: This is also optional and it allows us to specify any string to be appended (joined) after
the last value. The default is a new line.

Type Conversion

Type conversion means changing from one data type to another. There are two types of
type conversions: - Implicit and Explicit type conversion.
Explicit Conversion

Explicit conversion, also called type casting happens when data type conversion takes place
because the programmer forced it in the program. The general form of an explicit data
type conversion is:

(new_data_type) (expression)

Example:

x=123

y=str(x) #the value x which is integer is converted to string and stored in y

print(y)

Implicit Conversion

Implicit conversion, also known as coercion, happens when data type conversion is done
automatically by Python and is not instructed by the programmer.
Example

n1=10

n2=20.0

sum1=n1+n2

print(sum1)

Note: Here, n1 is int and n2 is float. So when they are added, the int will be converted to float
implicitly. One may wonder why was the float value not converted to an integer instead? This
is due to type promotion that allows performing operations (whenever possible) by
converting data into a wider-sized data type without any loss of information.

Debugging

The process of identifying and removing such mistakes, also known as bugs or
errors, from a program is called debugging. Errors occurring in programs can be categorised
as:

i) Syntax errors
ii) Logical errors

iii) Runtime errors

Syntax Errors
Errors that occurs due to wrong syntax (violating the rules of python).

Example: Missing parenthesis.

print(7+3

Logical Errors

A logical error is a bug in the program that causes it to behave incorrectly. A logical error
produces an undesired output but without abrupt termination of the execution of
the program. Logical errors are also called semantic errors as they occur when the
meaning of the program (its semantics) is not correct.

For example, if we wish to find the average of two numbers 10 and 12 and we write the code as
10 + 12/2, it would run successfully and produce the result 16. Surely, 16 is not the average of
10 and 12. The correct code to find the average should have been (10 + 12)/2 to give the
correct output as 11.

Runtime Error

A runtime error causes abnormal termination of program while it is executing. Runtime


error is when the statement is correct syntactically, but the interpreter cannot execute it.
Runtime errors do not appear until after the program starts running or executing.

For example, we have a statement having division operation in the program. By mistake, if the
denominator entered is zero then it will give a runtime error like “division by zero”.

You might also like