0% found this document useful (0 votes)
23 views10 pages

Python Programming Basics Guide

The document provides an introduction to Python programming, detailing its features, execution modes, keywords, identifiers, variables, comments, and data types. It explains the concept of mutable and immutable data types, operators, expressions, type conversion, and debugging, including syntax, logical, and runtime errors. The document serves as a comprehensive guide for beginners to understand the fundamentals of Python programming.

Uploaded by

fulhansdariya
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)
23 views10 pages

Python Programming Basics Guide

The document provides an introduction to Python programming, detailing its features, execution modes, keywords, identifiers, variables, comments, and data types. It explains the concept of mutable and immutable data types, operators, expressions, type conversion, and debugging, including syntax, logical, and runtime errors. The document serves as a comprehensive guide for beginners to understand the fundamentals of Python programming.

Uploaded by

fulhansdariya
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

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.

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. For example, NUMBER and number are not same
in Python.
• Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.
• Python has a rich library of predefined functions.
• Python is also helpful in web development. Many popular web services
and applications are built using Python.
• Python uses indentation for blocks and nested blocks.

Execution Modes:
There are two ways to use the Python interpreter:
a) Interactive mode
b) Script mode

Interactive mode allows execution of individual statement instantaneously.


Whereas, Script mode allows us to write more than one instruction in a file
called Python source code file that can be executed.

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. As Python is case sensitive,
keywords must be written exactly same as defined in Python libraries.

Examples of Python keywords are as shown in the table below:-


IDENTIFIERS:
In programming languages, 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:
• The name should begin with an uppercase or a lowercase alphabet or an
underscore sign (_). This may be followed by any combination of characters
a–z, A–Z, 0–9 or underscore (_). Thus, an identifier cannot start with a digit.
• It can be of any length. (However, it is preferred to keep it short and
meaningful).
• It should not be a keyword or reserved word.
• We cannot use special symbols like- !, @, #, $, %, etc., in identifiers.

For example, to find the average of marks obtained by a student in three


subjects, we can choose the identifiers as marks1, marks2, marks3 and avg
rather than a, b, c, or A, B, C.
avg = (marks1 + marks2 + marks3)/3

VARIABLES:
A variable in a program is uniquely identified by a name (identifier).
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 (e.g., ‘b’, ‘Global Citizen’),
numeric (e.g., 345) or any combination of alphanumeric characters (CD67).
In Python we can use an assignment statement to create new variables and
assign specific values to them.

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 following the #


till the end of that line is treated as a comment and the interpreter simply
ignores it while executing the statement.

Example:
#Variable amount is the total spending on
#grocery
amount = 3400
#totalMarks is sum of marks in all the tests
#of Mathematics
totalMarks = test1 + test2 + finalTest

EVERYTHING IS AN OBJECT:
Python treats every value or data item whether numeric, string, or other
type as an object in the sense that it can be assigned to some variable or can
be passed to a function as an argument. Every object in Python is assigned a
unique identity (ID) which remains the same for the lifetime of that object.
This ID is akin to the memory address of the object. The function id()
returns the identity of an object.

DATA TYPES:
Every value belongs to a specific data type in Python. 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 (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.

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.
(A) 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”).

(B) List
List is a sequence of items separated by commas and the items are enclosed
in square brackets [ ].
# list1 = [5, 3.4, "New Delhi", "20C", 45]

(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed
in parenthesis ( ). This is unlike list, where values are enclosed in brackets
[ ]. Once created, we cannot change the tuple.
#tuple1 = (10, 20, "Apple", 3.4, 'a')

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.
#set1 = {10,20,3.14,"New Delhi"}

None
None is a special data type with a single value. It is used to signify the
absence of value in a situation. None supports no special operations, and it
is neither same as False nor 0 (zero).

Mapping
Mapping is an unordered data type in Python. Currently, there is only one
standard mapping data type in Python called 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 [ ].
#dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}

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.

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.

(i) Arithmetic Operators


Python supports arithmetic operators that are used to perform the four
basic arithmetic operations as well as modular division, floor division and
exponentiation. For example:- +, /, -, *, //, %, **

(ii)Relational Operators
Relational operator compares the values of the operands on its either side
and determines the relationship among them. For example:- ==, !=, >=, <=,
<, >

(iii)Assignment Operators
Assignment operator assigns or changes the value of the variable on its left.
For example:- =, +=, -=, *=, /=, **=, //=, %=

(iv)Logical Operators
There are three logical operators supported by Python. These operators
(and, or, not) are to be written in lower case only. The logical
operator evaluates to either True or False based on the logical operands on
either side. Every value is logically either True or False. By default, all
values are True except None, False, 0 (zero), empty collections "", (), [], {},
and few other special values. So if we say num1 = 10, num2 = -20,
then both num1 and num2 are logically True. For example:- and, or, not

(v)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. There are
two identity operators.

(vi)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. A value or a
standalone variable is also considered as an expression but a standalone
operator is not an expression. Some examples of valid expressions are-

(i) 100 (iv) 3.0 + 3.14


(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"

Precedence of Operators:
Evaluation of the expression is based on precedence of operators. When an
expression contains different kinds of operators, precedence determines
which operator should be applied first. Higher precedence operator is
evaluated before the lower precedence operator.

Note:
a) Parenthesis can be used to override the precedence of operators. The
expression within () is evaluated first.
b) For operators with equal precedence, the expression is evaluated from
left to right.

TYPE CONVERSION:
As and when required, we can change the data type of a variable in Python
from one type to another. Such data type conversion can happen in two
ways: either explicitly (forced) when the programmer specifies for the
interpreter to convert a data type to another type; or implicitly, when the
interpreter understands such a need by itself and does the type conversion
automatically.

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)

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.

Program to show implicit conversion from int to float.


#Program 5-10
#Implicit type conversion from int to float
num1 = 10 #num1 is an integer
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float
and an integer
print(sum1)
print(type(sum1))
Output:
30.0
<class 'float'>

DEBUGGING:
A programmer can make mistakes while writing a program, and hence, the
program may not execute or may generate wrong output. 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
Like other programming languages, Python has its own rules that
determine its syntax. The interpreter interprets the statements only if it is
syntactically (as per the rules of Python) correct. If any syntax error is
present, the interpreter shows error message(s) and stops the execution
there. For example, parentheses must be in pairs, so the expression (10 +
12) is syntactically correct, whereas (7 + 11 is not due to absence of right
parenthesis.

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. Since the program interprets
successfully even when logical errors are present in it, it is sometimes
difficult to identify these errors. The only evidence to the existence of
logical errors is the wrong output. While working backwards from the
output of the program, one can identify what went wrong.

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.

Logical errors are also called semantic errors as they occur when the
meaning of the program (its semantics) is not correct.

5.13.3 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”.

Example of a program which generates runtime error.


#Runtime Errors Example
num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads
to runtime error
print(num1/num2)

You might also like