Chapter 6
Chapter 6
INTRODUCTION
All computer actions are governed by IPO (Input, Process, Output) cycle. For every program, there is
certain Input, certain kind of Processing and an Output.
To transform some kind of input to certain output, you have to develop and execute a program.
A program is a set of instructions that govern the processing, i.e., a program forms the base for
processing.
The basic elements that a Python program can contain are character set, tokens, expressions, statements,
simple input and output, etc.
PYTHON CHARACTER SET
Character set is a set of valid characters that a programming language can recognize. A character represents
any letter, digit or any other symbol. Python supports Unicode encoding standard. The character set of
Python are:
Letters A – Z, a – z
Digits 0–9
Special symbols space + – * / ** \ ( ) [ ] { } // = != == < > ' " ''' . , ; : % ! & # <= >= @ _ (underscore)
Whitespaces Blank space, tabs (), carriage return (), newline, formfeed
Other characters Python can process all ASCII and Unicode characters as part of data or literals.
TOKENS IN PYTHON
The smallest individual unit in a program is known as a Token or a lexical unit. Python has the following
tokens:
1. Keywords
2. Identifiers (Names)
3. Literals
4. Operators
5. Punctuators
Keywords
A Keyword is a predefined word having special meaning reserved by the programming language.
A keyword must not be used as a normal identifier name.
Python programming language has the following keywords:
Identifiers (Names)
Identifiers are the names given to different parts of the program such as variables, functions, lists,
dictionaries, etc.
Python is case sensitive as it treats upper and lower-case characters differently.
Naming rules for Python identifiers:
Variable names must only be a non-keyword word with no spaces in between.
Variable names must be made up of only letters, numbers and underscore (_).
Variable names cannot begin with a number.
Examples for Valid and Invalid Identifiers
The following are some valid identifiers:
Myfile, DATE9_7_77, MYFILE, _DS, _CHK, FILE13, Z2TOZ9, _HJI3_JK
Literals / Values
Literals are data items that have a fixed / constant value. The various types of literals are:
1. String Literals
A string literal is a sequence of characters surrounded by single or double or triple quotes.
Single line strings must terminate in one line.
Multiline strings are strings spread across multiple lines. With single and double quotes, each line
other than the concluding line has an end character \ (backslash) but with triple quotes, no
backslash is needed.
In strings, you can include non-graphic characters through escape sequences as given below:
Size of Strings: Python determines the size of a string as the count of characters in the string. But if your
string literal has an escape sequence contained within it, then make sure to count the escape sequence as
one character. Some examples are:
'\\' Size is 1 (\\ is an escape sequence to represent backslash)
'abc' Size is 3
"\ab" Size is 2 (\a is an escape sequence, thus one character)
"Seema\'s pen" Size is 11 (For typing apostrophe (') sign, escape sequence \' has been used)
"Amy's" Size is 4 (Python allows a single quote without escape sequence in double-
quoted string and vice versa
For multiline strings created with triple quotes, while calculating size, the EOL (end-of-line) character at
the end of the line is also counted in the size. For example, if you have created a string Str3 as:
Str3='''a The enter keys are considered as EOL (end-of-line)
b characters and counted in the length of multi-line
c''' string.
then size of the string Str3 is 5 (three characters a, b, c and two EOL characters that follow characters
a and b respectively).
For multiline strings created with single / double quotes and backslash character at end of the line, while
calculating size, the backslashes are not counted in the size of the string; also you cannot put EOLs using
return key in single / double quoted multiline strings, e.g.,
Str4='a\
b\
c'
The size of string Str4 is 3 (only 3 characters, no backslash counted).
To check the size of the string, you can also type len(<stringname>) command on the Python
prompt in console window shell as shown below:
>>> Str3='''a
b
c'''
>>> Str4='a\
b\
c'
>>> len(Str3)
5
>>> len(Str4)
3
>>>
2. Numeric Literals:
These literals are numeric values and can be one of the following types:
a. int (signed integers) are the positive or negative whole numbers with no decimal point. The
integer literals can be written in:
Decimal form: an integer with only digits 1–9. e.g., 1234, 4100, etc.
Octal form: an integer beginning with 0o (zero followed by letter o)
e.g., 0o35, 0o77, etc.
In octal number system, 8 and 9 are invalid digits.
Hexadecimal form: an integer beginning with 0x (zero followed by letter x)
e.g., 0x73, 0xAF, etc.
Valid digits for hexadecimal numbers are 0 – 9 and A – F.
b. Floating Point or Real literals represent real numbers and are written with a decimal point
dividing the integer and fractional parts.
These literals can be written in fractional form e.g., –13.0, .75, 7. etc. or in Exponent form e.g.,
0.17E5, 3.E2, .6E4, etc.
c. Complex number literals are of the form a + bJ, where a and b are floats and J (or j) represents
√(−1), which is an imaginary number.
a is the real part of the number, and b is the imaginary part.
3. Boolean Literals
A Boolean literal in Python is used to represent one of the two Boolean values, i.e., True (Boolean
true) or False (Boolean false).
A Boolean literal can either have value as True or as False.
4. Special Literal (None)
Python has one special literal, which is None.
The None literal is used to indicate the absence of value.
Python can also store literal collections, in the form of tuples, lists, etc.
Operators
Operators perform some computation / action when applied to operands (i.e., variables and other objects) in
an expression.
Unary Operators: The operators that require one operand to operate upon. Following are some unary
operators:
+ Unary plus – Unary minus
~ Bitwise complement not Logical negation
Binary Operators: The operators that require two operands to operate upon. Following are some binary
operators:
The operators can be:
Arithmetic operators (+ Addition, – Subtraction, * Multiplication, / Division, % Remainder / Modulus,
** Exponent (raise to power), // Floor division)
Bitwise operators (& Bitwise AND, | Bitwise OR, ^ Bitwise exclusive OR [XOR]),
Shift operators (<< Shift left, >> Shift right),
Identity operators (is is the identity same ?, is not is the identity not same ?),
Relational operators (< Less than, > Greater than, <= Less than or equal to, >= Greater than or equal to,
== Equal to, != Not equal to),
Logical operators (and Logical AND, or Logical OR),
Assignment operator (= Assignment),
Membership operators (in, not in), and
Arithmetic-Assignment operators (+= Assign sum, –= Assign difference, *= Assign product,
/= Assign quotient, %= Assign remainder, **= Assign exponent, //= Assign floor division).
Punctuators
Symbols are used in programming languages to organize the program structure, and to indicate the
emphasis of expressions and statements.
Most common punctuators of Python programming language are:
'"#\()[]{}@:,.`=
BAREBONES OF A PYTHON PROGRAM
Variable Definition:
A variable is defined only when you assign some value to it. Using an undefined variable in an expression /
statement causes an error called NameError. For example, consider the following code fragment:
print(x)
x=20
print(x)
When you run the above code, it will produce an error for the first statement as:
NameError: name 'x' is not defined
The reason for above error is implicit; printing / using uncreated (undefined) variable results into error. So,
to correct the above code, you need to first assign something to x before using it in a statement.
x=0 # variable x created now
print(x)
x=20
print(x)
The above code will execute without any error.
Dynamic Typing
A variable pointing to a value of a certain type can be made to point to a value / object of different type.
Example:
X = 10
print (X)
X = “Hello World”
print (X)
With dynamic typing, Python makes a label refer to new value with new assignment.
Although Python is comfortable with changing types of a variable, the programmer is responsible for
ensuring right types for certain type of operations. For example,
x=10
y=0
y=x/2 # Legal, because two integers can be used in divide operation
x='Day' # Python is comfortable with dynamic typing
y=x/2 # ERROR! a string cannot be divided.
If you want to determine the type of a variable, you can use type() in following manger:
type(<variable name>)
For example, consider the following sequence of commands that uses type() three times:
>>> a=10
>>> type(a) # The type returned as int (integer)
<class 'int'>
>>> a=20.5
>>> type(a) # The type returned as float (floating-point number)
<class 'float'>
>>> a="hello"
>>> type(a) # The type returned as str (string)
<class 'str'>
Dynamic Typing vs. Static Typing
In static typing, a data type is attached with a variable when it is defined first and it is fixed, i.e., data type of
a variable cannot be changed, whereas there is no such restriction in dynamic typing.
Python supports dynamic typing.
The input() function always returns a value of string type. Python offers two functions int() and
float() to convert the values received through input() into int and float types.
The general usage of these functions in input() are:
<variable_name>=int(input(<prompt string>))
Or
<variable_name>=float(input(<prompt string>))
Example:
While inputting integer values using int() or float values using float() with input(), make sure that
the value being entered must be compatible to int type or float type (e.g., 'abc' cannot be converted to
int or float, hence it is not compatible).
You can change the value of separator character with sep argument of print ( ).
It appends a newline character at the end of the line unless you give your own end argument.
Example:
print("My name is Amit. ")
print("I am 16 years old. ")
will produce the output as:
My name is Amit.
I am 16 years old.
If you explicitly give an end argument with a print() function, then the print() will print the line and
end it with the string specified with the end argument, and not the newline character. For example,
print("My name is Amit. ", end = '$')
print("I am 16 years old.")
will print the output as:
My name is Amit. $I am 16 years old.