Module 1
Module 1
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.
Language syntax of programming languages can be defined as a set of rules and structures
that determine how the code should be written to be correctly translated and executed by the
compilers or interpreters.
Types of Syntax Error:
1. Missing Parentheses or Brackets: Forgetting to include closing parentheses ), square
brackets ], or curly braces {} can lead to syntax errors, especially in expressions,
function calls, or data structures.
2. Missing Semicolons: In languages that use semicolons to terminate statements (e.g.,
C, Java, JavaScript), omitting a semicolon at the end of a statement can result in a
syntax error.
3. Mismatched Quotes: Forgetting to close quotation marks ' or " around strings can lead
to syntax errors, as the interpreter/compiler will interpret everything until the next
matching quote as part of the string.
4. Incorrect Indentation: In languages like Python, incorrect indentation can cause
syntax errors, especially within control structures like loops, conditional statements,
or function definitions.
5. Misspelled Keywords or Identifiers: Misspelling keywords, variable names, function
names, or other identifiers can result in syntax errors. The interpreter/compiler won't
recognize these misspelled names, leading to errors.
Common Syntax Errors:
1. Violation of Language Rules: Syntax errors take place when a programmer writes
code that violates the syntax rules of the computer language that is established. These
rules dictate the proper use of parentheses, brackets, semicolons, quotation marks, and
other punctuation marks and the structure and organization of the expressions and
statements.
2. Compiler or Interpreter Detection: When you try to compile or execute code having
syntax errors, the compiler or interpreter goes through the code and lists down any
breaches of the rules of the language’s syntax. Then, it produces an error message
which pinpoints the exact place and nature of the errors.
3. Prevents Execution: Unlike runtime errors that happen while the program runs, syntax
errors do not allow the program to run at all. This is because the compiler or
interpreter cannot interpret the instructions given in the code because of their faulty
structure or grammar.
4. Common Causes: There are syntax errors that come about due to various mistakes
made by the programmer including misspelled keywords, missing or misplaced
punctuation, incorrect indentation, mismatching of parentheses or brackets, and
typographical errors. These mistakes are simple errors, but sometimes they can
produce prominent effects when they are not corrected.
5. Error Messages: When a grammar mistake is caught, the compiler or interpreter
usually signals it by generating an error message that tells about the nature of the
mistake and suggests fixing it like where it is located in the code and sometimes how
it should be changed. Making out the information and interpreting the error message
is the key to successful code debugging.
Runtime errors:
• A runtime error in a program is an error that occurs while the program is running after
being successfully compiled.
• Runtime errors are commonly called referred to as "bugs" and are often found during
the debugging process before the software is released.
• When runtime errors occur after a program has been distributed to the public,
developers often release patches, or small updates designed to fix the errors.
• While solving problems on online platforms, many run time errors can be faced,
which are not clearly specified in the message that comes with them. There are a
variety of runtime errors that occur such as logical errors, Input/Output
errors, undefined object errors, division by zero errors, and many more.
Types of Runtime Errors:
• SIGFPE: SIGFPE is a floating-point error. It is virtually always caused by a division
by 0. There can be mainly three main causes of SIGFPE error described as follows:
1. Division by Zero.
2. Modulo Operation by Zero.
3. Integer Overflow.
Semantic errors:
• It refers to the meaning associated with the statement in a programming language.
• It is all about the meaning of the statement which interprets the program easily.
• Errors are handled at runtime.
It referred to as a semantic
It is referred to as a syntax error. It is
error. It is generally
generally encountered at the compile time.
encountered at run time. It
It occurs when a statement that is not valid
occurs when a statement is
Error according to the grammar of the
syntactically valid but does
programming language. Some examples are
not do what the programmer
missing semicolons in C++, using
intended. This type of error is
undeclared variables in Java, etc.
tough to catch.
Python Variables
Variables: Variables are containers for storing data values.
Creating Variables: A variable is created the moment you first assign a value to it.
x=5
y = "Raj"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after
they have been set.
x=4 # x is of type int
x = "Raj" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• A variable name cannot be any of the Python keywords.
Output Variables
The Python print() function is often used to output variables.
x = "Python is awesome"
print(x)
In the print() function, you output multiple variables, separated by a comma:
Example
x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
x=5
y = "John"
print(x + y)
The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:
Integers:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex
Complex numbers are written with a "j" as the imaginary part:
Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Note: You cannot convert complex numbers into another number type.
Random Number
Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Import the random module, and display a random number from 1 to 9:
import random
print([Link](1, 10))
Python Casting
Specify a Variable Type
There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float literal (by removing
all decimals), or a string literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including strings, integer
literals and float literals
• Integers:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
• Floats:
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
w = float("4.2") # w will be 4.2
• Strings:
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'
Python Operators
Operators in general are used to perform operations on values and variables. These are
standard symbols used for logical and arithmetic operations. In this article, we will
look into different types of Python operators.
• OPERATORS: These are the special symbols. Eg- + , * , /, etc.
• OPERAND: It is the value on which the operator is applied.
Order of Operations
Operators Precedence
Operator precedence defines order in which Python evaluates different operators in an
expression. When an expression has multiple operators, Python follows precedence rules to
decide order of evaluation.
Expression:
10 + 20 * 30
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it
was found
index() Searches the string for a specified value and returns the position of where it
was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of
where it was found
rindex() Searches the string for a specified value and returns the last position of
where it was found
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
String Length: To find length of string we use len() function
Eg:
Method1:
a="Navkis"
length=len(a)
print(length)
Method2:
a = "Navkis"
print(len(a))
Method3:
print(len("Navkis"))
capitalize(): this function is used to capitalize first character of the given string
txt = "hello, and welcome to my world."
x = [Link]()
print (x)
Input function
The input() function allows user input.
Syntax: input(prompt)
Parameter Description
1. Develop a program to read the student details like name, USN and marks in three
subjects. Display the student details, total marks and percentage with suitable messages
Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not. (static program)
import sys
name=input("\n Enter your name:")
year=int(input("\n Enter your birth year:"))
if(year>=2025):
print("Invalid year")
[Link]()
age=2025-year
if(age>=60):
print(name + "is a senior citizen")
else:
print(name + "is not a senior citizen")
Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not. (dynamic program)
import sys
import datetime
current_time = [Link]() # using now() to get current time
name=input("\n Enter your name:")
year=int(input("\n Enter your birth year:"))
if(year>=current_time.year):
print("Invalid year")
[Link]()
age= current_time.year -year
if(age>=60):
print(name + "is a senior citizen")
else:
print(name + "is not a senior citizen")
Nested if Statement
A nested if statement in Python is an if statement located within another if or else clause. This
nesting can continue with multiple layers, allowing programmers to evaluate multiple
conditions sequentially. It's particularly useful in scenarios where multiple criteria need to be
checked before taking an action.
While loop: It is used to execute a block of statements repeatedly until a given condition is
satisfied. When the condition becomes false, the line immediately after the loop in the
program is executed.
While(condition) Do
{ {
statements Statement
}
}while(condition)
I=1 Do
While(i<3) {
{
Print(i)
Print(i) I=i+1
I=i+1 }while(i<3)
}
Demonstrate a program to print multiplication table using do loopn
multiplier = int(input("Enter a number:"))
counter = 1
while counter <= 10:
result = counter * multiplier
print(f"{counter} x {multiplier} = {result}")
counter += 1
Demonstrate a program to accept a number and find sum of the number using while
loop
input=12345
output=15
num = int(input("Enter a number:"))
sum = 0
while num > 0:
rem = num % 10
sum = sum + rem
num = num / 10
print(sum)
Method 2:
num = int(input("Enter a number:"))
sum = 0
while num > 0:
sum += num % 10 # extract last digit
num //= 10 # remove last digit
print(sum)
Demonstrate a program to find sum of first N Natural numbers using while loop
input = 10
output =55
num=int(input("Enter a number:"))
sum=0
i=1
while i<=num:
sum+=i
i+=1
print(sum)
if (result == num):
print("is an Armstrong number")
else:
print("is not an Armstrong number")
reversed = 0
n=int(input("Enter an integer: "))
original = n
#reversed integer is stored in reversed variable
while (n != 0):
remainder = n % 10
reversed = reversed * 10 + remainder
n = n // 10
#palindrome if orignal and reversed are equal
if (original == reversed):
print("is a palindrome.")
else:
print("is not a palindrome.")
/ Operator // Operator
This operator is used for true division. No This operator is used for floor division.
matter what the inputs are, result is always a Instead of keeping fractional part, it returns
floating-point number. Even if division is largest integer less than or equal to the
exact, Python still returns the result as a result. In other words, it rounds down
float. This operator preserves fractional part answer towards negative infinity.
of the result. Example: Here we divide 10 by 3 using //.
Example: Here we divide 10 by 3 using /. Unlike /, this operator removes the
Since / does true division, it keeps the fractional part.
decimal part.
res = 10 / 3 res = 10 // 3
print(res) print(res)
print(type(res)) print(type(res))
Output Output
3.3333333333333335 3
<class 'float'> <class 'int'>
For Loop
Python for loops are used for iterating over sequences like lists, tuples, strings and ranges.
• A for loop allows you to apply the same operation to every item within the loop.
• Using a for loop avoids the need to manually manage the index.
• A for loop can iterate over any iterable object, such as a dictionary, list or custom
iterator.
Python For Loop Syntax
for var in iterable:
# statements
pass
Note: In Python, for loops only implement the collection-based iteration.
Eg:
num = int(input("Enter a number: "))
for i in range(2, num):
print(i)
Starting with any positive integer N, Collatz sequence is defined corresponding to n as the
numbers formed by the following operations:
1. If n is even, then n = n / 2.
2. If n is odd, then n = 3*n + 1.
3. Repeat above steps, until it becomes 1.
Write a Python program where you take any positive integer n, if n is even, divide it by
2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process
until you reach 1.
the Collatz conjecture is a conjecture in mathematics named after Lothar Collatz, who first
proposed it in 1937. The conjecture is also known as the 3n + 1 conjecture.
The conjecture can be summarized as follows. Take any positive integer n. If n is even, divide
it by 2 to get n / 2. If n is odd, multiply it by 3 and add 1 to obtain 3n + 1. Repeat the process
(which has been called "Half Or Triple Plus One") indefinitely. The conjecture is that no
matter what number you start with, you will always eventually reach 1.
Example:
For instance, starting with n = 12, one gets the sequence 12, 6, 3, 10, 5, 16, 8, 4, 2, 1.
n = 19, for example, takes longer to reach 1: 19, 58, 29, 88, 44, 22, 11, 34, 17, 52, 26, 13, 40,
20, 10, 5, 16, 8, 4, 2, 1.
Tables: Before computers were readily available, people had to calculate logarithms, sines
and cosines by hand, to make easier mathematics books contained long tables listing the
values of these functions.
For some operations, computers use tables of values to get an approximate answer and then
perform computations to improve the approximation. In some cases, there have been errors in
the underlying tables.
Program to outputs a sequence of values in the left column and 2 raised to the power of
that value in the right column
Output
0 1
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
The string “\t” represents a tab character. The backslash character in “\t” indicates the
beginning of an escape sequence. Escape sequences are used to represent invisible characters
like tabs and newlines. The sequence \n represents a newline.
As characters and strings are displayed on the screen, an invisible marker called the cursor
keeps track of where the next character will go. After a print function, the cursor normally
goes to the beginning of the next line.
The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are
useful for making columns of text line up.
Because of the tab characters between the columns, the position of the second column does
not depend on the number of digits in the first column.
Two-dimensional tables
A two-dimensional table is a table where you read the value at the intersection of a row and a
column. A multiplication table is a good example
for i in range (1,11):
print(2*i, end =" ")
print()
output:
2 4 6 8 10 12 14 16 18 20
break Keyword
The break keyword is used to break out a for loop, or a while loop.
i = int(input(“ Enter a number:”))
while i < 5:
print(i)
if i == 3:
break
i += 1
print ("out of loop")
The break statement in Python is used to exit or "break" out of a loop (either a for or while
loop) prematurely, before the loop has iterated through all its items or reached its condition.
When the break statement is executed, the program immediately exits the loop, and the
control moves to the next line of code after the loop.
Explanation: When i == 6, the continue statement executes, skipping the print operation for
6.
Syntax
while True:
...
if x == 10:
continue
print(x)
Parameters: The continue statement does not take any parameters.
Returns: It does not return any value but alters the flow of the loop execution by skipping the
current iteration.
Paired data: Making a pair of things in python is simple as putting them into parentheses
Year_born = (“Raj kumar”, 1990)
We can put many pairs into a list of pairs
Year_born = [(“Raj Kumar”, 1990), (“Ram”, 1991), (“Ravi”, 1992)]
Output:
2*1=2 3*1=3
2*2=4 3*2=6
2*3=6 3*3=9
2*4=8 3 * 4 = 12
2 * 5 = 10 3 * 5 = 15
2 * 6 = 12 3 * 6 = 18
2 * 7 = 14 3 * 7 = 21
2 * 8 = 16 3 * 8 = 24
2 * 9 = 18 3 * 9 = 27
2 * 10 = 20 3 * 10 = 30
Functions:
Python Functions are a block of statements that does a specific task. Some commonly or
repeatedly done task together and make a function so that instead of writing the same code
again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
Defining a Function
We can define a function in Python, using the def keyword. A function might take input in
the form of parameters.
The syntax to declare a function is:
Here, we define a function using def that prints a welcome message when called.
def fun():
print("Welcome to Navkis")
Calling a Function
After creating a function in Python we can call it by using the name of the functions followed
by parenthesis containing parameters of that particular function.
def fun():
print("Welcome to Navkis")
fun() # Driver code to call a function
Output
Welcome to Navkis
Function Arguments
Arguments are the values passed inside the parenthesis of the function. A function can
have any number of arguments separated by a comma.
Syntax:
def function_name(parameters):
"""Docstring"""
# body of the function
return expression
We will create a simple function in Python to check whether the number passed as an
argument to the function is even or odd.
def evenOdd(x):
if (x % 2 == 0):
return "Even"
else:
return "Odd"
print(evenOdd(16))
print(evenOdd(7))
Output
Even
Odd
Types of Function Arguments
Python supports various types of arguments that can be passed at the time of the function call.
In Python, we have the following function argument types in Python, Let's explore them one
by one.
1. Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument.
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)
Output
x: 10
y: 50
2. Keyword Arguments
In keyword arguments, values are passed by explicitly specifying the parameter names, so the
order doesn’t matter.
def student(fname, lname):
print(fname, lname)
student(fname='Raj', lname='kumar')
student(lname='kumar', fname='Raj')
Output
Raj kumar
Raj kumar
3. Positional Arguments
In positional arguments, values are assigned to parameters based on their order in the
function call.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
print("Case-1:")
nameAge("Suraj", 27)
print("\nCase-2:")
nameAge(27, "Suraj")
Output
Case-1: Hi, I am Suraj My age is 27
Output
Non-Keyword Arguments (*args):
Hey
Welcome
print(cube(7))
print(cube_l(7))
Output
343
343
print(square_value(2))
print(square_value(-4))
Output
4
16
Recursive Functions
A recursive function is a function that calls itself to solve a problem. It is commonly used in
mathematical and divide-and-conquer problems. Always include a base case to avoid infinite
recursion.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(4))
Output
24
Print the Fibonacci sequence - Python
To print the Fibonacci sequence in Python, we need to generate a series of numbers where
each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci
sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is
the sum of the two previous numbers.
Mathematically, the Fibonacci sequence can be represented as:
F(n) = F(n-1) + F(n-2)
Where:
F(0) = 0
F(1) = 1
F(n) for n > 1 is the sum of the two preceding numbers.
The sequence looks like this:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Write a program to generate Fibonacci sequences of length (N).
n=int(input("Enter N - length of fibonacci sequence\n"))
if(n<0):
print("Invalid input")
elif(n==0):
print("0")
else:
a=0
b=1
print("The Fibonacci series is")
print(a)
print(b)
for i in range(2,n):
c=b
b=a+b
a=c
print(b)
Output:
Enter N - length of fibonacci sequence: 10
The Fibonacci series is
0
1
1
2
3
5
8
13
21
34
Output:
Input the number of Fibonacci numbers you want to generate? 10
Number of first 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34
Factorial of a Number - Python
The factorial of a number is the product of all positive integers less than or equal to that
number. For example, the factorial of 5 (denoted as 5!) is 5 × 4 × 3 × 2 × 1 = 120
Python program to find the factorial of a number
n=6
# Initialize the factorial variable to 1
fact = 1
# Calculate the factorial using a for loop
for i in range(1, n + 1):
fact *= i
print(fact)
Output
720
num = 5
print(fact(num))
Output
120
def binomial_coefficient(n,r):
return factorial(n) // (factorial(r) * factorial(n-r))
Output:
Enter the value of n5
Enter the value of r2
Factorial of a number is:
120
Binomial coefficient for given n and r is:
10