UNIT 1
1
Syllabus
UNIT 1: Python Basics and Functions and Modules
Syntax and Semantic Basics
Data types: strings, integers, floats, Variable assignments and expressions,
Basic input/output operations
Defining and calling functions: Function parameters and return values-
Using built-in modules, Creating and using custom modules, Exception
handling basics
2
What is Python
• Python is a general purpose, dynamic, high-level, and interpreted
programming language.
• It supports Object Oriented programming approach to develop
applications.
• It is simple and easy to learn and provides lots of high-level data
structures.
3
Python History
Guido van Rossum
• Guido van Rossum was a fan of the popular BBC comedy show of that time, "Monty
Python's Flying Circus".
• He decided to pick the name Python for his newly created programming language.
4
Why learn Python?
• Python provides many useful features to the programmer. These
features make it most popular and widely used language.
❑Easy to use and Learn
❑Interpreted Language
❑Object-Oriented Language
❑Open Source Language
❑GUI Programming Support
❑Wide Range of Libraries and Frameworks
5
Where is Python used?
• Python is a general-purpose, popular programming language and it is
used in almost every technical field.
❑Data Science
❑Web Applications
❑Mobile Applications
❑Software Development
❑Artificial Intelligence
❑Machine Learning
6
Identifiers and Keywords
• Python is a case-sensitive language.
• Python identifier is a name used to identify a variable, function, class,
module, or other object.
• Rules for creating identifiers:
o Starts with the alphabet or an underscore. Followed by zero or more letters,_,
and digits.
o Keyword cannot be used as an identifier.
• All keywords are in lowercase.
• Python has 36 keywords
7
Variables
• Variables are containers for storing data values.
8
The rules to name a variable are given below.
• The first character of the variable must be an alphabet or underscore ( _ ).
• All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore, or digit (0-9).
• Variable name must not contain any white-space, or special character (!, @,
#, %, ^, &, *).
• Variable name must not be similar to any keyword defined in the language.
• Variable names are case sensitive; for example, myname, and MyName is
not the same.
• Examples of valid variables: a123, _n, n_9, etc.
• Examples of invalid variables: 1a, n%4, n 9, etc.
9
x=5
y = "John"
print(x)
print(y)
10
Python Data Types
Python supports 3 categories of data types:
• Basic types - int, float, complex, bool, string, bytes
• Container types - list, tuple, set, dictionary
• User-defined types - class
11
Integer and Float Ranges
int can be of any arbitrary size.
a = 123
b=1234567890
c = 123456789012345678901234567890
• Python has arbitrary precision integers.
• Arithmetic operations can be performed on integers without worrying
about overflow/underflow
12
• Floats are represented internally in binary as 64-bit double-precision
values, as per the IEEE 754 standard.
• As per this standard, the maximum value a float can have is
approximately 1.8 x 10308. A number greater than this is represented
as inf (short for infinity).
13
Variable Type and Assignment
• There is no need to define the type of a variable.
• During execution, the type of the variable is inferred from the
context in which it is being used.
• Hence Python is called a dynamically typed language
14
Examples
a=25
b=3.314
c= “hi”
15
Multiple variable assignment
• a=10; pi = 31.4; name = "Sanjay
• a, pi, name=10, 3.14, Sanjay
• a=b=c=d=5
16
• Write a Python program to swap two variables without a temp
variable.
17
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
18
Write a Python Program to Find the Square Root
Hint : num ** 0.5
19
Write a Python Program to Calculate the Area of a Circle
Write a Python Program to Calculate the Area of a Square
Write a Python Program to Calculate the Area of a Rectangle
20
Write a Python Program to convert temperature in Celsius to
Fahrenheit
fahrenheit = celsius * 1.8 + 32
21
Python If-else statements
• Decision making is the most important aspect of almost all the
programming languages.
• As the name implies, decision making allows us to run a particular
block of code for a particular decision.
• Here, the decisions are made on the validity of the particular
conditions.
• Condition checking is the backbone of decision making.
22
If Statement
• The if statement is used to test a specific condition.
• If the condition is true, a block of code (if-block) will be executed.
23
24
The syntax of the if-statement is given below.
if expression:
statement
25
The if-else statement
• The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
• If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.
26
27
if condition:
#block of statements
else:
#another block of statements (else-block)
28
Example
1. Write a Program to check whether a person is eligible to vote or
not.
2. Write a Program to check whether a number is even or not.
3. Write a Python Program to Find the Largest Among two Numbers
29
if...elif...else Statement
Syntax of if...elif...else
30
Flowchart of if...elif...else
31
• Write a Python Program to Find the Largest Among Three Numbers
32
33
34
For Loop
A for loop is used for iterating over a sequence
Syntax of for Loop
35
Flowchart of for Loop
36
The range() Function
• To loop through a set of code a specified number of times, we can use
the range() function,
• The range() function returns a sequence of numbers, starting from 0
by default, and increments by 1 (by default), and ends at a specified
number.
37
for x in range(6):
print(x)
38
while loop
The while loop in Python is used to iterate over a block of code as long
as the test expression (condition) is true.
Syntax of while Loop in Python
39
• Print First 10 natural numbers using while loop
40
break statement
• The break statement terminates the loop containing it.
• Control of the program flows to the statement immediately after the
body of the loop.
41
42
43
continue statement
• The continue statement is used to skip the rest of the code inside a
loop for the current iteration only.
• Loop does not terminate but continues on with the next iteration.
44
45
46
• Write a program to accept a number from a user and calculate the
sum of all numbers from 1 to a given number
• For example, if the user entered 10 the output should be 55
(1+2+3+4+5+6+7+8+9+10)
47
• Write a program to print multiplication table of a given number
48
• Write a program to count the total number of digits in a number
using a while loop.
• For example, the number is 75869, so the output should be 5.
49
Question
Write a program to find the sum of the digits of a given number
For example: if a user enters 123
Sum of digits is 6 (1+2+3)
50
Question
Write a program to display the reverse of the number
For example:
INPUT: 12345
OUTPUT: 54321
51
Question
Write a program to print the factorial of a number
For example:
INPUT: 6
OUTPUT: 720
52
Question
Write a program to check whether the number entered is an Armstrong
number or not
For example:
153 = 13+53+33
=1+125+27
= 153
53
Question
Write a program to calculate the sum of numbers from 1 to 20 which
are not divisible by 2,3 or 5
54
PYTHON STRINGS
55
Strings
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.
• 'hello' is the same as "hello"
56
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
a = ”””III SEM,
Dept. of CSE,
Graphic Era University ””””
print(a)
57
Strings indexing and splitting
• Like other languages, the indexing of the Python strings starts from 0.
• For example, The string "HELLO" is indexed as given below
58
• The slice operator [] is used to access the individual characters of the string.
• However, we can use the : (colon) operator in Python to access the substring
from the given string
59
Negative Indexing and Slicing
The negative slicing in the string; it starts from the rightmost character,
which is indicated as -1. The second rightmost index indicates -2, and
so on.
60
61
62
63
String Properties
• Python strings are immutable-they cannot be changed.
• Strings can be concatenated using +.
• Strings can be replicated during printing.
• Whether one string is part of another can be found out using in.
64
Built-in Function
str=“python”
• len(str)
• max(str)
• min(str)
65
String Methods
66
Test Functions
• isalpha() checks if all characters in string are alphabets
• isdigit() checks if all characters in a string are digits
• isalnum() checks if all characters in a string are alphabets or digits
• islower() checks if all characters in a string are lowercase alphabets
• isupper() checks if all characters in a string are uppercase alphabets
• startswith() checks if a string starts with a value
• endswith() checks if a string ends with a value
67
68
Search and replace
• find() searches for a value, returns its position
• replace() replace one value with another
69
70
Trims Whitespace
• lstrip() removes whitespace from the left of a string including \t
• rstrip() removes whitespace from the right of a string including \t
• strip() removes whitespace from left and right
71
split and partition
• split() split the string at a specified separator string
• partition() partitions the string into 3 parts at the first occurrence of the specified
string
• join() joins string to each element of string1 except the last
72
73
String Conversion
• upper()
• lower()
• capitalize()
• title()
• swapcase()
74
String Comparison
Two strings can be compared using operators
• ==
• !=
•<
•>
• <=
• >=
75
76
Functions
77
Python function is a block of code that performs a specific and well-
defined task.
Two main advantages of function are:
(a) They help us divide our program into multiple tasks. For each task,
we can define a function. This makes the code modular.
(b) Functions provide a reuse mechanism. The same function can be
called any number of times.
78
There are two types of Python functions:
(a) Built-in functions - Ex. len(), sorted(), min(), max(), etc.
(b) User-defined functions
79
80
Python convention for function names:
• Always use lowercase characters
• Connect multiple words using _
• Example: cal_si(), split_data(), etc.
81
Communication with Functions
Communication with functions is done using parameters/arguments
passed to it and the value(s) returned from it.
82
83
Types of Arguments
Arguments in a Python function can be of 4 types:
(a) Positional arguments
(b) Keyword arguments
(c) Variable-length positional arguments
(d) Variable-length keyword arguments
• Positional and keyword arguments are often called 'required' arguments
• variable-length arguments are called 'optional' arguments.
84
Positional arguments
• Positional arguments must be passed in correct positional order.
• For example, if a function expects an int, float and string to be passed
to it, then while calling this function the arguments must be passed in
the same order.
85
86
Keyword arguments
• Keyword arguments can be passed out of order.
• Python interpreter uses keywords (variable names) to match the
values passed with the arguments used in the function definition.
87
88
• In a call we can use positional as well as keyword arguments.
• If we do so, the positional arguments must precede keyword
arguments.
89
Question
Write a program to receive three integers from the keyboard and get
their sum and product calculated through a user-defined function
cal_sum_prod().
90
Question
Write a program that defines a function count_alphabets_digits() that
accepts a string and calculates the number of alphabets and digits in it.
91
Question
Write a program that defines a function count_lower_upper()
that accepts a string and calculates the number of uppercase
and lowercase alphabets in it.
92
Question
Pangram is a sentence that uses every letter of the alphabet.
Write a program that checks whether a given string is pangram or not,
through a user-defined function ispangram()
93
Question
Write a Python program that accepts a hyphen-separated sequence of
words as input and calls a function convert() which converts it into a
hyphen-separated sequence after sorting them alphabetically. For
example, if the input string is
'here-come-the-dots-followed-by-dashes'
then, the converted string should be
'by-come-dashes-dots-followed-here-the’
94
Variable-length positional arguments
• Sometimes number of positional arguments to be passed to a
function is not certain.
• In such cases, variable-length positional arguments can be received
using *args
95
• args used in the definition of student is a tuple, indicating that it will hold all
the arguments passed to the student.
• The tuple can be iterated by using a for loop
96
Variable-length keyword arguments
• Sometimes number of keyword arguments to be passed to a function
is not certain.
• In such cases, variable-length keyword arguments can be received
using **kwargs.
97
• kwargs used in the definition of student() is a dictionary containing variable
names as keys and their values as values.
• ** indicates that it will hold all the arguments passed to student().
98
• We can use any other names in place of args and kwargs.
• We cannot use more than one args and more than one kwargs while
defining a function.
99
Question
A palindrome is a word or phrase which reads the same in both
directions. Given below are some palindromic strings:
deed
level
Malayalam
Rats live on no evil star
Murder for a jar of red rum
Write a program that defines a function ispalindrome(), which checks
whether a given string is a palindrome or not. Ignore spaces and case
mismatches while checking for palindrome.
100