0% found this document useful (0 votes)
1 views46 pages

Module 1

Uploaded by

tharunhas7
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)
1 views46 pages

Module 1

Uploaded by

tharunhas7
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

Python Programming: 1BPLC105B

Python was developed by Guido van Rossum.


Python Programming language: Python is a popular programming language. It was created
by Guido van Rossum, and released in 1991.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

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.

Python Syntax compared to other programming languages


• Python was designed for readability, and has some similarities to the English language
with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.

What is a program: A computer program is a set of instructions (smallest unit of execution)


that are used to execute particular tasks to get particular results.
It is required for programmers to learn basic concepts of mathematics to write programs. For
different types of tasks, we have to write different programs. The set of instructions used to
perform a specific task to obtain a specific result is termed a computer program. The
computer program is generated by programmers or software developers. The code is then
processed and executed to provide the output of the program.
Computer Program Terminologies
1. Source Code: It is nothing but code written in High-level language that humans easily
understand.
2. Machine code: It is binary code that is easy to understand by computers or machines.
3. Compiler: It is used to translate the source code into machine code all at once.
4. Interpreter: It is used to execute the source code line by line converting it into
machine code.
5. Algorithm: It is nothing but a set of instructions to solve a problem.

What is debugging: In the context of software engineering, debugging is the process of


fixing a bug in the software. When there's a problem with software, programmers analyze the
code to figure out why things aren't working correctly. They use different debugging tools to
carefully go through the code, step by step, find the issue, and make the necessary
corrections.
Syntax errors: is defined as a fundamental mistake created in programming when the code
doesn’t follow the syntax rules of the programming language.

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.

Basis Syntax Semantics

It refers to the meaning


It refers to the rules of any statement in the associated with any
Meaning
programming language. statement in the
programming language

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.

There are two areas of


The syntax is the arrangement or order of
In semantics that are logical
words, determined by both the writer’s
linguistics semantics and lexical
style and grammar rules.
semantics.

The syntax is case sensitive in most Most of the semantics are


Sensitivity
programming languages. case-insensitive.
Experimental debugging:
Debugging in Python is facilitated by pdb module (python debugger) which comes built-in to
the Python standard library. It is actually defined as the class Pdb which internally makes use
of bdb(basic debugger functions) and cmd (support for line-oriented command interpreters)
modules. The major advantage of pdb is it runs purely in the command line, thereby making
it great for debugging code on remote servers when we don't have the privilege of a GUI-
based debugger.
pdb supports:
• Setting breakpoints
• Stepping through code
• Source code listing
• Viewing stack traces

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

Get the Type


You can get the data type of a variable with the type() function.
x=5
y = "Raj"
print(type(x))
print(type(y))

String variables can be declared either by using single or double quotes:


x = "Raj"
# is the same as
x = 'Raj'

Variable names are case-sensitive.


This will create two variables:
a=4
A = "Raj"
#A will not overwrite a

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.

Legal variable names:


myvar = "Raj"
my_var = "Raj"
_my_var = "Raj"
myVar = "Raj"
MYVAR = "Raj"
myvar2 = "Raj"
Illegal variable names:
2myvar = "Raj"
my-var = " Raj "
my var = " Raj "
Remember that variable names are case-sensitive
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "Raj"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "Raj"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "Raj"

Python Variables - Assign Multiple Values


Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of values, or else you will get
an error.
One Value to Multiple Variables
And you can assign the same value to multiple variables in one line:
x = y = z = "Orange"
print(x)
print(y)
print(z)

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)

You can also use the + operator to output multiple variables:


Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
For numbers, the + character works as a mathematical operator:
x=5
y = 10
print(x + y)
In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:

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:

Python Data Types


Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Text Type: Str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset

Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:
Print the data type of the variable x:
x=5
print(type(x))
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
x = 1 # int
y = 2.8 # float
z = 1j # complex
To verify the type of any object in Python, use the type() function:
print(type(x))
print(type(y))
print(type(z))

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

a = float(x) #convert from int to float:

b = int(y) #convert from float to int:

c = complex(x) #convert from int to 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

Operator Precedence and Associativity List in Python


Consider following list of operator precedence and associativity in Python. It shows all
operators from highest precedence to lowest precedence.
1. () : Parentheses (highest precedence) -> Associativity: Left to right
2. x[index], x[index:index] : Subscription, slicing -> Associativity: Left to right
3. await x : Await expression
4. ** : Exponentiation -> Associativity: Right to left
5. +x, -x, ~x : Unary plus, unary minus, bitwise NOT -> Associativity: Right to left
6. *, @, /, //, % : Multiplication, matrix multiplication, division, floor division,
remainder -> Associativity: Left to right
7. +, - : Addition and subtraction -> Associativity: Left to right
8. <<, >> : Bitwise shifts -> Associativity: Left to right
9. & : Bitwise AND -> Associativity: Left to right
10. ^ : Bitwise XOR -> Associativity: Left to right
11. | : Bitwise OR -> Associativity: Left to right
12. in, not in, is, is not, <, <=, >, >=, !=, == : Comparisons, membership, identity tests -
> Associativity: Left to right
13. not x : Boolean NOT -> Associativity: Right to left
14. and : Boolean AND -> Associativity: Left to right
15. or : Boolean OR -> Associativity: Left to right
16. if-else : Conditional expression -> Associativity: Right to left
17. lambda : Lambda expression
18. := : Assignment expression (Walrus operator) -> Associativity: Right to left
Note: Parentheses () have highest precedence and can override default order. Some
operators, like await and lambda, do not have associativity.
Operators Associativity
If an expression contains two or more operators with same precedence then Operator
Associativity is used. It can either be Left to Right or from Right to Left.
Expression:
100 / 10 * 10

Operators Precedence and Associativity


Operators Precedence and Associativity are two main characteristics of operators that
determine evaluation order of sub-expressions in the absence of brackets.
Expression:
100 + 200 / 10 - 3 * 10
Non-associative Operators
In Python, most operators have associativity, which means they are evaluated from left to
right or right to left when they have same precedence. However, there are a few operators that
are non-associative, meaning they cannot be chained together.
Example: This code demonstrates that = and += cannot be chained because they are non-
associative operators.
a=5
b = 10
c = 15
a = b = (a < b) += (b < c)
Output
a = b= (a < b) += (b < c)
^^
SyntaxError: invalid syntax
Explanation: = and += are non-associative; combining them in one expression causes a
syntax error.
Operations on strings
Single character we call character
More than one character we call string
R
R \0

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it
was found

format() Formats specified values in a string

format_map() Formats specified values from a dictionary in a string

index() Searches the string for a specified value and returns the position of where it
was found

isalnum() Returns True if all characters in the string are alphanumeric

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

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

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

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

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"))

islower(): to check given string is in lower case or not


txt = "Hello world!"
x = [Link]()
print(x)

replace(): to replace any string with new string


txt = "I like bananas"
x = [Link]("bananas", "apples")
print(x)

isalpha(): to check given string has alphabets or not


txt = "999"
x = [Link]()
print(x)
count():
txt = "I love apples, apple are my favorite fruit"
x = [Link]("are")
print(x)

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

Prompt A String, representing a default message before the input.

print('Enter your name:')


x = input()
print('Hello, ' + x)

Use the prompt parameter to write a message before the input:


x = input('Enter your name:')
print('Hello, ' + x)

Taking multiple inputs from user in Python


Using input() and split()
One of the simplest ways to take multiple inputs from a user in Python is by using the input()
function along with the split() method. The split() method splits a string into a list based on a
specified separator (by default, it uses whitespace).
# taking two inputs at a time
x, y, z = input("Values: ").split()
print(x)
print(y)
print(z)
How it Works:
• input() takes the full input as a single string.
• .split() divides the string into separate components based on whitespace by default.
• The values are assigned to individual variables (x, y, z).

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

name=input("\nEnter your name:")


usn=input("\nEnter your usn:")
marks1=int(input("\nEnter your marks in subject1:"))
marks2=int(input("\nEnter your marks in subject2:"))
marks3=int(input("\nEnter your marks in subject3:"))
total_marks=marks1+marks2+marks3
total_perc=float(total_marks/300)*100
total_perc=round(total_perc,2)
print("\n")
print("Students Details\n")
print("Name:"+name)
print("USN:"+usn)
print("Total marks obtained:"+str(total_marks))
print("Total Percentage:"+str(total_perc))
Iteration: Assignment, updating variables, the for loop, the while statement, the Collatz 3n+1
sequence tables, two-dimensional tables, break statement, continue statement, paired data,
nested loops for nested data.
Control statements: Selection statement, Looping statement, Iteration statement

Selection statement: simple if,


if(condition):
Execute block
Next statement
2. Develop a python program to read 2 numbers from the keyboard and perform the
basic arithmetic operations based on the choice. (1-Add, 2-Subtract, 3-Multiply, 4-
Division)
num1=int(input("Enter Number 1:"))
num2=int(input("Enter Number 2:"))
choice=int(input("Enter your choice: 1-Add, 2-Sub, 3-Multiply, 4-Division"))
if(choice==1):
print("Addition of two number is:",num1+num2)
if(choice==2):
print("Subtraction of two number is:",num1-num2)
if(choice==3):
print("Multiplication of two number is:",num1*num2)
if(choice==4):
print("Division of two number is:",num1/num2)
if(choice>4):
print("Invalid choice")

Develop a program to print todays date, month and year


# importing datetime module for now()
import datetime

# using now() to get current time


current_time = [Link]()

print ("The attributes of now() are : ") # Printing attributes of now().


print ("Year: ", end = "")
print (current_time.year)
print ("Month: ", end = "")
print (current_time.month)
print ("Day: ", end = "")
print (current_time.day)
If(condition) If(marks>35)
{ {
Execute if block PRINT(“PASS”)
} }
Else Else
{ {
Execute else block Print(“try again”)
} }
Next statement Next statement

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.

If(condition) If(2nd pu)


{ {
If(condition) If(behaviour)
{ {
Inner loop Inner loop
} }
Else Else
} }
else else
age = 30
member = True
if age > 18:
if member:
print("Ticket price is $12.")
else:
print("Ticket price is $20.")
else:
if member:
print("Ticket price is $8.")
else:
print("Ticket price is $10.")
Output
Ticket price is $12.
if-elif Statement
The if-elif statement is a shortcut for chaining multiple if-else conditions. While using if-elif
statement at the end else block is added which is performed if none of the above if-elif
statement is true.
Syntax
if (condition):
statement
elif (condition):
statement
else:
statement
letter = "A"
if letter == "B":
print("letter is B")
elif letter == "C":
print("letter is C")
elif letter == "A":
print("letter is A")
else:
print("letter isn't A, B or C")

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)

Program to Check Armstrong Number


A positive integer is called an Armstrong number (of order n) if
abcd... = an + bn + cn + dn +
In the case of an Armstrong number of 3 digits, the sum of cubes of each digit is equal to the
number itself. For example, 153 is an Armstrong number because
153 = 1*1*1 + 5*5*5 + 3*3*3
1+125+27
153 (armstrong number)
250= 2*2*2 + 5*5*5+0*0*0
8+125
133 (not a armstrong number)
result = 0
num=int(input("Enter a three-digit integer: "))
originalNum = num
while (originalNum != 0):
#remainder contains the last digit
remainder = originalNum % 10

result += remainder * remainder * remainder


#removing last digit from the orignal number
originalNum //= 10

if (result == num):
print("is an Armstrong number")
else:
print("is not an Armstrong number")

Program to Check Whether a Number is Palindrome or Not


An integer is a palindrome if the reverse of that number is equal to the original number.
Input: num = 171
Reverese =171 output : Palindrome
Num = 150
Reverse =051 output: Not a palindrome

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)

# Program to check if a number is prime or not


num = int(input("Enter a number: "))
for i in range(2, num):
# define a flag variable
flag = False
if num == 0 or num == 1:
print(num, "is not a prime number")
elif num > 1:
# check for factors
for i in range(2, num):
if (num % i) == 0:
# if factor is found, set flag to True
flag = True
# break out of loop
break
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
Collatz 3n+1 sequence
The “computational rule” for creating the sequence is to start from some given n, and to
generate the next term of the sequence from n, either by halving n, (whenever n is even), or
else by multiplying it by three and adding 1. The sequence terminates when n reaches 1.
n = 1027371
while(n!=1):
print(n, end=",")
if n%2 ==0:
n=n//2
else:
n=n*3+1
print(n, end=".\n")
Output:
1027371,3082114,1541057,4623172,2311586,1155793,3467380,1733690,866845,2600536,1
300268,650134,325067,975202,487601,1462804,731402,365701,1097104,548552,274276,1
37138,68569,205708,102854,51427,154282,77141,231424,115712,57856,28928,14464,7232
,3616,1808,904,452,226,113,340,170,85,256,128,64,32,16,8,4,2,1.

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

for x in range(11): # Generate numbers 0 to 10


print(x, “\t”, 2**x) # 2**x is equal to 2x

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.

Python continue Keyword


The continue keyword is used to end the current iteration in a for loop (or a while loop), and
continues to the next iteration.
for i in range(5):
if i == 3:
continue
print(i)
Output:
0
1
2
4
Python continue statement is a loop control statement that forces to execute the next
iteration of the loop while skipping the rest of the code inside the loop for the current
iteration only, i.e. when the continue statement is executed in the loop, the code inside the
loop following the continue statement will be skipped for the current iteration and the next
iteration of the loop will begin.
for i in range(1, 11):
if i == 6:
continue
print(i, end=" ")

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)]

Nested Loops for Nested Data:


A Nested loop is a loop inside a loop. The inner loop will be executed one time for each
iteration of the outer loop.
Eg:
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
Output:
14
15
24
25

Printing multiplication table using Python nested for loops


for i in range(2, 4):

# Printing inside the outer loop


# Running inner loop from 1 to 10
for j in range(1, 11):

# Printing inside the inner loop


print(i, "*", j, "=", i*j)
# Printing inside the outer loop
print()

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

Case-2: Hi, I am 27 My age is Suraj


4. Arbitrary Arguments
In Python Arbitrary Keyword Arguments, *args and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
• *args in Python (Non-Keyword Arguments)
• **kwargs in Python (Keyword Arguments)
This code separately shows non-keyword (*args) and keyword (**kwargs) arguments in the
same function.
def myFun(*args, **kwargs):
print("Non-Keyword Arguments (*args):")
for arg in args:
print(arg)

print("\nKeyword Arguments (**kwargs):")


for key, value in [Link]():
print(f"{key} == {value}")

# Function call with both types of arguments


myFun('Hey', 'Welcome', first='Raj', mid='for', last='kumar')

Output
Non-Keyword Arguments (*args):
Hey
Welcome

Keyword Arguments (**kwargs):


first == Raj
mid == for
last == kumar
Anonymous Functions
In Python, an anonymous function means that a function is without a name. def keyword is
used to define the normal functions and the lambda keyword is used to create anonymous
functions.
def cube(x): return x*x*x # without lambda
cube_l = lambda x : x*x*x # with lambda

print(cube(7))
print(cube_l(7))

Output
343
343

Return Statement in Function


The return statement ends a function and sends a value back to the caller. It can return any
data type, multiple values (packed into a tuple), or None if no value is given.
Syntax:
return [expression]
Parameters: return ends the function, [expression] is the optional value to return (defaults to
None).
def square_value(num):
"""This function returns the square
value of the entered number"""
return num**2

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

Write a program to print Fibonacci series


def fibonacci():
x, y = 0, 1
while True:
yield x
x, y = y, x + y

# Accept input from the user


n = int(input("Input the number of Fibonacci numbers you want to generate? "))
print("Number of first ",n,"Fibonacci numbers:")
fib = fibonacci()
for _ in range(n):
print(next(fib),end=" ")

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

Using a Recursive Approach


This Python program uses a recursive function to calculate the factorial of a given number.
The factorial is computed by multiplying the number with the factorial of its preceding
number.
def fact(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * fact(n - 1)

num = 5
print(fact(num))

Output
120

Write a function to calculate the factorial of a number. Develop a program to compute


binomial coefficient ( Given N and R)
def factorial(n):
if n == 0:
return 1
if n == 1:
return 1
return n*factorial(n-1)

def binomial_coefficient(n,r):
return factorial(n) // (factorial(r) * factorial(n-r))

n=int(input("Enter the value of n"))


r=int(input("Enter the value of r"))
print("Factorial of a number is:")
print(factorial(n))
print("Binomial coefficient for given n and r is:")
print(binomial_coefficient(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

You might also like