0% found this document useful (0 votes)
27 views47 pages

Ch2. Basics of Python Programming: Dr. Tulika Assistant Professor Department of Computer Science Miranda House

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)
27 views47 pages

Ch2. Basics of Python Programming: Dr. Tulika Assistant Professor Department of Computer Science Miranda House

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/ 47

CH2. BASICS OF PYTHON Dr.

Tulika
Assistant Professor

PROGRAMMING Department of Computer Science


Miranda House
REF. BOOK- KAMTHANE, A. N. & KAMTHANE, A. A.,
“PROGRAMMING AND PROBLEM SOLVING WITH
PYTHON”, 2ND EDITION, MCGRAW HILL EDUCATION,
2020.
2.1 INTRODUCTION
Computer programming languages are designed to process different kinds of data,
viz. numbers, characters and strings in the form of digits, alphabets, symbols etc. to
get a meaningful output known as result or information.
Thus, program written in any programming language consists of a set of instructions or
statements which executes a specific task in a sequential form.
Whereas all these instructions are written using specific words and symbols according
to syntax rules or the grammar of a language.
2.2 PYTHON CHARACTER SET
2.3 TOKEN
Each token corresponds to a substring of a statement. Python contains various types of
tokens.
2.3.1 Literal
Literals are numbers or strings or characters that appear directly in a program. A list
of some literals in Python is as follows:
Example
78 #Integer Literal
2l.98 #Floating Point Literal
‘Q’ #Character Literal
“Hello” #String Literal
2.3.2 Value and Type on Literals
To know the exact type of any value, Python offers an in-built method called type.
2.3.3 Keywords
Keywords are reserved words with fixed meanings assigned to them. Keywords
cannot be used as identifiers or variables.
2.3.4 Operator
Python contains various operators, viz. arithmetic, relational, logical and bitwise
operators
2.3.5 Delimiter
Delimiters are symbols that perform a special role in Python like grouping, punctuation
and assignment. Python uses the following symbols and symbol combinations as
delimiters.
2.3.6 Identifier/Variable
Identifier is the name used to find a variable, function, class or other objects. All identifiers
must
obey the following rules.
An identifier:
• Is a sequence of characters that consists of letters, digits and underscore
• Can be of any length
• Starts with a letter which can be either lower or upper case
• Can start with an underscore ‘_’
• Cannot start with a digit
• Cannot be a keyword.
Some examples of valid identifiers are Name, Roll_NO, A1, _Address etc.
Python gives a syntax error if a programmer writes an invalid identifier. Some examples of
invalid identifiers are First Name, 12Name, for, Salary@
2.4 PYTHON CORE DATA TYPE
2.4.1 Integer
From simple Mathematics, we know that an integer is a combination of positive and
negative numbers including (zero) 0.
Integer literals can be octal or hexadecimal in format.
To represent an octal, 0o, i.e. a zero and a lower or upper case letter O followed by
a sequence of digits from 0 to 7 is used.
Numbers can also be represented as hexadecimal (base 16) notation using 0x (zero
and the letter X) followed by a sequence of digits.
The int function converts a string or a number into a whole number to integer. The int
function removes everything after the decimal point.

2.4.2 Floating Point Number


The value of π (3.14) is an example of a real number in mathematics. It consists of a
whole number, decimal point and fractional part.
The float function converts a string into a floating-point number.
>>>float(‘10.23’)
10.23

2.4.3 Complex Number


A complex number is a number that can be expressed in the form a+bj, where a and
b are real numbers and j is an imaginary unit.
2.4.4 Boolean Type
The Boolean data type is represented in Python as type bool. It is a primitive data
type having one of the two values, viz. True or False.
2.4.5 String Type
A string literal or string in Python can be created using single, double and triple
quotes.
The str function is used to convert a number into a string.

print function is to display the contents on the screen.


Syntax of print() function:
print(argument)
The argument of the print function can be a value of any type int, str, float etc. It can
also be a value stored in a variable.
The print function automatically prints a linefeed (\n) to cause the output to advance
to the next line.
However, if you want to display the messages “Hello” “World” and “Good Bye” in
one line without using a single print statement, then you can invoke the print function
by passing a special argument named end=‘ ‘.
2.6 ASSIGNING VALUE TO A
VARIABLE
2.6.2 SCOPE OF A VARIABLE
Each variable has a scope. The scope of a variable is a part of the program where a
variable can be referenced.
>>> C = Count + 1
Traceback (most recent call last):
File “<pyshell#9>”, line 1, in <module>
C = Count + 1
NameError: name ‘Count’ is not defined
In the above example, we have written a statement as C = Count + 1, but when
Python tries to execute the above statement it raises an error, viz. “Count is not
defined”. To fix the above error in Python the variable must be assigned some value
before it is used in an expression.
2.7 MULTIPLE ASSIGNMENTS
Python supports simultaneous assignment to multiple variables. The syntax of multiple
assignments is
Var1, Var2, Var3, ………… = Exp1, Exp2, Exp3, …………… ExpN
2.8 STATEMENT IN PYTHON
A statement in python is a logical instruction that reads, interprets and executes. It is a
command that programmer gives to the program.
E.g.:
>>>a=10 #assignment statement
>>>b = 2
>>>a ** b # statement with expression
100
2.9 MULTILINE STATEMENT IN
PYTHON
Every statement in python ends with a newline character. Multiline statements in
python can be done using “Explicit line continuation” and “Implicit line continuation”.
Explicit line continuation
Done using ‘\’ (continuation character)
E.g.
>>>a = [1, 2,\
3, 4,\
5]
>>>a
[1, 2, 3 ,4 ,5]
Implicit line continuation
Without using ‘\’.
Can be used when statements or expressions are enclosed in [], () or {}.
E.g.
>>>result = (1+ 2 +
3+4+
5)
>>>result
15
2.10 WRITING SIMPLE PROGRAMS
IN PYTHON
STEP 1: Design an algorithm for the given problem.
STEP 2: Translate an algorithm to programming instructions or code.
2.11 THE INPUT() FUNCTION
The input() function is used to accept an input from a user.
Syntax
Variable_Name = input()
OR
Variable_Name = input(‘String’)
Note: The input function produces
only string. Therefore, in the above
program even if the user enters a
numeric, i.e. integer value, Python
returns the type of input value as string.
2.12 THE EVAL() FUNCTION
It takes a string as parameter and returns it as if it is a Python expression. For
example, if we try to run the statement eval(‘print(“Hello”)’) in Python interactive
mode, it will actually run the statement print(“Hello”).
2.12.1 Apply eval() to input() Function
X = int (input(‘Enter the Number’))
can be written as:
X = eval(input(‘Enter the Number’))
With respective to the above statement, a programmer does not know what values a
user can enter. He/she may enter a value of any type, i.e. int, float, string, complex
etc. By making use of eval, Python automatically determines the type of value
entered by the user.
2.13 FORMATTING NUMBER AND
STRINGS
A formatting string helps make string look presentable to the user for printing. A
programmer can make use of format function to return a formatted string.
The syntax of format function is
format(item, format-specifier)
item is the number or string and format-specifier is a string that specifies how the item
is formatted.
Example: ‘.2f’ is the format specifier which tells the Python interpreter to display only
two digits after the decimal point.
2.13.1 Formatting Floating Point Numbers
If the item is a float value, we can make use of specifiers to give the width and
precision. We can use format function in the form width.precisionf.
Precision specifies the number of digits after the decimal point and width specifies the
width of the resultant string. In width.precisionf ‘f’ is called conversion code. ‘f’
indicates the formatting for floating point numbers.
2.13.2 Justifying Format
By default, the integer number is right justified. You can insert < in the format
specifier to specify an item to be left justified.
2.13.3 Integer Formatting
In case of integer formatting, you can make use of conversion code d and x. d
indicates that the integer is to be formatted, whereas x specifies that the integer is
formatted into a hexadecimal integer.

2.13.4 Formatting String


A programmer can make use of conversion code s to format a string with a specified
width. However, by default, string is left justified.
2.13.5 Formatting as a Percentage
The conversion code % is used to format a number as a percentage. The following
example illustrates the same.
Example
>>> print(format(0.31456,”10.2%”))
31.46%
>>> print(format(3.1,”10.2%”))
310.00%
>>> print(format(1.765,”10.2%”))
176.50%
2.13.6 Formatting Scientific Notation
While formatting floating point numbers we have used the conversion code f.
However, if we want to format a given floating point number in scientific notation then
the conversion code e will be used. An example of formatting floating point numbers
is given as follows:
Example
>>> print(format(31.2345,”10.2e”))
3.12e+01
>>> print(format(131.2345,”10.2e”))
1.31e+02
2.14 PYTHON INBUILT FUNCTIONS
2.14.1 THE ORD AND CHR
FUNCTIONS
A string is a sequence of characters. It can include both text and numbers.
All these characters are stored in a computer as a sequence of 0s and 1s. Therefore,
a process of mapping a character to its binary representation is called character
encoding.
There are different ways to encode a character. The encoding scheme decides the
manner in which characters are encoded. The American Standard Code for
Information Interchangeable ( ASCII) is one of the most popular encoding schemes. It is
a 7-bit encoding scheme for representation of all lower and upper case letters, digits
and punctuation marks.
The ASCII uses numbers from 0 to 127 to represent all characters. Python uses the
in-built function ord(ch) to return the ASCII value for a given character.
The chr(Code) returns the character corresponding to its code, i.e. the ASCII value.

You might also like