Python Basics
Python Basics
Introduction to programming
• A program is a set of instructions instructing a computer to do specific tasks
• Software is a generic term used to describe computer programs - other terms include
scripts, applications, programs and a set of instructions
• System software includes device drivers, operating systems, compilers and utilities helping
the computer to operate more efficiently - serves as a base for application software -
responsible for managing hardware components
• Application software such as office suites, gaming applications, database systems and
educational software are intended to perform certain tasks - can be a single program or a
collection of small programs
1
3/2/2025
Programming languages
• Programs are created through programming languages to control the behavior and output
of a machine through accurate algorithms
Machine language
• All instructions, memory locations, numbers and characters are represented using 0s and 1s
• Advantages: it can run and execute very fast as the code will be directly executed by a
computer and the programs efficiently utilize memory
• Disadvantages: (a) almost impossible for human use because it consists entirely of 0s and
1s; (b) hard to maintain and debug; (c) no mathematical functions available; and (d) memory
locations are manipulated directly (requires keeping track of every memory location)
3
Programming languages
Assembly language
ADD 3, 5, result
SUB 1, 2, result
• Disadvantages: there are no symbolic names for memory locations - difficult to read -
machine-dependent (makes it difficult for portability)
2
3/2/2025
Programming languages
High-level language
• Programs are written in a form that is close to human language (enables the programmers
to just focus on the problem being solved)
• A program written in the high-level language is called source program or source code and
is any collection of human-readable computer instructions
• Advantages: easier to modify, faster to write code and debug and portable
• A compiler or interpreter is needed to translate the program (source code) into machine
language (the only language the computer understands)
• A compiler is a system software program that transforms the source code written in a high-
level programming language into machine language
Programming languages
• Compilers translate source code all at once and the computer then executes the machine
language that the compiler produced - generated machine language can be later executed
many times against different data each time
• Interpreter: an interpreter reads source code one statement at a time, translates the
statement into machine language, executes the machine language statement, and then
continues with the next statement
• Compiled code runs faster than an interpreted code - overall time is usually larger in
compiling and running than interpreting and running a program
3
3/2/2025
History of Python
• Python was conceived in the late 1980s, and its implementation was started in December
1989 by Guido van Rossum at the Centrum Wiskunde & Informatica (abbr. CWI; English:
National Research Institute for Mathematics and Computer Science) in the
Netherlands
• Python was named after the BBC TV Show Monty Python's Flying Circus
4
3/2/2025
Python basics
Identifiers
Keywords
Statements /
Expressions Arithmetic
Variables Assignment
Numbers
Operators Comparison
Boolean
Data types Logical
Strings
Indentation Bitwise
None
Comments Single-line
Input
Input / Output Multi-line
Output
Type-casting
Elements of Python
10
5
3/2/2025
• Spaces and special symbols like !, @, #, $, % etc. can neither be used as an identifier nor
as the part of an identifier
11
if import in is lambda
Keywords
12
6
3/2/2025
• Statements are everything that can make up a line (or several lines) of Python code - for
example, z = 1 is an assignment statement
• An expression is the arrangement of values and operators which are evaluated to make a
new value - expressions are statements as well
• A value is the representation of some entity like a letter or a number that can be manipulated
by a program
• A single value >>> 20 or a single variable >>> z or a combination of variable, operator and
value >>> z + 20 are all examples of expressions
13
>>> 8 + 2
10
• Same expression when used in Python program does not show any output altogether - one
need to explicitly print the result
14
7
3/2/2025
• Variable names can consist of any number of letters, underscores and digits
• Variable names are case-sensitive - e.g., computer and Computer are different variables
• Python variables use lowercase letters with words separated by underscores as necessary
to improve readability, like this whats_up and how_are_you (not strictly enforced, but
considered a best practice)
15
• Ensure variable names are descriptive and clear enough (this allows other programmers to
have an idea about what the variable is representing)
variable_name = expression
• Examples:
number = 100
values = 1000.0
name = “Python”
8
3/2/2025
Arithmetic operators
17
Arithmetic operators
18
9
3/2/2025
• Assignment operators are used for assigning the values generated after evaluating the right
operand to the left operand - assignment operation always works from right to left
• Simple assignment is done with the equal sign (=) and simply assigns the value of its right
operand to the variable on the left
• Compound assignment operators support shorthand notation for avoiding the repetition of
the left-side variable on the right side - they combine = operator with another operator with =
being placed at the end of original operator
19
10
3/2/2025
• When the values of two operands are to be compared then comparison operators are used
• The output of these comparison operators is always a Boolean value, either True or False
• Strings are compared letter by letter using their ASCII values - thus, “P” is less than “Q”, and
“Aston” is greater than “Asher”
21
Comparison operators
22
11
3/2/2025
• The logical operators are used for comparing or negating the logical values of their operands
and to return the resulting logical value
• The values of the operands on which the logical operators operate evaluate to either True or
False
• The result of the logical operator is always a Boolean value, either True or False
23
not Logical NOT Reverses the operand state not p results in False
Logical operators
P Q P and Q P or Q Not P
24
12
3/2/2025
• Bitwise operators treat their operands as a sequence 0s and 1s and perform bit-by-bit
operation, but they return standard Python numerical values
The value of p is 60 and q is 13
Name of
Operator Description Example
operator
& Binary AND Performs respective bit-wise logical AND p & q = 12 (0000 1100)
25
• Operator precedence determines the way in which operators are parsed with respect to
each other
• Operators with higher precedence become the operands of operators with lower precedence
• Associativity determines the way in which operators of the same precedence are parsed -
almost all the operators have left-to-right associativity
26
13
3/2/2025
() Parentheses Highest
** Exponent
+, - Addition, Subtraction
Operator precedence
<<, >> Bitwise shift operators
^ Bitwise XOR
| Bitwise OR
or Logical OR Lowest
27
• Integers, floating point numbers and complex numbers fall under Python numbers category
• Integer and floating points are separated by decimal points - 1 is an integer, 1.0 is floating
point number
• Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part
28
14
3/2/2025
• Boolean is essential while using conditional statements - since a condition is just a yes-or-no
question, the answer to that question is a Boolean value, either True or False
• The Boolean values, True and False, are treated as reserved words
3) Strings
• A string consists of a sequence of one or more characters, which can include letters,
numbers and other types of characters - a string can also contain spaces
• Single quotes or double quotes are used to represent strings, and it is also called a string
literal
29
4) None
• None is another special data type, frequently used to represent the absence of a value
• For example,
money = None
30
15
3/2/2025
• Any statement written under another statement with the same indentation is interpreted to
belong to the same code block - a next statement with less indentation to the left means the
end of the previous code block
• If a code block must be deeply nested, then the nested statements need to be indented
further to the right
31
Single-line comment
• The hash (#) symbol is used to start writing a comment - Hash (#) symbol makes all text
following it on the same line into a comment
• For example,
32
16
3/2/2025
• First method: the hash (#) symbol is placed at the beginning of each line
#This is
#multiline comments
#in Python
• Second method: use triple quotes, either ''' or ""“ - the triple quotes are generally used for
multiline strings, and they can be used as a multiline comment as well
'''This is
multiline comment
33
variable_name = input([prompt])
• The prompt gives an indication to user of the value that needs to be entered through the
keyboard - when the user presses Enter key, the program resumes and input returns what
the user typed as a string
• Even when the user inputs a number, it is treated as a string which should be converted to
number explicitly using appropriate type casting function
• Example:
34
17
3/2/2025
• The print function will print everything as strings and anything that is not already a string is
automatically converted to its string representation
• Example:
print("Hello World!!")
• The [Link]() method is used to insert the value of a variable, expression or an object
into another string and display it to the user as a single string
• The format() method uses its arguments to substitute an appropriate value for each format
code in the template
35
where p0, p1,... are called as positional arguments and, k0, k1,... are keyword
arguments with their assigned values of v0, v1,... respectively
• Positional arguments are a list of arguments that can be accessed with an index of
argument inside curly braces like {index} - index value starts from zero
• Keyword arguments are a list of arguments of type keyword = value, that can be accessed
with the name of the argument inside curly braces like {keyword}
• The str is a mixture of text and curly braces of indexed or keyword types - the indexed or
keyword curly braces are replaced by their corresponding argument values and is displayed
as a single string to the user
36
18
3/2/2025
print("I live in {0}".format(country)) The 0 inside the curly braces {0} is the
str index of the first (0th) argument
I live in India
• Example #2: a = 10
b = 20
• You can have as many arguments as you want if the indexes in curly braces have a
matching argument in the argument list
37
• These strings may contain replacement fields, which are expressions enclosed within curly
braces - the expressions are replaced with their values
• An f at the beginning of the string tells Python to allow any currently valid variable name
within the string
I live in India
38
19
3/2/2025
• Output:
39
40
20
3/2/2025
41
float_to_string = str(3.5)
42
21
3/2/2025
• The chr() function converts an integer into a string of one character whose ASCII code is
same as the integer - the integer value should be in the range of 0-255
• Example:
ascii_to_char = chr(100)
• Output:
43
• The complex() function is used to print a complex number with the value real + imag*j or
convert a string or number to a complex number
• If the first argument for the function is a string, it will be interpreted as a complex number
and the function must be called without a second parameter - the second parameter can
never be a string
• Each argument may be any numeric type (including complex) - if imag is omitted, it defaults
to zero and the function serves as a numeric conversion function like int(), long() and float() -
if both arguments are omitted, the complex() function returns 0j
44
22
3/2/2025
complex_with_string = complex("1")
complex_with_number = complex(5, 8)
• Output:
45
Python basics
Other related functions
• The ord() function returns an integer representing Unicode code point for the given Unicode
character
• The hex() function converts an integer number (of any size) to a lowercase hexadecimal
string prefixed with “0x”
• The oct() function converts an integer number (of any size) to a lowercase octal string
prefixed with “0o”
• The type() function returns the data type of the given object - for example type(1) returns
<class 'int’>, type(6.4) returns <class 'float’>, and so on
46
23
3/2/2025
• Python is also a strongly typed language as the interpreter keeps track of all the variables
types - in a strongly typed language, you are simply not allowed to do anything that’s
incompatible with the type of data you are working with
Traceback (most recent call last): Traceback indicates the occurrence of an error
47
Block of True
Block of instructions
Block of Block of
instructions #2 False
instructions #1 instructions #2
Block of
instructions #3
48
24
3/2/2025
if conditional_expression:
49
if conditional_expression:
else:
statement(s)
Statement(s) Statement(s)
else:
50
25
3/2/2025
• An if statement that contains another if statement either in its if block or else block is called a
Nested if statement
if conditional_expression1:
if conditional_expression2:
statement(s)
else:
statement(s)
else:
statement(s)
51
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
else:
else:
else:
52
26
3/2/2025
if conditional_expression1:
statement(s)
Only the first control
elif conditional_expression2: expression which evaluates
to True will be executed - if
statement(s) none of the conditional
expression is True, then the
elif conditional_expression3: else statement is executed
statement(s)
else:
statement(s)
53
Condition
True False
#1
Statement(s) Condition
#2
Flow diagram of
True False if…elif…else statement
Statement(s) Condition
#3 False
True
Statement(s) Condition
#... False
True
Statement(s)
Statement(s) of
else
27
3/2/2025
print(“Wrong input”)
else:
• The ternary operator is a one-line if…else statement - instead of using multi-line if…else
statements, a ternary operator is used If the conditional_expression evaluates to True,
then expression1 is to be executed and if the
conditional_expression is evaluated to be False,
• Syntax: then expression2 is to be executed
• Just like the nested if…else statement, it is also possible to write the nested ternary operator
• Syntax:
56
28
3/2/2025
print (“The bigger number is: ”, a) if a > b else print(“The bigger number is:”, b)
print (“The number is positive”) if a > 0 else print(“The number is negative”) if a < 0 else
print(“The number is zero”)
57
while conditional_expression:
statement(s) Condition
False
expr.
• While loop executes a set of statements repeatedly as
True Update expr.
long as the conditional_expression is true
Body of while loop
Statement
Program to demonstrate the while loop
Flow diagram of while loop
i=0
i=i+1
58
29
3/2/2025
statement(s)
False Test expr.
• The collection_of_items can be taken from the range() True Update expr.
• The for loop is used when we know the maximum Flow diagram of for loop
number of times the body of the loop is executed and
when we want to iterate over all the elements of a
collection such as string, list, tuple, etc.
59
• The start and step are optional - when omitted, they will have default values of 0 and 1
respectively
• Examples: range(10) will have range objects of (0, 1, 2, 3, 4, 5, 6, 7, 8, 9), range(1, 10) will
have range objects of (1, 2, 3, 4, 5, 6, 7, 8, 9), and range(1, 10, 2) will have range objects of
(1, 3, 5, 7, 9)
Program to demonstrate the for loop (program that will find the sum of first 9 numbers)
sum = 0
sum += i
30
3/2/2025
• The continue statement is used to skip the rest of the code inside the loop for the current
iteration (only) - the loop does not terminate but continues with the next iteration
• Syntax:
statement(s) statement(s)
if (condition): if (condition2)
continue continue
statement(s) statement(s)
61
• The break statement terminates the loop containing it - on encountering a break statement
inside a loop, the control jumps to the statement immediately after the body of the loop
• Syntax:
statement(s) statement(s)
if (condition): if (condition2):
break break
statement(s) statement(s)
statement(s) statement(s)
62
31
3/2/2025
• The pass statement refers to doing nothing (no code) - it just acts as a placeholder - it
means instead of writing nothing, we write pass
• Example:
for k in range(5): k=1
if (k == 3): while k in range(5):
pass if (k == 3):
else pass
print(k) else
print(“Outside the loop”) print(k)
k=k+1
print(“Outside the loop”)
63
• Any type of loop can be nested under any other loop - this means we can have a for-loop
inside another for-loop or a for-loop inside a while-loop or a while-loop nested inside another
while-loop or we may also have a while-loop nested inside a for-loop
• Example:
for k in range(5):
for m in range(5):
statement(s)
statement(s)
64
32
3/2/2025
• The length of the resulting array will be the length of the smallest array - rest of the items
on the bigger list after the length of the smaller list will be omitted
print(i,”\t”,j) (5+5j) 10
65
• The iterator iter() is a special data structure in Python - it can iterate over by using its index
starting at 0 and continuing until the last item of the sequence
• The iter() supports both sequence data and non-sequence datatypes (keys of a dictionary,
lines of a file, etc.) including user-defined objects
• An iterator has a special method next() to access the next value just like in any looping
structure where we increment the control variable
• An iterator accesses the next item by iterator.__next__() method - the iterator raises a stop
exception once all the items are exhausted
66
33
3/2/2025
i = iter(myTup)
while True:
try:
except StopIteration:
break
It is not possible to move backward, go back to the
beginning or copy an iterator - if we want to iterate
• Output: The next item in Tuple is 1 over the same objects again (or simultaneously),
then another iterator object needs to be used.
The next item in Tuple is two
67
• There are at least two distinguishable kinds of errors, viz., syntax errors and exceptions
a) Syntax errors
• Syntax errors (aka parsing errors) are perhaps the most common kind of error you get
while you are still learning Python
• Example: Output:
68
34
3/2/2025
• An exception is an unwanted event that interrupts the normal flow of the program - even a
syntactically correct statement or expression may cause such an exception during its
execution
• The program execution gets terminated when an exception occurs - we get a system-
generated error message in such cases
• Exception handling allows the programmer to provide a meaningful message to the user
about the issue rather than a system-generated message (which may not be
understandable to the user)
• The interpreter or built-in functions can generate the built-in exceptions while user-defined
exceptions are custom exceptions created by the user
69
>>> 10 * (1/0)
70
35
3/2/2025
• A try block consisting of one or more statements is used to partition the code that might be
affected by an exception
• The associated except blocks are used to handle any resulting exceptions thrown in the
try block
• If any statement within the try block throws an exception, control immediately shifts to the
catch block - if no exception is thrown in the try block, the catch block is skipped
• There can be one or more except blocks - multiple except blocks with different exception
names can be chained together
71
72
36
3/2/2025
• Only one except block is executed for each exception thrown - if no except block specifies a
matching exception name, an except block that does not have an exception name is
executed (if present in the code)
• Instead of having multiple except blocks with multiple exception names for different
exceptions, you can combine multiple exception names together separated by a comma
(aka parenthesized tuples) in a single except block
• You can also leave out the name of the exception after the except keyword (this is generally
not recommended as the code will now be catching different types of exceptions and
handling them in the same way)
73
• When handling exceptions, it is better to be as specific as possible and only catch what you
can handle
Write a program to repeatedly read numbers until the user enters done. Once done is entered,
print the total, count and average of numbers. If the user enters anything other than a number,
detect the mistake using try and except, print an error message and skip to next number.
total = 0
count = 0
while True:
74
37
3/2/2025
break
else:
try:
total += float(num)
except:
print("Invalid input")
continue
count += 1
75
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Average is 2.5
76
38