Python Basics-1 PDF
Python Basics-1 PDF
Python Basics-1 PDF
Python was created by Guido Van Rossum when he was working at CWI (Centrum Wiskunde
& Informatica) which is a National Research Institute for Mathematics and Computer Science in
Netherlands. The language was released in 1991. Python got its name from a BBC comedy series from
seventies called “Monty Python’s Flying Circus”. It is based on ABC programming languages.
Presently it is owned by Python Software Foundation (PSF).
It is a general purpose programming language which can be used for both scientific and non-
scientific programming.
It is free, open source and portable language.
It is a very simple, high level, loosely typed language with vast library of add–on modules.
It is excellent for beginners as the language is interpreted (It is processed at run-time by the
interpreter), hence gives immediate results.
The programs written in Python are easily readable and understandable.
It is easily compatible with other languages like C, C++ etc.
It is easy to learn and use.
It is case sensitive. i.e. Uppercase and Lowercase alphabets are different.
ADVANTAGES OF PYTHON:
1. Easy to Use: Python is compact and very easy to use Object Oriented language with very simple
syntax rules. It is programmer–friendly.
2. Expressive Language/Higher Productivity: Because of simple syntax and fewer lines of code,
it is more capable to express code's purpose than many other languages and hence program
development time is less.
3. Interpreted Language: Python interprets and executes the code line by line at a time. It makes
Python an easy–to–debug language and thus suitable for beginners and advanced users.
4. Completeness: Python Standard Library provides various modules for different functionalities.
For example, it can be used for different functionalities like email, web–pages, databases, GUI
development, network connections and many more. Hence no additional libraries to be installed.
5. Cross–Platform Language (Platform Independent/Portable): Python can run on different
platforms like Windows, Linux / Unix, Macintosh, Super Computers, Smart Phones etc. Hence
it portable language.
6. Free and Open Source: Python is freely available at free of cost and its source code is available
to every body for further improvement.
7. Syntax Highlighting: It allows to distinguish between input, output and error messages by
different color codes.
Limitations of Python:
1. Not the Fastest Language: Fully compiled languages are faster than interpreted languages.
Python is an interpreted language. Hence Python is not faster compared to fully compiled
languages.
2. Lesser Libraries: Python offers library support for almost all computing programs, but its
library is still not competent with languages like C, Java, Perl as they have larger collection of
libraries.
3. Not Strong on Type–Binding: Python is not strong on catching 'Type Mismatch'. For example,
a String value can be stored in a variable declared as an integer, where Python never complain
about it.
4. Not Easily Convertible: The syntax of Python language is simple but different compared to
other programming languages. Hence it is not easy to convert a program which is in Python into
other language.
Installing Python:
https://www.python.org/downloads/
Python distribution comes with:
Python IDLE
Python Interpreter
PIP (Python Package Installer/Manager)
WORKING IN PYTHON:
To write and run Python program, install Python interpreter in computer. IDLE (GUI integrated)
is the standard, most popular Python development environment. IDLE is an acronym of Integrated
Development and Learning Environment. It lets edit, run, and browse and debug Python Programs from
a single interface. This environment makes it easy to write programs.
Interactive Mode: As the name suggests, this mode allows to interact with OS and as soon as you type
command, you can see the output in the same window. This mode does not save commands in form of a
program. Some points to remember while working in interactive mode are:
This mode is suitable when running a few lines of code.
The symbol '>>>' is called Python command prompt, indicates that interpreter is ready to accept
command.
At the prompt, either a command or statement or expression can be given.
Alt+P and Alt+N are used to invoke and repeat prior commands provided interactive window.
The quit( ), exit(), Alt+F4, Ctrl+D or Ctrl+Q is used to exit Python command prompt.
Ctrl+F6 will restarts the shell.
Type credits at the prompt to get information about the organization involved in Python
development.
The commands copyright and license( ) can be used to know more about Python.
The command help( ), with empty parenthesis, will provides an interactive help.
The command help( ), with a command inside parenthesis, will provide an exclusive
help about required command.
To leave help and return to interactive mode, quit command can be used.
Script Mode: In script mode, Python program is to be typed in a file and then interpreter to be used to
execute the content of the file. Working in interactive mode is convenient for beginners and for testing
small pieces of code. But for coding more than few lines, code is to be saved so that it can be modified
and reused.
To create and run a Python script, the following steps to be used in IDLE:
1. File->Open OR File->New Window (for creating a new script file)
2. Write the Python code as function i.e. script(extension .py or .pyw)
3. Save it (Ctrl+S)
4. Execute it in interactive mode, by using RUN option (F5)
TOKENS:
The smallest individual unit in a program is known as Token. It is also called as Lexical Unit. Tokens
present in Python are:
(i) Identifiers (ii) Keywords (iii) Literals/Constants (iv) Operators (v) Punctuators/Delimiters
KEYWORDS: A keyword is a reserved word that has a predefined meaning to the interpreter. A
keyword must not be used as identifier. For checking/displaying the list of keywords available in
Python:
**All keywords are in lower case except True, False and None.
Literals / Constants: A literal or constant is a program element that will never change its values during
program execution. Python allows several kinds of literals like:
(i) String literals (ii) Numeric literals (iii) Boolean literals (iv) Special Literal-None
String Literals: A string literal is a sequence of characters enclosed in either single quotes or double
quotes. Either both single quotes and both double quotes to be used for a string. Example: "Python",
'Program' etc. A single quoted string inside double quotes and vice–versa is legal in Python. Ex: "Anu's"
and 'Anu"s' are valid.
Single–line Strings: The strings that create by enclosing text in single quotes or double quotes
are called single–line strings. Ex: "Python", 'Apple'
Numeric Literals: These literals are three types namely (i) Integer literals (ii) float literals (iii) complex
literals
Integer Literals: An integer constant must have at least one digit and must not contain any decimal
point. Different integer literals available are,
1. Decimal Integer Literals: It consists of a sequence of digits between 0 and 9 and does not start
with zero. Ex: 1234, –458 etc
2. Octal Integer Literals: It consists of a sequence of digits between 0 and 7. It begins with 0o(Digit
Zero Letter o) Ex: 0o24, 0o746 etc
3. Hexadecimal Literals: It consists of a sequence of hexadecimal values between 0–9 and A–F. It
begins with 0x. Ex: 0x14AC
Floating Point Literals: These are also called as Real Literals. These can be expressed in two forms
viz. Fractional Form and Exponent Form
1. Fractional Form: A real constant in fractional form must have at least one digit either before or
after decimal point. Ex; 2.0, 17.5, –14.6, –0.05, .3 (means 0.3), 6. (means 6.0)
2. Exponent Form: A real constant in exponent form consists of two parts mantissa and exponent.
The mantissa must be either an integer or a proper real constant. The mantissa is followed by a
letter E or e and the exponent. The exponent must be an integer.
Ex: 152E05, 1.52e07, 0.152E08, 152e+8,–0.172E–3, .25e–4
Boolean Literals: A Boolean literal represent one of the two Boolean values i.e. True or False. A
Boolean literal can either have value as True or as False.
IDENTIFIERS: An identifier is a name given to a program element such as variable, function, list,
dictionary etc. The rules to be followed while naming an identifier in Python are,
It may consist of letters (A–Z, a–z), digits (0–9), and underscore (_).
It must begin with a letter or an underscore.
It must not begin with a digit.
Uppercase and lowercase alphabets are different. For example sum, Sum, SUM all are different.
A keyword must not be used as an identifier.
It can be of any length. However, it is preferred to be short and meaningful.
Operators: An operator is a symbol that is used in a program in respect of some operation. Each
operation is denoted by some operator. For example the operation addition is denoted by + and the
operation “finding remainder” is denoted by %. Each programming language will have its own set of
operators.
The constants or variables that participate in the operation are called operands
6 + 4
Unary Operator: If an operator takes only one operand then it is called Unary Operator
Binary Operator: If an operator takes two operands then it is called Binary Operator.
Ternary Operator: If an operator takes three operands then it is called Ternary Operator
Punctuators/Delimiters: These are the symbols used in programming which can be used as separators
of values or to enclose some values. Some punctuators available in Python are, ' " # \ ( ) [ ] { } @ , : .
=
DATA TYPES:
A data type represents the type of data like character, integer, real, string etc. Different types
of data types in Python are,
Numbers: Number data type stores numerical values. This data type is immutable, mean that the value
of its object cannot be changed. These are of three different types:
Integers: Integers are the whole numbers like 100000, –99, 0, 17 etc. They have no decimal point.
Integers can be positive or negative. If an integer has no sign, then it is positive. There are two types of
Integers
int: While writing an integer value, commas must not be used to separate digits. Also integers
should not have leading zeros. The data type int can store any integer, either big or small.
Range of an integer in Python can be from -2147483648 to +2147483647, and long integer
has unlimited range, subject to available memory.
bool: These represent the truth values False and True, that resembles integers 0 and 1
respectively. The bool( ) function returns the boolean equivalent digit.
>>> bool(1)
True
>>> bool(0)
False
>>>bool_1 = (6>10)
>>>print(bool_1)
False
Floating Point Numbers / Real Numbers: Numbers with fractions or decimal point are called floating
point numbers. A floating point number will consist of sign (+,–) sequence of decimals digits and a dot
such as 0.0, –21.9, 0.98333328, 15.2963. These numbers can be written in two forms
(i) Fractional Form Examples 3500.75, 0.00005, 147.9101 etc
(ii) Exponent Form Examples 3.50075E03, 0.5E–04, 1.479101E02 etc
The advantage of floating point numbers over integers are, they can be used to represent much greater
range of values.
Complex Numbers: Complex number in python is made up of two floating point values, one each for
real and imaginary part. For accessing different parts of variable (object) x; we will use x.real and
x.imag. Imaginary part of the number is represented by j instead of i, so 1+0j denotes zero imaginary
part.
>>> c=2–3j
>>> c.real 2.0
>>> c.imag
–3.0
None: This is special data type with single value. It is used to signify the absence of value/false in a
situation. It is represented by None. It is used to define a null value, or no value at all. None is not the
same as 0, False, or an empty string.
>>> x=None
>>>print(x) None
VARIABLES:
A variable is a program element that can change its value during program execution. It is an
identifier that has a named location and refers to a value and that value can be processed during program
run. As a variable is an identifier, all the rules for naming an identifier are applicable for naming a
variable
Creating a Variable: A variable is created by assigning a value of desired type to it. For example, an
integer variable can be created by assigning an integer value, and a string variable can be created by
assigning a string. It is not possible to create a variable without assigning a value to it.
Dynamic Typing: A variable having a value of certain data type can be assigned with value of some
other data type. In this case, it automatically assumed to change the data type of that variable. This is
referred as Dynamic Typing
x = 10
print (x)
x = "Informatics Practices"
print(x)
This code will results in:
10
‘Informatics Practices’
VARIABLE INTERNALS:
The data or values are referred to as object. Similarly, a variable is also an object that refer to a value.
Every object has three key attributes associated to it. These are,
(i) type of object: The data type of a constant or variable can be displayed using type( ) statement with
the required argument.
Ex: >>> type(11)
<class 'int'>
>>> type(12.5)
<class 'float'>
>>> type(2+3j)
<class 'complex'>
>>> type('Vidyalaya')
<class 'str'>
(ii) value of object: The print( ) can be used to print the value of an object like a variable or constant.
(iii) id of an object: The id of an object is the memory location of it. The function id( ) is used for this
purpose.
Ex: >>>x=10
>>>id(x)
140715083070816
>>>y=20
>>>id(y)
140715083071136
>>>z=10
>>>id(z)
140715083070816
Input: The input( ) function is used to input during runtime of a program. But, this function always
returns a value of string type. i.e. even a number inputted using input( ) method is not a number and is
a string.
In the above case the value 10 inputted is assumed as string. Hence type of x is string.
To input as a number it is to be appropriately converted into desired data type, like below
>>>
print(a+2) 12
Output: The print( ) function is used for output to standard output device, monitor.
Syntax: print(object1, [object2, object3, , sep=' ' or separator_string, end=' ' or end_string])
Default value for separator is space.
Default value for end is newline(\n).
Remainder / >>>17%5
% Modulo Division 2
>>>2**3 >>>2**8
** Exponentiation 8 256
>>>16**.5
4.0
Integer Division >>>7//2 >>>3//2
// (or) Floor Division 3 1
Relational Operators:
ASCII values
American Standard Code for information Interchange
A-65, B-66,C-67.....
a-97, b-98,c-99,.....
Logical Operators:
Symbol Description
and If both the operands are true, then the condition becomes true
or If any one of the operand is true, then the condition becomes true
not Reverses the state of operand/condition
A B A and B A or B not A
True True True True False
True False False True False
False True False True True
False False False False True
Identity Operators:
Membership Operators:
Precedence of Operators:
While evaluating an expression the precedence of operators will be like below. It gives the order of
evaluation of operators in an expression. However the precedence can be changed by using parenthesis.
Operators Associativity is used when two operators of same precedence appear in an expression.
Associativity can be either Left to Right or Right to Left.
** - Right to Left
Assignment Operators – Right to Left
EXPRESSIONS:
2. Relational Expressions: An expression having literals and/or variables of any valid type and
relational operators is a relational expression
3. Logical Expressions: An expression having literals and/or variables of any valid type and
logical operators is a logical expression.
4. String Expressions: An expression that have string operands and results to string are string
expression.
Comments:
Single-Line Comment:
Multi-line Comment:
‘’’ This is a
Multiline
Comment ‘’’
“””This is a
Multiline
Comment “””
DEBUGGING:
A bug is an error caused in a program. Correcting an error is called Debugging. Different types of errors
that will be encountered while developing any application are as follows:
Syntax Errors
Runtime Errors
Logical Errors
Syntax Errors: A set of rules for writing a statement in a program is called Syntax. Hence, syntax errors
occur when the syntax rules of program are not followed. These errors are visible during interpretation of
program.
In case of syntax errors, program will never execute.
For example, parentheses mismatch the following statement will results into a syntax error.
d = (b * b – (4 * a * c)
Runtime Errors: These errors are so called because these will be occurred during runtime of
program. A program may be syntactically correct, but may generate errors during run time. For
example,
a = 10, b = 0
c=a/b
The above code is syntactically correct. But during runtime division with 0 is not possible and hence
error will be generated. These errors will cause abnormal termination of code.
Logical Errors: A program, without having any syntax and runtime errors, may give wrong results. The
errors that will give wrong results due to the mistakes made by programmer are called Logical Errors.
These errors are hard to locate. Consider the below example:
hin_marks = 82, eng_marks = 90, gk_marks = 94;
Non-graphic characters: which cannot be directly typed from the keyboard, backspace, tab,etc.
Example:
\n - new line
\b – backspace
\t - tab
\v – vertical tab
\’ – single quote
Etc.
Example:
string = 'That\'s my bag.'
print(string)
That’s my bag.
Type conversion:
Syntax:
(new_data type) (expression)
Example:
>>>x=50.75
>>>print(int(x))
50
Disadvantage:
There is a risk of data loss.
Example:
>>>Num1=10
>>>Num2=55.0
>>>Num3=Num1+Num2
>>>print(Num3)
65.0