hapter – 3 (Python Programming Fundamentals)
Use this link to get more: https://www.w3schools.com/python/python_intro.asp
Character set is a set of valid characters recognized by Python. A character represents any letter, digit or any
other symbol. Python uses the Unicode character set.
A token is the smallest element of a Python script that is meaningful to the interpreter.
Token can be of following categories: Keyword, Identifier, Literal/Constant, Operator, Punctuator/ Delimiter.
Keywords are reserved words. Each keyword has a specific meaning to the Python interpreter. As Python
is case sensitive.
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.
Variable is an identifier whose value can change. Variable name should be unique in a program.
Remember that a variable has three main components: Identity, Type, and Value.
Identify refers to the object’s address in the memory which does not change once it has been created.
The address of an object can be checked using the method id(). Syntax: id(variable/object)
The type() function is used to determine the type of a variable, i.e., what type of value does it hold/point to.
Variables whose values can be changed after they are created and assigned values are called mutable
variables. Example: list, dictionary, etc.
Variables whose values cannot be changed after they are created and assigned values are called
immutable variables. Example: int, string, tuple, etc.
Note that, 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.
In Python, we can use an assignment statement to create new variables and assign specific values to them.
gender = 'M'
message = "Keep Smiling"
price = 987.9
Variables must always be assigned values before they are used in the program, otherwise it will lead to an
error.
Wherever a variable name occurs in the program, the interpreter replaces it with the value of that
particular variable.
Every value belongs to a specific data type in Python. Data type identifies the type of data which a variable can
hold and the operations that can be performed on those data.
Number data type stores numerical values only. It is further classified into three different types: int, float and
complex.
A Python sequence is an ordered collection of items, where each item is indexed by an integer value. Three
types of sequence data types available in Python are Strings, Lists and Tuples.
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 (for example ‘Hello’) or in double quotation
marks (for example “Hello”). The quotes are not a part of the string, they are used to mark the beginning and
end of the string for the interpreter. We cannot perform numerical operations on strings, even when the string
contains a numeric value. For example, str2 is a numeric string.
Python allows us to represent a string constituting non-graphic characters as well. Non-graphic characters are
those characters which cannot be directly typed from the keyboard such as backspace, tab spaces, carriage
return etc. These non-graphic characters are represented by using escape sequences.
An escape sequence is represented by a backslash (\) followed by one or more characters.
List is a sequence of items separated by commas and items are enclosed in square brackets [ ]. Note that items
may be of different date types.
Example: [5, 3.4, 'New Delhi', '20C', 45]
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 items in the tuple. Similar to List,
items may be of different data types.
Example: (10, 20, "Apple", 3.4, 'a')
Mapping is an unordered data type in Python. There is only one standard mapping data type in Python called
Dictionary.
Dictionary in Python holds data items in key-value pairs and Items 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. Keys are usually of string type and their values can be
of any data type. In order to access any value in the dictionary, we have to specify its key in square brackets [ ].
An operator is used to perform specific mathematical or logical operation on values. The values that the
operator works on are called operands.
Python supports arithmetic operators to perform the four basic arithmetic operations (+, -, *, /) as well as
modular division, floor division and exponentiation.
Relational operator compares the values of the operands on its either side and determines the relationship
among them. Example: >, >=, <, <=, ==, <> etc.
Assignment operator (=) assigns or changes the value of the variable on its left.
Note that, there should be one and only one variable on the left-hand side of the assignment operator. This
variable name is called the Left value or the L-value. There can be any valid expression on the right-hand side
of the assignment operator. This expression is called the Right value or R-value.
Syntax: L-value = R-value
A statement is an instruction that the Python interpreter can execute.
In Python, we can declare multiple variables in a single statement. It is used to enhance the readability of the
program.
Example: var1, var2, var3, … var-n = value1, value2, value3, …, value-n # for assigning multiple values
var1 = var2 = var3,= … = var-n = value # for assigning same value
There is a concept of shorthand assignment operator in programming language.
A shorthand or compound or augmented assignment operator is a combination of a binary operation and
assignment. Example: +=, -=, *=, /=, %=, **=, //=, etc.
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 its
either side.
Membership operator is used to check if a value is a member of the given sequence or not. Example: in, not in.
An expression in a program is a sequence of operators and operands to do an arithmetic or logical
computation.
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 valid expressions are:
- Assigning a value to a variable.
- Performing mathematical calculations using one or more variables.
- Comparing two values.
When an expression contains more than one operator, their precedence (order or hierarchy) determines
which operator should be applied first. Higher precedence operator is evaluated before the lower precedence
operator. In the following example, '*' and '/' have higher precedence than '+' and '-'.
Note that:
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.
Sometimes, we need to enter data or enter choices into a program. In Python, we have the input() function for
taking values entered by input device such as a keyboard.
The input() function prompts user to enter data. It accepts all user input (whether alphabets, numbers or
special character) as string.
The syntax for input() is: variable = input([Prompt])
Hear, Prompt is the string we may like to display on the screen prior to taking the input, but it is optional.
Remember that, input() function 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 (=).
Python uses the print() function to output data to standard output device — the screen. It evaluates the
expression before displaying it on the screen.
The syntax for print() is: print( ‘message’, [sept = ‘ ’, end = ‘\n’] ) OR
print(“message”, variable/value)
There is another function eval(), used to evaluate the value of a string. It takes a string as an argument,
evaluates this string as a number, and returns the numeric result. If the given argument is not a string, or if it
cannot be evaluated as a number, then it results in an error.
An arithmetic expression that uses numeric data of various types is known as mixed mode expression or
impure expression.
Note that, while executing an impure expression, the process of converting the value from one data type to
another is known as 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:
Explicit conversion, also called type casting, happens when data type conversion takes place deliberately, i.e.,
the programmer forces it in the program. Syntax: <new data type> (expression)
Example: int(), float(), str(), chr(), etc.
The int() function is used to convert the accepted string to an integer. If the entered string is non-numeric, an
error will be generated.
Implicit conversion, also known as coercion, happens when data type conversion is done automatically by
Python and is not instructed by the programmer.
An error or bug is exceptional, unusual and unexpected situation and it never part of the normal flow of a
program. Removing the bug or error is called debugging.
Due to errors, a program may not execute or may generate wrong output. Three types of errors are:
i) Syntax errors ii) Logical errors iii) Runtime errors
Like any programming language, Python has rules that determine how a program is to be written. This is called
syntax. The interpreter can interpret a statement of a program only if it is syntactically correct.
A syntax error is an error in the syntax of a sequence of characters or tokens. These types of errors are
generated when we violate the syntax of a programming language.
Syntax errors are errors that occur due to incorrect format of a Python statement.
If any syntax error is present in the program, the interpreter shows error message(s) and stops the execution
there. Such errors need to be removed before execution of the program.
A logical error/bug (called semantic error) does not stop execution but the program behaves incorrectly and
produces undesired /wrong output.
Example: To find the average of two numbers 10 and 12.
10 + 12/2 will result 16 or (10 + 12)/2 will results 11.
A runtime error occurs after Python interpreter interprets the code we write and the computer begins to
execute it. 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.
Examples:
- Division by zero
- performing an operation on incompatible types
- using an identifier which has not been defined
- accessing a list element, dictionary value or object attribute which does not exist
- trying to access a file which does not exist
A function refers to a set of statements or instructions grouped under a name that perform specified tasks.
Python has many predefined functions called built-in functions. We have already used two built-in functions
print() and input().
A module is a python file in which multiple functions are grouped together. These functions can be easily used
in a Python program by importing the module using ‘import’ command.
To use a built-in function we must know the following about that function:
• Function Name — name of the function.
• Arguments — While calling a function, we may pass value(s), called argument, enclosed in parenthesis, to
the function. The function works based on these values. A function may or may not have argument(s).
• Return Value − A function may or may not return one or more values. A function performs operations on the
basis of argument (s) passed to it and the result is passed back to the calling point. Some functions do not
return any value.
Python follows a particular style of indentation to define the code.
Indentation is shifting of a statement to the right of another statement or by adding white space before a
statement.
In Python, indentation is used to form suites (blocks of statements) which indicates that the group of
statements belongs to a particular block of code. A suite is a group of statements which is treated as a unit.
In other words, Indentation refers to the spaces at the beginning of a code line. Python uses indentation to
indicate a block of code.
Blocks of code in Python are denoted by line indentation, which is implemented using 4 spaces per
indentation level.
Comments are statements in a script that are ignored by the Python interpreter and therefore, have no effect
on the actual output of the code. Comments make the code more readable and understandable for human
beings.
In other words, Comments in Python are non-executable statements. It means the Python compiler will not
execute them. Comments are intended for human understanding, not for the Python compiler. Therefore they
are called non-executable statements. Two types of commenting features are available in Python: single-line
and multi-line comments.
A single-line comment begins with a hash (#) symbol and helps mention that the whole line should be
considered a comment until the end.
A multi-line comment is helpful when we need to comment on many lines. You can also use a single-line
comment, but using a multi-line instead of a single-line comment is easy to comment on multiple lines. In
Python, Triple double quotes (""") and single quotes (''') are used for Multi-line commenting. It is used at the
beginning and end of the block to comment on the entire block. Hence it is also called block comments.