0% found this document useful (0 votes)
5 views138 pages

Python Coding Latest Update

The document provides a comprehensive overview of various Python programming concepts, including data types, input handling, type casting, string manipulation, arithmetic, comparison, logical, and bitwise operators. It includes examples and outputs for each concept, demonstrating how to use Python effectively for basic programming tasks. Additionally, it covers built-in functions and string methods that facilitate string handling and manipulation.

Uploaded by

orbitramesh85
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views138 pages

Python Coding Latest Update

The document provides a comprehensive overview of various Python programming concepts, including data types, input handling, type casting, string manipulation, arithmetic, comparison, logical, and bitwise operators. It includes examples and outputs for each concept, demonstrating how to use Python effectively for basic programming tasks. Additionally, it covers built-in functions and string methods that facilitate string handling and manipulation.

Uploaded by

orbitramesh85
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Execercise:[Link]

com/python-
exercises/date-time-exercise/[Link]
Python

1)import keyword
print([Link])

Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async',
'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
'return',
'try', 'while', 'with', 'yield']
2) Source Code
Getting input in Python
#Getting String input Statement
name=input("Enter Name : ")
print(type(name))
print(name)

#Getting Integer input Statement


a=int(input("Enter The Value of A : "))
b=int(input("Enter The Value of B : "))
c=a+b
print(c)
print(type(a))

#Getting Float input Statement


a=float(input("Enter The Value of A : "))
b=float(input("Enter The Value of B : "))
c=a+b
print(c)
print(type(a))

Output
Enter Name : Tuttor
<class 'str'>
Tuttor
Enter The Value of A : 23
Enter The Value of B : 12
35
<class 'int'>
Enter The Value of A : 34.45
Enter The Value of B : 23.76
58.21000000000001
<class 'float'>

3) name1,name2,name3=input("Enter 3 Names : ").split()


print("Name 1 : ",name1)
print("Name 2 : ",name2)
print("Name 3 : ",name3)
name1,name2,name3=input("Enter 3 Names : ").split(',')
print("Name 1 : ",name1)
print("Name 2 : ",name2)
print("Name 3 : ",name3)

Output
Enter 3 Names : Ram kumar siva
Name 1 : Ram
Name 2 : kumar
Name 3 : siva
Enter 3 Names : Ram kumar,Sam kumar,siva kumar
Name 1 : Ram kumar
Name 2 : Sam kumar
Name 3 : siva kumar

4) a="""
Lorem Ipsum is simply dummy text of the printing and
typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s,
"""
print(type(a))
print(a)

para=[]
print("Enter a Para : ")

while True:
line=input()
if line:
[Link](line)
else:
break
print(para)
output='\n'.join(para)

print(output)

Output
<class 'str'>

Lorem Ipsum is simply dummy text of the printing and


typesetting industry. Lorem Ipsum has been the industry's
standard dummy text ever since the 1500s,

Enter a Para :
Ram is Good
HE is in Salem

['Ram is Good', 'HE is in Salem']


Ram is Good
HE is in Salem

5) # Basic Program in Python


# Basic Program in Python
# Basic Program in Python
'''
Basic Program in Python
Basic Program in Python
Basic Program in Python
Basic Program in Python
Basic Program in Python
'''
a = 10
b = 20
c=a+b
print(c)
Output
30

19-10-24 excersis
6) Type Casting in Python

In Python, type casting is the process of converting one data


type to another. Python is a dynamically-typed language, which
means that the data type of a variable can change based on
the value assigned to it. However, sometimes you may need to
convert a variable from one data type to another.
There are several built-in functions in Python that can be used
for type casting:

 int(): Converts a value to an integer.


 float(): Converts a value to a floating-point number.
 str(): Converts a value to a string.
 bool(): Converts a value to a Boolean (True or False).

This is a simple program in Python that performs the following


operations:

 Accepts two integer inputs from the user, a and b.


 Adds a and b and stores the result in a variable c.
 Converts the result stored in c to a string using
the str() function.
 Prints the message "Total : " followed by the result stored
in c.

In this program, the user inputs are obtained using


the input() function and then cast to integers using int(). The
result of the addition of a and b is then stored in c, and to
display it, the c is first converted to a string using str() before it's
concatenated with the string "Total : " using the + operator.
Finally, the result is displayed on the screen using
the print() function.
Source Code
"""
a = 10.0
print(a)
print(type(a))
b = int(a)
print(b)
print(type(b))

int()
float()
str()
"""
a = int(input("Enter The Value of A : "))
b = int(input("Enter The Value of B : "))
c=a+b
print("Total : " + str(c))
To download raw file Click Here
Output
Enter The Value of A : 20
Enter The Value of B : 20
Total : 40
7)String and String
Functions in Python
Python has several built-in functions associated with the string
data type. These functions let us easily modify and manipulate
strings. Creating Strings is the simplest and easy to use in
Python. To create a string in Python, we simply enclose a text
in single as well as double-quotes.

 type() => The returns the type of the object.


 upper() => All the characters in a given string are uppers
case.
 lower() => All the characters in a given string are lower
case.
 capitalize() => The first character is the upper case
 The title() => The first character in every word of the string
is an upper case.
 count() => Finds the number of times a specified value in
the given string.
 find() => Finds the first occurrence of the specified value.
 replace() => Replaces a specified phrase with another
specified phrase.
 isalnum() => Checks whether all the characters in a given
string is alphanumeric or not
 isalpha() => returns True if all the characters in the string
are alphabets
 islower() => Checks if all characters in the string are
lowercase
 isupper() => Checks if all characters in the string are
uppercase
 strip() => The used to trim whitespaces from the string
object

# String And String Function


s = "orbit computer"
print(s)
print(type(s))
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]("t"))
print([Link]("ED"))
print([Link]("o"))
print([Link]("o", 5))
print([Link]("o", '0'))
a = "joes1234"
print("Is Upper : ", [Link]())
print("Is Lower : ", [Link]())
print("Is Alpha Numeric : ", [Link]())
print("Is Alpha : ", [Link]())
s = "he\nis\ngood"
print(s)
print([Link]())
print([Link](True))
a = "orbit computer education"
print([Link](" "))
a = "orbit computer education"
print([Link](","))
s=" orbit "
print(len(s))
print(len([Link]()))
print(len([Link]()))
print(len([Link]()))
s='12-03-2020'
print([Link]('-'))
Output

orbit Joes

TUTOR JOES
tutor joes
Tutor joes
Tutor Joes
2
False
3
7
tut0r J0es
Is Upper : False
Is Lower : True
Is Alpha Numeric : True
Is Alpha : False
he
is
good
['he', 'is', 'good']
['he\n', 'is\n', 'good']
['Tutor', 'Joes', 'Computer', 'Education']
['Tutor', 'Joes', 'Computer', 'Education']
13
4
9
8
('12', '-', '03-2020')

8)String
Manipulation in
Python
String manipulation is a process of manipulating the string,
such as slicing, parsing, analyzing, etc. String slicing in python
programming is all about fetching a substring from a given
string by slicing it from a start to end index.
Syntax :
s [ start : end ]
s [ start : ]
s [ : end ]
s[::]
This program is using the concept of slicing in python, which
allows you to extract a portion of a string by specifying a range
of indices.
The following operations are performed in the above code:

 print(s): This line will print the original string "sample".


 print(s[0:2]): This line uses slicing to extract a substring of
the original string "sa", starting at index 0 and ending at
index 2 (not included).
 print(s[:5]): This line uses slicing to extract a substring of
the original string "sampl", starting at index 0 and ending
at index 5 (not included).
 print(s[1:]): This line uses slicing to extract a substring of
the original string "ample", starting at index 1 and going till
the end of the string.
 print(s[-1]): This line uses slicing to extract the last
character of the string "e" by specifying the index as -1, as
in python, negative index is used to access elements from
the end of the list.
 print(s[-2:-1]): This line uses slicing to extract the second
last character of the string "l" by specifying the range as -2
to -1, as in python

# String Manipulation
'''
S a m p l e
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
'''
s = "sample"
print(s)
print(s[0:2])
print(s[:5])
print(s[1:])
print(s[-1])
print(s[-2:-1])
print(s[:-1])
print(s[::-1])

Output

sample
sa
sampl
ample
e
l
sampl
elpmas

[Link]
Operators in Python
Arithmetic operators are used to perform mathematical
operations like addition, subtraction, multiplication ,division and
also python have floor division,exponentiation.

 Addition ( + ) => This operator is a binary operator and is


used to add two operands.
 Subtraction ( - ) => This operator is a binary operator and
is used to subtract two operands.
 Multiplication ( * ) => This operator is a binary operator
and is used to multiply two operands.
 Division ( / ) => This is a binary operator that is used to
divide the first operand(dividend) by the second
operand(divisor) and give the quotient as result.
 Modulus ( % ) => This is a binary operator that is used to
return the remainder when the first operand(dividend) is
divided by the second operand(divisor).
 Exponentiation ( * * ) => The performs exponential (power)
calculation on operators
 Floor division ( / / ) => The division of operands where the
result is the quotient in which the digits after the decimal
point are removed.

Source Code
# Arithmetic operators
"""
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor division

"""
a = 123
b = 10
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(2**3)

Output
133
113
1230
12.3
12
3
8

[Link] Operators or Relational


Operators in Python

A comparison operator in python, also called python relational


operators are used to establish some sort of relationship
between the two operands. Some of the relevant examples
could be less than, greater than or equal to operators.
Relational operators compares the values of two operands and
returns TRUE or FALSE based on whether the condition is
met.

Operator uses

== Equal operator

!= Not Equal operator

< Less than operator

> Greater than operator

<= Less than or equal to operator

>= Greater than or equal to operator

The program is using comparison operators in Python to


compare the values of two variables a and b.

 a = 20: This line assigns the value 20 to the variable a.


 b = 20: This line assigns the value 20 to the variable b.
 print(a == b): This line uses the comparison operator == to
check if the value of a is equal to the value of b. The
output will be True because 20 is equal to 20.
 print(a != b): This line uses the comparison operator != to
check if the value of a is not equal to the value of b. The
output will be False because 20 is equal to 20.
 print(a > b): This line uses the comparison operator > to
check if the value of a is greater than the value of b. The
output will be False because 20 is not greater than 20.
 print(a < b): This line uses the comparison operator < to
check if the value of a is less than the value of b. The
output will be False because 20 is not less than 20.
 print(a >= b): This line uses the comparison operator >= to
check if the value of a is greater than or equal to the value
of b. The output will be True because 20 is equal to 20.
 print(a <= b): This line uses the comparison operator <= to
check if the value of a is less than or equal to the value of
b. The output will be True because 20 is equal to 20.

Source Code
# Comparison Operators or Relational
Operators
"""
== Equal
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

"""
a = 20
b = 20
print(a == b)
print(a != b)
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
Output

True
False
False
False
True
True
[Link] Operators in Python

Logical operators are used to combine multiple conditions in a


single expression in Python. The three logical operators in
Python are and, or, and not.

 and: This operator returns True if both the conditions on


either side of the operator are True, otherwise it returns
False.
 or: This operator returns True if either of the conditions on
either side of the operator is True, otherwise it returns
False.
 not: This operator inverts the truth value of a single
condition. If a condition is True, the not operator will make
it False and vice versa.

This program is using logical operators in Python to check if the


value of a variable a falls within a certain range.

 a = 25: This line assigns the value 25 to the variable a.


 print(a >= 10 and a <= 20): This line uses the logical
operator and to check if the value of a is greater than or
equal to 10 AND less than or equal to 20. Since 25 is not
in the range 10 to 20, the output will be False.
 print(a >= 10 or a <= 20): This line uses the logical
operator or to check if the value of a is greater than or
equal to 10 OR less than or equal to 20. Since 25 is
greater than 10 the output will be true
 print(not(a >= 10 and a <= 20)): This line uses the logical
operator not to check if the value of a is not in the range of
10 to 20. The output will be True because 25 is not in the
range 10 to 20.

Source Code
# Logical Operators in Python
"""
and
or
not

"""
a = 25
print(a >= 10 and a <= 20)
print(a >= 10 or a <= 20)
print(not(a >= 10 and a <= 20))

Output
False
True
True

[Link] Operators in Python

In Python, bitwise operators are used to perform bitwise


calculations on integers. The integers are first converted into
binary and then operations are performed on bit by bit, hence
the name bitwise operators. Then the result is returned in
decimal format. Bitwise AND operator: Returns 1 if both the bits
are 1 else 0

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ Bitwise NOT

<< Left shift

>> Right shift


This program uses bitwise operations in Python.

 a & b: The "&" operator performs a bitwise AND operation,


resulting in the value 9 (binary representation of 25 is
11001 and 45 is 101101, so the AND operation is 100001
which is 9 in decimal).
 a | b: The "|" operator performs a bitwise OR operation,
resulting in the value 61 (binary representation of 25 is
11001 and 45 is 101101, so the OR operation is 111101
which is 61 in decimal).
 a ^ b: The "^" operator performs a bitwise XOR operation,
resulting in the value 52 (binary representation of 25 is
11001 and 45 is 101101, so the XOR operation is 010100
which is 52 in decimal).
 ~a: The "~" operator performs a bitwise NOT operation,
resulting in the value -26 (in binary, the NOT of 11001 is
00110, which is -26 in two's complement).
 a << 2: The "<<" operator performs a bitwise left shift
operation, resulting in 100 (the binary representation of 25
is 11001, so the left shift operation is 100100 which is 100
in decimal).
 a >> 2: The ">>" operator performs a bitwise right shift
operation, resulting in 6 (the binary representation of 25 is
11001, so the right shift operation is 00110 which is 6 in
decimal).

Source Code
# Bitwise Operators
"""
& AND
| OR
^ XOR
~ NOT
<< Zero fill left shift
>> Signed right shift
"""
a = 25
b = 45
print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 2)
print(a >> 2)
9
61
52
-26
100
6
26-10-24 online class
[Link] Statement in Python

The if statement is the most basic of all the control flow


statements. It tells your program to execute a certain section of
code only if a particular test evaluates to true. The if statement
is written with the if keyword.
Syntax :
if ( condition ) :
// body of the statements will execute if the condition
is true
This program is a simple implementation of an "if-else"
statement in Python to check whether a given number is even
or odd.

 n = int(input("Enter The Number : ")) - This line takes the


input from the user and converts it to an integer.
 if n % 2 == 0: - The "if" statement checks if the value of n
divided by 2 has a remainder of 0. If it's true, the following
indented block of code is executed.
 print(n, " is Even Number") - If the condition in the if
statement is true, this line will print the message "n is
Even Number".

The program checks if the given number is even or odd by


checking if it's divisible by 2 (i.e. n % 2 == 0), and if it is, the
program outputs the message "n is Even Number".

Source Code
# IF Statement in Python

n = int(input("Enter The Number : "))


if n % 2 == 0:
print(n, " is Even Number")
Output

Enter The Number : 34


34 is Even Number

14IF - Else Statement in Python


The if-else statement is used to execute both the true part and
the false part of a given condition. If the condition is true, the if
block code is executed and if the condition is false, the else
block code is executed.
Syntax :
if ( condition ) :
// body of the statements will execute if the condition
is true
else :
// body of the statements will execute if the condition
is false
This program is a simple Python script that prompts the user to
enter their name and age, and then checks if the entered age is
greater than or equal to 18. If the age is greater than or equal to
18, the program prints a message stating that the person is
eligible to vote, along with their name and age. If the age is less
than 18, the program prints a message stating that the person
is not eligible to vote, along with their name and age.

Source Code
# IF Else Statement in Python

name = input("Enter Your Name : ")


age = int(input("Enter Your Age : "))
if age >= 18:
print(name, " age is ", age, " Eligible
for Vote.")
else:
print(name, " age is ", age, " Not
Eligible for Vote.")
To download raw file Click Here
Output
Enter Your Name : Ram
Enter Your Age : 23
Ram age is 23 Eligible for Vote.

15Elif Statement in Python

The elif condition is used to multiple conditional expressions


after the if condition or between the if and else conditions. The
elif block is executed if the specified condition evaluates to
True.
Syntax :
if ( condition 1 ) :
// body of the statements will execute if the condition1
is true
elif ( condition 2 ) :
// body of the statements will execute if the condition2
is true
.
.
else :
// body of the statements will execute if the condition1
is false condition2 is False
This program is a Python script that prompts the user to enter a
number of days and then calculates a fine based on that
number.

 It starts by using the input() function to ask the user to


enter a number of days, which is stored in
the "days" variable.
 Then, the program uses an if-elif block to check the value
of the "days" variable against a series of conditions.
 If the value of "days" is equal to 0, the program
prints "Good No Fine"
 If the value of "days" is greater than or equal to 1 and less
than or equal to 5, the program calculates the fine as 0.5 *
days and prints the fine amount
 If the value of "days" is greater than 5 and less than or
equal to 10, the program calculates the fine as 1 *
days and prints the fine amount
 If the value of "days" is greater than 10 and less than or
equal to 30, the program calculates the fine as 5 *
days and prints the fine amount
 If none of the above conditions are met, the program will
print "Membership Cancel"

So the program is checking the number of days and based on


the number of days it is calculating the fine.
Source Code
# elif Statement in Python
"""
0 No Fine
1-5 0.5
5-10 1
10-30 5
>30 Membership Cancel
"""
days = int(input("Enter The Days : "))
if days == 0:
print("Good No Fine")
elif days >= 1 and days <= 5:
print("Fine Amount : ", days * 0.5)
elif days > 5 and days <= 10:
print("Fine Amount : ", days * 1)
elif days > 10 and days <= 30:
print("Fine Amount : ", days * 5)
else:
print("Membership Cancel")
To download raw file Click Here
Output
Enter The Days : 5
Fine Amount : 2.5

16. Nested If Statement in Python


Nested If Statement means to place one If inside another If
Statement. Nested ifs are very common in programming. when
you nest ifs, the main thing to remember is that an else
statement always refers to the nearest if statement that is within
the same block as the else and that is not already associated
with an else.
Syntax:
if ( Expression 1 ) :
// Executes when the Expression 1 is true
if ( Expression 2 ) :
// Executes when the Expression 2 is true
This program is a Python script that prompts the user to enter
three marks, then calculates the total and average of those
marks, and then uses if-else statements to determine the result
and grade based on the marks.

 It starts by using the input() function to ask the user to


enter three marks, m1, m2, and m3, which are then stored
in variables. The program then calculates the total of the
marks by adding the three marks and stores it in the
variable 'total' and also calculates the average of the
marks by dividing total with 3.0 and stores it in the variable
'average'
 Then, the program uses an if-elif block to check the value
of the three marks against a series of conditions.
 If all three marks are greater than or equal to 35, the
program will print "Result : Pass" and then again check the
average of the marks and calculate the grade If average is
greater than or equal to 90 and less than or equal to 100,
the program will print "Grade : A" If average is greater than
or equal to 80 and less than or equal to 89, the program
will print "Grade : B" If average is greater than or equal to
70 and less than or equal to 79, the program will
print "Grade : C" If none of the above conditions are met,
the program will print "Grade : D"
 If any of the three marks is less than 35, the program will
print "Result : Fail" and "Grade : No Grade"

So the program is checking the student's three marks,


calculating the total and average of the marks, and then
determining the result and grade based on the marks and
average.

Source Code
# Nested If Statement in Python
"""
3 Marks as Input
Total
Average
Result
If Pass Grade
90-100 A
80-89 B
70-79 C
Else D
"""
m1 = int(input("Enter Mark-1 : "))
m2 = int(input("Enter Mark-2 : "))
m3 = int(input("Enter Mark-3 : "))
total = m1 + m2 + m3
average = total / 3.0
print("Total : ", total)
print("Average : ", average)
if m1 >= 35 and m2 >= 35 and m3 >= 35:
print("Result : Pass")
if average >= 90 and average <= 100:
print("Grade : A")
elif average >= 80 and average <= 89:
print("Grade : B")
elif average >= 70 and average <= 79:
print("Grade : C")
else:
print("Grade : D")
else:
print("Result : Fail")
print("Grade : No Grade")
To download raw file Click Here
Output
Enter Mark-1 : 90
Enter Mark-2 : 90
Enter Mark-3 : 90
Total : 270
Average : 90.0
Result : Pass
Grade : A

Python simple programme

1)print("Hello, World!")

Output

Hello world
2) import sys

print([Link])

3) Python Indentation
if 5 > 2:

print("Five is greater than two!")

out put

Five is greater than two

4) if 5 > 2:

print("Five is greater than two!")

if 5 > 2:

print("Five is greater than two!")

output

Five is greater than two

Five is greater than two

5) x = 5

y = "John"

print(x)
print(y)

output

5 Creating Variables

John

6) x = 4

x = "Sally"

print(x)

output

Sally

7)

x = str(3)

y = int(3)

z = float(3)

print(x)

print(y)

print(z)

output

3
3.0

8) Variable Names
myvar = "John"

my_var = "John"

_my_var = "John"

myVar = "John"

MYVAR = "John"

myvar2 = "John"

print(myvar)

print(my_var)

print(_my_var)

print(myVar)

print(MYVAR)

print(myvar2)

output

John

John

John

John

John

John
9) Many Values to Multiple Variables

x, y, z = "Orange", "Banana", "Cherry"

print(x)

print(y)

print(z)

output

orange

Banana

Cherry

10) One Value to Multiple Variables

x = y = z = "Orange"

print(x)

print(y)

print(z)

output

Orange
Orange

Orange

11) Unpack a Collection


fruits = ["apple", "banana", "cherry"]

x, y, z = fruits

print(x)

print(y)

print(z)

output

apple

banna

cherry

12. input function


"""
a = 10.0
print(a)
print(type(a))
b = int(a)
print(b)
print(type(b))

int()
float()
str()
"""
a = int(input("Enter The Value of A : "))
b = int(input("Enter The Value of B : "))
c=a+b
print("Total : " + str(c))

Output

Enter The Value of A : 20


Enter The Value of B : 20
Total : 40

13. Single and Multiline Comment in Python

In Python, there are two types of comments: single-line and


multi-line.
 Single-line comments start with a hash symbol (#) and
extend to the end of the line:
 Multi-line comments start and end with three quotation
marks (""").

Source Code
# Basic Program in Python
# Basic Program in Python
# Basic Program in Python
'''
Basic Program in Python
Basic Program in Python
Basic Program in Python
Basic Program in Python
Basic Program in Python
'''
a = 10
b = 20
c=a+b
print(c)

output
30
14. String and String Functions in Python

Python has several built-in functions associated with the string


data type. These functions let us easily modify and manipulate
strings. Creating Strings is the simplest and easy to use in
Python. To create a string in Python, we simply enclose a text
in single as well as double-quotes.

 type() => The returns the type of the object.


 upper() => All the characters in a given string are uppers
case.
 lower() => All the characters in a given string are lower
case.
 capitalize() => The first character is the upper case
 The title() => The first character in every word of the string
is an upper case.
 count() => Finds the number of times a specified value in
the given string.
 find() => Finds the first occurrence of the specified value.
 replace() => Replaces a specified phrase with another
specified phrase.
 isalnum() => Checks whether all the characters in a given
string is alphanumeric or not
 isalpha() => returns True if all the characters in the string
are alphabets
 islower() => Checks if all characters in the string are
lowercase
 isupper() => Checks if all characters in the string are
uppercase
 strip() => The used to trim whitespaces from the string
object

Source Code
# String And String Function
s = "tutor Joes"
print(s)
print(type(s))
print([Link]())
print([Link]())
print([Link]())
print([Link]())
print([Link]("t"))
print([Link]("ED"))
print([Link]("o"))
print([Link]("o", 5))
print([Link]("o", '0'))
a = "joes1234"
print("Is Upper : ", [Link]())
print("Is Lower : ", [Link]())
print("Is Alpha Numeric : ", [Link]())
print("Is Alpha : ", [Link]())
s = "he\nis\ngood"
print(s)
print([Link]())
print([Link](True))
a = "Tutor Joes Computer Education"
print([Link](" "))
a = "Tutor,Joes,Computer,Education"
print([Link](","))
s=" Joes "
print(len(s))
print(len([Link]()))
print(len([Link]()))
print(len([Link]()))
s='12-03-2020'
print([Link]('-'))
To download raw file Click Here
Output

tutor Joes

TUTOR JOES
tutor joes
Tutor joes
Tutor Joes
2
False
3
7
tut0r J0es
Is Upper : False
Is Lower : True
Is Alpha Numeric : True
Is Alpha : False
he
is
good
['he', 'is', 'good']
['he\n', 'is\n', 'good']
['Tutor', 'Joes', 'Computer', 'Education']
['Tutor', 'Joes', 'Computer', 'Education']
13
4
9
8
('12', '-', '03-2020')

15. String Manipulation in Python

String manipulation is a process of manipulating the string,


such as slicing, parsing, analyzing, etc. String slicing in python
programming is all about fetching a substring from a given
string by slicing it from a start to end index.
Syntax :
s [ start : end ]
s [ start : ]
s [ : end ]
s[::]
This program is using the concept of slicing in python, which
allows you to extract a portion of a string by specifying a range
of indices.
The following operations are performed in the above code:

 print(s): This line will print the original string "sample".


 print(s[0:2]): This line uses slicing to extract a substring of
the original string "sa", starting at index 0 and ending at
index 2 (not included).
 print(s[:5]): This line uses slicing to extract a substring of
the original string "sampl", starting at index 0 and ending
at index 5 (not included).
 print(s[1:]): This line uses slicing to extract a substring of
the original string "ample", starting at index 1 and going till
the end of the string.
 print(s[-1]): This line uses slicing to extract the last
character of the string "e" by specifying the index as -1, as
in python, negative index is used to access elements from
the end of the list.
 print(s[-2:-1]): This line uses slicing to extract the second
last character of the string "l" by specifying the range as -2
to -1, as in python

Source Code
# String Manipulation
'''
S a m p l e
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
'''

s = "sample"
print(s)
print(s[0:2])
print(s[:5])
print(s[1:])
print(s[-1])
print(s[-2:-1])
print(s[:-1])
print(s[::-1])
To download raw file Click Here
Output

sample
sa
sampl
ample
e
l
sampl
elpmas

16. Arithmetic Operators in Python

Arithmetic operators are used to perform mathematical


operations like addition, subtraction, multiplication ,division and
also python have floor division,exponentiation.

 Addition ( + ) => This operator is a binary operator and is


used to add two operands.
 Subtraction ( - ) => This operator is a binary operator and
is used to subtract two operands.
 Multiplication ( * ) => This operator is a binary operator
and is used to multiply two operands.
 Division ( / ) => This is a binary operator that is used to
divide the first operand(dividend) by the second
operand(divisor) and give the quotient as result.
 Modulus ( % ) => This is a binary operator that is used to
return the remainder when the first operand(dividend) is
divided by the second operand(divisor).
 Exponentiation ( * * ) => The performs exponential (power)
calculation on operators
 Floor division ( / / ) => The division of operands where the
result is the quotient in which the digits after the decimal
point are removed.
Source Code
# Arithmetic operators
"""
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
** Exponentiation
// Floor division
"""
a = 123
b = 10
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(2**3)
To download raw file Click Here
Output
133
113
1230
12.3
12
3
8

17. Assignment Operators in Python

Assignment operators are used to assigning value to a variable.


The left side operand of the assignment operator is a variable
and right side operand of the assignment operator is a value.
This operator is used to assign the value on the right to the
variable on the left

Compound Operator Sample Expression Expanded Form

+= a+=2 a=a+2

-= a-=6 a=a-6

*= a*=7 a=a*7

/= a/=4 a=a/4

%= a%=9 a=a%9

**= a**=3 a=a**3


//= a//=2 a=a//2

This program is using the assignment operators along with the


basic arithmetic operations in python

 a = 125: This line assigns the value 125 to the variable a.


 print(a): This line prints the value of a which is 125.
 a += 5: This line uses the shorthand assignment operator
+= to add 5 to the current value of a and assigns the result
back to a. The value of a becomes 130.
 print(a): This line prints the updated value of a which is
130.
 a -= 10: This line uses the shorthand assignment operator
-= to subtract 10 from the current value of a and assigns
the result back to a. The value of a becomes 120.
 print(a): This line prints the updated value of a which is
120.
 a *= 10: This line uses the shorthand assignment operator
*= to multiply the current value of a by 10 and assigns the
result back to a. The value of a becomes 1200.
 print(a): This line prints the updated value of a which is
1200.
 a /= 10: This line uses the shorthand assignment
operator /= to divide the current value of a by 10 and
assigns the result back to a. The value of a becomes 120.
 print(a): This line prints the updated value of a which is
120.
 a %= 10: This line uses the shorthand assignment
operator %= to find the remainder when dividing the
current value of a by 10 and assigns the result back to a.
The value of a becomes 0.0.
 print(a): This line prints the updated value of a which is
0.0.
 a **=10: This line uses the shorthand assignment operator
**= to raise the current value of a to the power of 10 and
assigns the result back to a. The value of a becomes 0.0.
 print(a): This line prints the updated value of a which is
0.0.
 a //= 10: This line uses the shorthand assignment operator
//= to divide the current value of a by 10 and assigns the
result rounded down to the nearest integer back to a. The
value of a becomes 0.0.
 print(a): This line prints the updated value of a which is
0.0.

Source Code
# Assignment Operators

"""
= Assignment
+= Addition
-= Subtraction
*= Multiplication
/= Division
%= Modulus
**= Exponentiation
//= Floor division
"""
a = 125
print(a)
a += 5 # a=a+5
print(a)
a -= 10 # a=a-10
print(a)
a *= 10 # a=a*10
print(a)
a /= 10
print(a)
a %= 10
print(a)
a **=10
print(a)
a //= 10
print(a)
To download raw file Click Here
Output
125
130
120
1200
120.0
0.0
0.0
0.0

18. Logical Operators in Python

Logical operators are used to combine multiple conditions in a


single expression in Python. The three logical operators in
Python are and, or, and not.

 and: This operator returns True if both the conditions on


either side of the operator are True, otherwise it returns
False.
 or: This operator returns True if either of the conditions on
either side of the operator is True, otherwise it returns
False.
 not: This operator inverts the truth value of a single
condition. If a condition is True, the not operator will make
it False and vice versa.

This program is using logical operators in Python to check if the


value of a variable a falls within a certain range.

 a = 25: This line assigns the value 25 to the variable a.


 print(a >= 10 and a <= 20): This line uses the logical
operator and to check if the value of a is greater than or
equal to 10 AND less than or equal to 20. Since 25 is not
in the range 10 to 20, the output will be False.
 print(a >= 10 or a <= 20): This line uses the logical
operator or to check if the value of a is greater than or
equal to 10 OR less than or equal to 20. Since 25 is
greater than 10 the output will be true
 print(not(a >= 10 and a <= 20)): This line uses the logical
operator not to check if the value of a is not in the range of
10 to 20. The output will be True because 25 is not in the
range 10 to 20.

Source Code
# Logical Operators in Python
"""
and
or
not

"""
a = 25
print(a >= 10 and a <= 20)
print(a >= 10 or a <= 20)
print(not(a >= 10 and a <= 20))
To download raw file Click Here
Output

False
True
True

19Nested If Statement in Python

Nested If Statement means to place one If inside another If Statement.


Nested ifs are very common in programming. when you nest ifs, the
main thing to remember is that an else statement always refers to the
nearest if statement that is within the same block as the else and that is
not already associated with an else.
Syntax:
if ( Expression 1 ) :
// Executes when the Expression 1 is true
if ( Expression 2 ) :
// Executes when the Expression 2 is true
This program is a Python script that prompts the user to enter three
marks, then calculates the total and average of those marks, and then
uses if-else statements to determine the result and grade based on the
marks.

 It starts by using the input() function to ask the user to enter three
marks, m1, m2, and m3, which are then stored in variables. The
program then calculates the total of the marks by adding the three
marks and stores it in the variable 'total' and also calculates the
average of the marks by dividing total with 3.0 and stores it in the
variable 'average'
 Then, the program uses an if-elif block to check the value of the
three marks against a series of conditions.
 If all three marks are greater than or equal to 35, the program will
print "Result : Pass" and then again check the average of the
marks and calculate the grade If average is greater than or equal
to 90 and less than or equal to 100, the program will print "Grade :
A" If average is greater than or equal to 80 and less than or equal
to 89, the program will print "Grade : B" If average is greater than
or equal to 70 and less than or equal to 79, the program will
print "Grade : C" If none of the above conditions are met, the
program will print "Grade : D"
 If any of the three marks is less than 35, the program will
print "Result : Fail" and "Grade : No Grade"

So the program is checking the student's three marks, calculating the


total and average of the marks, and then determining the result and
grade based on the marks and average.

Source Code
# Nested If Statement in Python
"""
3 Marks as Input
Total
Average
Result
If Pass Grade
90-100 A
80-89 B
70-79 C
Else D
"""
m1 = int(input("Enter Mark-1 : "))
m2 = int(input("Enter Mark-2 : "))
m3 = int(input("Enter Mark-3 : "))
total = m1 + m2 + m3
average = total / 3.0
print("Total : ", total)
print("Average : ", average)
if m1 >= 35 and m2 >= 35 and m3 >= 35:
print("Result : Pass")
if average >= 90 and average <= 100:
print("Grade : A")
elif average >= 80 and average <= 89:
print("Grade : B")
elif average >= 70 and average <= 79:
print("Grade : C")
else:
print("Grade : D")
else:
print("Result : Fail")
print("Grade : No Grade")
To download raw file Click Here

Output
Enter Mark-1 : 90
Enter Mark-2 : 90
Enter Mark-3 : 90
Total : 270
Average : 90.0
Result : Pass
Grade : A

20 .While Loop in Python

The while loop is repeats a statement or block while its controlling


expression is [Link] condition can be any Boolean expression. The
body of the loop will be executed as long as the conditional
expression is true. When condition becomes false, control passes to
the next line of code immediately following the loop.

 If the condition to true, the code inside the while loop is


executed.
 The condition is evaluated again.
 This process continues until the condition is false.
 When the condition to false, the loop stops.

Syntax:
while ( Condition ) :
// body of statement
The first while loop in the code you provided will continue to execute
and print the numbers from 1 to 10. It initializes the variable i to 1 and
then uses the while loop to check if i is less than or equal to 10. If the
condition is true, it prints the current value of i and then increments
the value of i by 1. This process will repeat until i is no longer less
than or equal to 10, at which point the while loop will exit.
The second while loop in the code is designed to print the even
numbers from 2 to 20. It initializes the variable i to 2, and the variable
n to 20. Then, it uses the while loop to check if i is less than or equal
to 20. If the condition is true, it prints the current value of i and then
increments the value of i by 2. This process will repeat until i is no
longer less than or equal to 20, at which point the while loop will exit.

Source Code
# While Loop
"""
[Link] Loop
[Link] Loop
"""
i=1
while i <= 10:
print(i)
i += 1
print("--------------------")
print("Even No : ")
n = 20
i=2
while i <= 20:
print(i)
i += 2
To download raw file Click Here
Output
1
2
3
4
5
6
7
8
9
10
--------------------
Even No :
2
4
6
8
10
12
14
16
18
20Continue using While Loop in Python
The continue statement instructs a loop to continue to the next
iteration. The continue statement is used to skip the remaining
statements of the current loop and go to the next iteration.
This program is a Python script that uses a while loop to iterate
over the numbers from 1 to 20, and prints only the odd
numbers.

 It starts by initializing a variable i to 1, which is used as the


counter for the while loop. The while loop then runs as
long as the value of i is less than or equal to 20.
 Inside the while loop, there is an if statement that checks
whether the remainder of i divided by 2 is equal to 0 using
the modulo operator %. If the remainder is 0, it means that
the number is even and the program will continue to the
next iteration using the continue statement.
 The continue statement causes the program to skip the
rest of the code in the current iteration of the loop, and
move on to the next iteration.
 If the remainder is not 0, it means that the number is odd,
and the program will print the current value of i and then
increments the value of i by 1.
 This process will repeat until i is no longer less than or
equal to 20, at which point the while loop will exit and the
program will end.
 So the program is using a while loop to iterate over the
numbers from 1 to 20, and using an if statement to check
whether each number is even or odd. The program is only
printing the odd numbers and skipping the even numbers
using continue statement.

Source Code
Print Odd Numbers using While Loop in Python
# Continue Statement
i=1
while i <= 20:
if i % 2 == 0:
i=i+1
continue;
print(i)
i += 1
To download raw file Click Here
Output
1
3
5
7
9
11
13
15
17
19
21Break using While Loop in Python

The break statements are your way of asking the loop to stop
and execute the next statement. When a break statement is
encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement
following the loop
This program is a Python script that uses a while loop to iterate
over the numbers from 1 to 20, but it exits the loop when the
number 7 is encountered.

 It starts by initializing a variable i to 1, which is used as the


counter for the while loop. The while loop then runs as
long as the value of i is less than or equal to 20.
 Inside the while loop, there is an if statement that checks
whether the value of i is equal to 7 using the comparison
operator ==. If the value is 7, it means that the number is 7
and the program will exit the loop using
the break statement.
 The break statement is used to exit a loop prematurely.
When the break statement is encountered inside a loop,
the loop is immediately terminated and the program
continues with the next statement following the loop.
 If the value of i is not equal to 7, it means that the number
is not 7, and the program will print the current value
of i and then increments the value of i by 1.
 This process will repeat until i is no longer less than or
equal to 20, or until i is equal to 7 at which point the while
loop will exit using the break statement and the program
will end.
 So the program is using a while loop to iterate over the
numbers from 1 to 20, and using an if statement
with break statement to check whether the number is 7 or
not. When the number is 7, the while loop exits and the
program ends.

Source Code
# Break Statement
i=1
while i <= 20:
if i==7:
break
print(i)
i += 1
To download raw file Click Here
Output
1
2
3
4
5
6
22Range in
Python….9/11/24

The program is a Python script that demonstrates the use


of the built-in range() function.

 The range() function creates an iterator that generates


a sequence of numbers within a given range.
 In the first line, range(5) creates an iterator that
generates a sequence of numbers from 0 (inclusive) to
5 (exclusive). The list() function is used to convert the
iterator to a list, so the output is [0, 1, 2, 3, 4].
 In the second line, range(2, 5) creates an iterator that
generates a sequence of numbers from 2 (inclusive) to
5 (exclusive). The output is [2, 3, 4].
 In the third line, range(0, 21, 2) creates an iterator that
generates a sequence of numbers from 0 (inclusive) to
21 (exclusive) with a step of 2. The output is [0, 2, 4, 6,
8, 10, 12, 14, 16, 18, 20].
 In the fourth line, range(1, 20, 2) creates an iterator
that generates a sequence of numbers from 1
(inclusive) to 20 (exclusive) with a step of 2. The
output is [1, 3, 5, 7, 9, 11, 13, 15, 17, 19].
 So the program is using the range() function
and list() function to create a range of numbers with
different start, stop and step values.
The range() function creates an iterator and
the list() function is used to convert the iterator to a
list.

Source Code
# Range in Python
"""
1-5 =>1,2,3,4,5
0-5 =>2,4 +2
range(5) =>0,1,2,3,4
range(2,5) =>
"""
print(list(range(5)))
print(list(range(2, 5))) # n-1
print(list(range(0, 21, 2)))
print(list(range(1, 20, 2)))
Output

[0, 1, 2, 3, 4]
[2, 3, 4]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

23. For Loop in Python


The for loop is used to repeat a specific block of code which
you want to repeat a fixed number of times. The for loop is a
control flow statement that is used to repeatedly execute a
group of statements as long as the condition is satisfied.
Syntax:
for variable_name in sequence :
body of loop
This program is a Python script that demonstrates the use of
the for loop and the built-in range() function.

 The first for loop uses the range() function to create an


iterator that generates a sequence of numbers from 0
(inclusive) to 21 (exclusive) with a step of 2. The for loop
iterates over the numbers in the sequence and prints each
one to the screen.
 The second for loop uses the range() function to create an
iterator that generates a sequence of numbers from 0 to 4.
The for loop iterates five times, each time prompting the
user to input a number using the built-in input() function.
 The values entered by the user are stored in variables a
and b, and then the program print the sum of a and b as
output. So the program is using the for loop and
the range() function to iterate over a sequence of numbers
and for each iteration, it prompts the user to enter two
numbers and print the sum of those numbers.
 The first for loop iterates over a sequence of even
numbers and the second for loop iterates 5 times and
each iteration it prompts user to enter two numbers.
Source Code
# For Loop in Python
for i in range(0, 21, 2):
print(i)

for i in range(5):
a=int(input("Enter a No : "))
b=int(input("Enter a No : "))
print(a+b)
To download raw file Click Here
Output

0
2
4
6
8
10
12
14
16
18
20
Enter a No : 3
Enter a No : 2
5
Enter a No : 2
Enter a No : 2
4
Enter a No : 3
Enter a No : 3
6
Enter a No : 3
Enter a No : 3
6
Enter a No : 3
Enter a No : 3
6

24. Nested For Loop in Python

The nested loop refers to a loop within a loop, an inner loop


within the body of an outer one. Nested loops are useful when
for each pass through the outer loop, you need to repeat some
action on the elements in the outer loop. The nested loop is a
one iteration of the outer loop is first executed, after which the
inner loop is executed. The execution of the inner loop
continues till the condition described in the inner loop is
satisfied.
Syntax:
// outer for loop
for variable_name in sequence :
// inner for loop
for variable_name in sequence :
// body of loop
This program is a Python script that demonstrates the use of
nested for loops and the built-in range() function.
The program contains three main parts, each one using a
different approach to accomplish different tasks.

 In the first part of the program, there is a nested for loop


where the outer loop uses the range() function to create
an iterator that generates a sequence of numbers from 0
to 5. The inner for loop uses the same function to create
an iterator that generates a sequence of numbers from 0
to the current value of the outer loop variable. The inner
loop prints an asterisk character (*) for each value of the
inner loop variable. The inner print statement uses
the end parameter to specify that no newline character
should be added after the asterisk. As a result, the
program prints a right-angled triangle pattern of asterisks.
 In the second part of the program, there is another nested
for loop where the outer loop uses the range() function to
create an iterator that generates a sequence of numbers
from 5 to 1 with a step of -1. The inner for loop uses the
same function to create an iterator that generates a
sequence of numbers from 0 to the current value of the
outer loop variable. As in the first part, the inner loop prints
an asterisk character (*) for each value of the inner loop
variable. The inner print statement uses
the end parameter to specify that no newline character
should be added after the asterisk. As a result, the
program prints another right-angled triangle pattern of
asterisks, but this time in reverse order.
 In the third part of the program, there is another nested for
loop where the outer loop uses the range() function to
create an iterator that generates a sequence of numbers
from 65 to 69. The inner for loop uses the same function
to create an iterator that generates a sequence of
numbers from 65 to 69. The inner loop prints a character
represented by the ASCII code of the current value of the
inner loop variable using the built-in chr() function. The
inner print statement uses the end parameter to specify
that no newline character should be added after the
character. As a result, the program prints a matrix
of 5x5 containing the characters A, B, C, D and E.

Source Code
# Nested For Loop
"""
*
**
***
****
*****
*****
****
***
**
*

ABCDE
ABCDE
ABCDE
ABCDE
ABCDE

A-Z => 65-90


a-z=> 97-122

"""

for i in range(6):
for j in range(i):
print("*",end="")
print("")
print("----------------")

for i in range(5,0,-1):
for j in range(i):
print("*",end="")
print("")
print("----------------")

for i in range(65,70,1):
for j in range(65,70,1):
print(chr(j),end="")
print("")
To download raw file Click Here
Output

*
**
***
****
*****
----------------
*****
****
***
**
*
----------------
ABCDE
ABCDE
ABCDE
ABCDE
ABCDE

[Link] Else and For Else in Python

Source Code
Else block will be executed only if the loop isn't terminated
by a break statement. The else clause executes after the
loop completes normally. This means that the loop did not
encounter a break statement. They are really useful once
you understand where to use them.
This program demonstrates the use of the else block in
both while loops and for loops in Python.
The first block of code is a while loop that starts with the
variable "i" equal to 1 and continues to run until "i" is no
longer less than or equal to 5. The loop prints the value
of "i" on each iteration, and then increments "i" by 1. After
the while loop completes its iterations, the else block is
executed and prints the message "Loop Completed".
The second block of code is a for loop that uses
the range() function to iterate over the numbers from 1 to
20. On each iteration, the value of the iterator variable "i" is
printed. After the for loop completes its iterations, the else
block is executed and prints the message "For Loop
Completed".
Both While and for loop checks for the condition inside the
loop and runs the loop until the condition is true. In the
given code, we don't have any condition to break the loop
that's why the both loops are running completely and
printing "Loop Completed" or "For Loop
Completed" respectively.
Syntax:
while condition :
while block statement
else :
else block statement
Syntax:
for variable_name in sequence :
for block statement
else :
else block statement

# While Else & For Else

i=1
while i<=5:
#if(i==4):
#break
print(i)
i+=1
else:
print("Loop Completed")

for i in range(1,21):
#if i==5:
#break
print(i)
else:
print("For Loop Completed")
To download raw file Click Here
Output

1
2
3
4
5
Loop Completed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
For Loop Completed

 Previous

26. List in Python


Lists are used to store multiple items in a single [Link]
separate two items, you use a comma ( , ) . List uses the
square brackets [ ]. Lists are one of 4 built-in data types in
Python used to store collections of data, the other 3 are Tuple,
Set, and Dictionary, all with different qualities and usage.

 Sequence Type
 Element of the list can access by index
 They are mutable

This program demonstrates various built-in functions and


methods that can be used with lists in Python.

 The first block of code shows how to create a list and


access its elements using indexing. It also shows how to
change the value of an element in a list using indexing.
 The second block of code shows how to create a list with
different data types and how to access the elements of the
list and their types.
 The third block of code demonstrates how to use
the clear() method to remove all elements from a list,
the copy() method to create a copy of a list,
the count() method to count the number of occurrences of
an element in a list, the index() method to find the index of
an element in a list, the len() function to find the length of
a list, the max() and min() functions to find the maximum
and minimum element in a list, the pop() method to
remove an element from a list using an index, and
the remove() method to remove an element from a list
using its value.
 The fourth block of code shows how to use
the append() method to add elements to a list,
the extend() method to add elements from another list,
and the insert() method to insert an element at a specific
index in a list.
 The fifth block of code demonstrates how to use
the range() function to create a list of numbers,
the list() function to convert a string to a list, and
the sort() method to sort the elements of a list in
ascending or descending order. It also shows how to use
the key parameter to sort the elements based on a
specific key and the reverse parameter to sort the
elements in descending order.

Source Code
# List in Python
"""
Sequence Type
Mutable
a[5]
a={1,2,3,4,5}
a[0]
"""
a = [1, 2, 3, 4, 5]
print(a)
print(type(a))
a[0] = 100
print(a)
print("Slicing")
print(a[1])
print(a[-1])
print(a[0:3])
print(a[2:])
print(a[:3])
print("-----------------------------")
a = [1, True, 'Ram', 2.5, [1, 2, 3, 4]]
print(a)
print(type(a))
print(a[0], " type is ", type(a[0]))
print(a[1], " type is ", type(a[1]))
print(a[2], " type is ", type(a[2]))
print(a[3], " type is ", type(a[3]))
print(a[4], " type is ", type(a[4]))
print(a[4][1])
print("-----------------------------")
a = [10, 25, 35, 45]
print(a)
[Link]()
print(a)
a = [10, 25, 35, 45]
b = [Link]()
print(b)
a = [10, 25, 35, 45, 25, 4, 25]
print([Link](25))
print([Link](25))
print(len(a))
print(max(a))
print(min(a))
print(a)
[Link](0) # remove Element using index
print(a)
a = [10, 25, 35, 45, 25, 4, 25]
[Link](25) # Values
print(a)
print("-----------------------------")
names = ["Ram"]
print(names)
[Link]("Sam")
[Link]("Ravi")
[Link]("Kumar")
print(names)
name2 = ["Sara", "Anitha"]
[Link](name2)
print(names)
[Link](0,"Suriya")
print(names)
print("-----------------------------")
print(list(range(5)))
print(list("Tutorjoes"))
a=[10,50,100,25,85]
print(a)
[Link]()
print(a)
[Link](reverse=True)
print(a)
a=["Orange","Apple","Zebra"]
[Link]()
print(a)
[Link](reverse=True)
print(a)
a=["Orange","Apple","Zebra"]
[Link](key=len)
print(a)

To download raw file Click Here


Output
[1, 2, 3, 4, 5]

[100, 2, 3, 4, 5]
Slicing
2
5
[100, 2, 3]
[3, 4, 5]
[100, 2, 3]
-----------------------------
[1, True, 'Ram', 2.5, [1, 2, 3, 4]]

1 type is
True type is
Ram type is
2.5 type is
[1, 2, 3, 4] type is
2
-----------------------------
[10, 25, 35, 45]
[]
[10, 25, 35, 45]
3
1
7
45
4
[10, 25, 35, 45, 25, 4, 25]
[25, 35, 45, 25, 4, 25]
[10, 35, 45, 25, 4, 25]
-----------------------------
['Ram']
['Ram', 'Sam', 'Ravi', 'Kumar']
['Ram', 'Sam', 'Ravi', 'Kumar', 'Sara', 'Anitha']
['Suriya', 'Ram', 'Sam', 'Ravi', 'Kumar', 'Sara', 'Anitha']
-----------------------------
[0, 1, 2, 3, 4]
['T', 'u', 't', 'o', 'r', 'j', 'o', 'e', 's']
[10, 50, 100, 25, 85]
[10, 25, 50, 85, 100]
[100, 85, 50, 25, 10]
['Apple', 'Orange', 'Zebra']
['Zebra', 'Orange', 'Apple']
['Apple', 'Zebra', 'Orange']
27, Tuple in Python

Tuple are used to store multiple items in a single [Link]


separate two items, you use a comma ( , ) . A tuple is like a list
except that it uses parentheses ( ) . Once you define a tuple,
you can access an individual element by its index. A tuple is a
collection of objects which ordered and immutable, you cannot
change its elements. Tuples are sequences, just like lists.
This program demonstrates the usage of tuples in Python. A
tuple is a collection of ordered and immutable elements, that
are enclosed within parentheses. The elements in a tuple can
be of different data types.

 The first line creates a tuple and assigns it to the


variable 'a'. Then, the program prints the tuple and its
type, which is <class 'tuple'>.
 The next lines show how to access the elements of the
tuple using indexing and slicing, just like in lists.
 The next lines convert the tuple to a list and append an
element to it, then converts the list back to a tuple.
 The for loop iterates through the elements of the tuple and
the if-else statement checks if a certain element is present
in the tuple.
 The len() function is also used to get the length of the
tuple.
 The next lines show how to concatenate and repeat tuples
using the + and * operators respectively.
 The program also demonstrates how to use
the count() and index() methods, which are also available
for tuples as well as lists. It also shows how to use
the min() and max() functions on tuple.

Source Code
# Tuple in Python
# Immutable
# Surrounded by Round Brackets (1,1,5)

a = (1, 2.5, True, "Ram")


print(a)
print(type(a))
print(a[1])
print(a[-1])
print(a[0:2])
b = list(a)
print(b)
[Link]("Raja")
print(b)
print(type(b))
a = tuple(b)
print(a)
print(type(a))

for i in a:
print(i)

if "Raj" in a:
print("Raja is Found")
else:
print("Not Found")
print(len(a))

a = (1,)
print(type(a))
del a
a = (1, 2, 7, 4)
b = (5, 6, 7, 8)
c=a+b
print(c)
print([Link](7))

a = (1, 2, 7, 4)
b = (5, 6, 7, 8)
c = (a, b)
print(c)
print(c[0])
print(c[1])
print(c[0][1])
x = ('Joes',) * 10
print(x)
a = (1, 2, 7, 4)
b = (5, 6, 7, 8)
print(min(a))
print(max(a))

[Link] in Python

Set are used to store multiple items in a single


variable. To separate two items, you use a
comma ( , ) . A set is like a list except that it uses
parentheses { } . Set is one of 4 built-in data types
in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with
different qualities and usage.

 Set are unordered


 A set doesn’t allow duplicate elements
 Set cannot be changed
The program creates two sets: "names" and "a".

 The "names" set is initially created with three


elements 'Ram', 'Sam', and 'Ravi'. The set is
printed and its type is also printed to show that
it is a set.
 The for loop iterates through each element in
the set and prints it. Then, a new
element 'Sara' is added to the set using
the "add" method.
 Another set "a" is created and its elements are
added to the names set using the "update"
method.
 The "remove" and "discard" methods are used
to remove elements from the set.
The "pop" method is used to remove an
arbitrary element from the set.
 The "clear" method is used to remove all
elements from the set and "del" is used to
delete the entire set.
 A new set "names" is created with duplicate
elements, but sets only store unique elements,
so the duplicate elements are removed.
Then, the program demonstrates set operations
such as union, intersection, symmetric difference
and set comparison methods such as isdisjoint,
issubset, and issuperset.

 The "union" method is used to combine the


elements of two sets and the "update" method
updates the set with the elements from
another set.
 The "intersection" method returns the common
elements in both sets and
the "intersection_update" method updates the
set with the common elements.
 The "symmetric_difference" method returns
the elements that are unique to each set and
the "symmetric_difference_update" method
updates the set with the unique elements.
 The "isdisjoint" method returns True if two sets
have no common elements and False
otherwise. The "issubset" method returns True
if a set is a subset of another set and False
otherwise.
 The "issuperset" method returns True if a set
is a superset of another set and False
otherwise.

Source Code
names={'Ram','Sam','Ravi'}
print(names)
print(type(names))
# Access Values Using For loop
for name in names:
print(name)
# Adding New Element
[Link]('Sara')
print(names)
# Update Another Set of Data
a={'Kumar','Sundar','Suresh'}
[Link](a)
print(names)
[Link]('Sara')
print(names)
[Link]('Suresh')
print(names)
[Link]()
print(names)
[Link]()
print(names)
del names
names={'Ram','Ram','Sam','Ravi','Kumar','Sundar','
Suresh'}
print(names)
a = {1, 2, 3, 4}
b = {'a', 'b', 'c', 'd'}
c=[Link](b)
print(c)
[Link](b)
print(a)
a = {1, 2, 3, 4, 5}
b = {5, 6, 7, 8, 9}
c=[Link](b)
print(c)
a.intersection_update(b)
print(a)
c=a.symmetric_difference(b)
print(c)
a.symmetric_difference_update(b)
print(a)
a = {5,6,7}
b = {5, 6, 7}
c=[Link](b)
print(c)
c=[Link](b)
print(c)
c=[Link](b)
print(c)
To download raw file Click Here

Output
{'Ravi', 'Ram', 'Sam'}
<class 'set'>
Ravi
Ram
Sam
{'Ravi', 'Sara', 'Ram', 'Sam'}
{'Ravi', 'Sara', 'Suresh', 'Sundar', 'Sam', 'Kumar',
'Ram'}
{'Ravi', 'Suresh', 'Sundar', 'Sam', 'Kumar', 'Ram'}
{'Ravi', 'Sundar', 'Sam', 'Kumar', 'Ram'}
{'Sundar', 'Sam', 'Kumar', 'Ram'}
set()
{'Ravi', 'Sundar', 'Ram', 'Sam', 'Kumar', 'Suresh'}
{'d', 1, 2, 3, 4, 'b', 'c', 'a'}
{'d', 1, 2, 3, 4, 'b', 'c', 'a'}
{5}
{5}
{6, 7, 8, 9}
{6, 7, 8, 9}
False
True
True

29. Dictionary in Python


A Python dictionary is a collection of key-value
pairs where each key is associated with a value.
dictionary are used to store multiple items in a
single variable. To separate two items, you use a
comma ( , ) . A dictionary is like a list except that it
uses parentheses { key : value } .

 They are Immutable


 A set doesn’t allow duplicate elements
 The key cannot be changed
This program demonstrates the usage of
dictionaries in Python. A dictionary is a collection
of key-value pairs, where each key is unique.
Initially, a dictionary 'user' is created with key-value
pairs of user's name, age, and marital status.

 The print statements show the dictionary, its


type and the values corresponding to the keys
"name" and "age".
 The keys() method returns the keys of the
dictionary, and the values() method returns the
values of the dictionary.
 The items() method returns a view of the
dictionary's key-value pairs.
 For loops are used to iterate over the keys,
values and items of the dictionary and print
them.
 The in keyword is used to check if
the "gender" key is present in the dictionary.
 The dictionary values can be updated using
the update() method and the [] operator.
 The pop() method is used to remove the key-
value pair with the given key, and
the clear() method is used to remove all key-
value pairs from the dictionary.
Another dictionary 'users' is created that contains
two dictionaries - 'user1' and 'user2' - as its values.

 The for loop is used to iterate over the keys of


the dictionary, 'users', and print the values of
the key "name" of each
dictionary 'user1' and 'user2'.

Source Code
user = {
"name": "Ram",
"age": 25,
"isMarried": True
}
print(user)
print(type(user))
print(user["name"])
print([Link]('age'))
print([Link]())
print([Link]())
print([Link]())
for x in user:
print(x," ",user[x])
for x in [Link]():
print(x)
for x in [Link]():
print(x)
for x,y in [Link]():
print(x,y)
if "gender" in user:
print("Present")
# Changing Values
[Link]({"gender":"male"})
print(user)
user["age"]=35
print(user)
[Link]("age")
print(user)
[Link]()
print(user)
users={
"user1": {
"name": "Ram",
"age": 25,
"isMarried": True
},
"user2": {
"name": "SAm",
"age": 35,
"isMarried": False
}
}
print(users)
for user in users:
print(user["name"])
To download raw file Click Here

Output
{'name': 'Ram', 'age': 25, 'isMarried': True}
<class 'dict'>
Ram
25
dict_keys(['name', 'age', 'isMarried'])
dict_values(['Ram', 25, True])
dict_items([('name', 'Ram'), ('age', 25), ('isMarried',
True)])
name Ram
age 25
isMarried True
Ram
25
True
name
age
isMarried
name Ram
age 25
isMarried True
{'name': 'Ram', 'age': 25, 'isMarried': True, 'gender':
'male'}
{'name': 'Ram', 'age': 35, 'isMarried': True, 'gender':
'male'}
{'name': 'Ram', 'isMarried': True, 'gender': 'male'}
{}
{'user1': {'name': 'Ram', 'age': 25, 'isMarried':
True}, 'user2': {'name': 'SAm', 'age': 35, 'isM
[Link] Operators in Python

Identity operators are used to compare the


objects, not if they are equal, but if they are
actually the same object, with the same memory
location. th operators test if the two operands
share an identity. We have two identity
operators is and is not. The is operators test If two
operands have the same identity, it returns True.
Otherwise, it returns False.
This program is about comparing the equality of
objects in Python.

 Two lists, a and b, are created with the same


values [1, 2].
 A third list c is assigned the reference of a.
 The id() function is used to print the memory
addresses of a, c, and b.
 The is operator is used to check if two objects
are pointing to the same memory location.
 The == operator is used to check if two objects
have the same values.
 The is not operator is used to check if two
objects are not pointing to the same memory
location.
 The != operator is used to check if two objects
do not have the same values.
Source Code
"""
is
is not
"""
a = [1, 2]
b = [1, 2]
c=a
print(id(a))
print(id(c))
print(id(b))
print(a is c)
print(a is b)
print(a==b)
print(a is not c)
print(a is not b)
print(a!=b)
To download raw file Click Here

Output
2541201282048
2541201282048
2541201303616
True
False
True
False
True
False

31Membership operators in Python

Membership operators are used to test if a sequence is


presented in an object. The use membership operators to
check whether a value or variable exists in a sequence (string,
list, tuples, sets, dictionary) or not. They are two membership
python operators in and not in. The in Operator is checks if a
value is a member of a sequence. The not in Operator is
checks if a value is not a member of a sequence.
The program checks if the value 22 is present in the list a and if
it's not present in the list a. The in operator returns True if the
element is present in the list and False if it's not. The not
in operator returns True if the element is not present in the list
and False if it's present.

 In this case, the output of print(22 in a) is False, as 22 is


not present in the list a.
 The output of print(22 not in a) is True, as 22 is not
present in the list a.
Source Code
a=[10,25,45,88]
print(22 in a)
print(22 not in a)
To download raw file Click Here

Output
False
True

32Functions in Python

Python allows us to divide a large program into the basic


building blocks known as a function. function is a group of
related statements that performs a specific task. A function is a
reusable block of code which only runs when it is called. You
can pass data, known as parameters, into a function. A function
can return data as a result.
Two Types of Function :
1. User-defined Function: We can create our own function
based on our requirements.
2. Standard Library Function: These are built-in function in
python that are available to use.
Syntax:
def function_name ( Parameter list ) :
// function block
Return Syntax:
return expression

Function Types :

 No Return Type With Argument Function


 No Return Type Without Argument Function
 Return Type Without Argument Function
 Return Type With Argument Function

Source Code
def welcome():
print("Welcome To Tutor Joes")

welcome()

# No Return Type Without Argument Function in Python


"""
def add():
a=int(input("Enter The Value of A : "))
b=int(input("Enter The Value of B : "))
c=a+b
print("Total ",c)

add()
"""

# No Return Type With Argument Function in Python


"""
def sub(a, b):
c=a-b
print("Difference : ", c)

sub(25, 2)
"""

# Return Type Without Argument Function in Python


"""
def mul():
a = int(input("Enter The Value of A : "))
b = int(input("Enter The Value of B : "))
c=a*b
return c

x=mul()
print("Mul ",x)
"""

# Return Type With Argument Function in Python


"""
def div(a, b):
c=a/b
return c

x = div(25, 2)
print("Division ", x)
"""

# Arbitrary Arguments Function in Python (*)


"""
def class_10(*students):
print(students)
for user in students:
print(user)

class_10("Ram", "Sam", "Raja", "Sara")


"""

# Keyword Arguments Function in Python

"""
def message(name, age):
print(name, " age is ", age)
message(age=25, name="Ram")
"""

# Arbitrary Keyword Arguments in Python(**)


"""
def bioData(**data):
print(data)

bioData(name="Ram Kumar", age=25, gender="Male")


"""

# Default Parameter Function in Python


"""
def user(name, city="Salem"):
print(name, " is from ", city)

user("Ram", "Namakkal")
user("Sam")
"""

# Passing a List as an Argument in Function Python


"""
def total(marks):
return sum(marks)
print("Total : ",total([55, 75, 80, 95, 47]))
"""

# recursive function
# 1 * 2 * 3 * 4 * 5=120
"""
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x - 1))

print("Factorial : ", factorial(5))


"""
"""
factorial(5)
5*factorial(4)
5*4*factorial(3)
5*4*3*factorial(2)
5*4*3*2*factorial(1)
5*4*3*2*1
120
"""

c = lambda a: a + 50
print(c(5))

c = lambda a, b: a * b
print(c(10, 25))

To download raw file Click Here

Output
Welcome To Tutor Joes

# No Return Type Without Argument Function in Python


Enter The Value of A : 34
Enter The Value of B : 78
Total 112

# No Return Type With Argument Function in Python


Difference : 23

# Return Type Without Argument Function in Python


Enter The Value of A : 2
Enter The Value of B : 45
Mul 90

# Return Type With Argument Function in Python


Division 12.5

# Arbitrary Arguments Function in Python (*)


('Ram', 'Sam', 'Raja', 'Sara')
Ram
Sam
Raja
Sara

# Keyword Arguments Function in Python


Ram age is 25

# Arbitrary Keyword Arguments in Python(**)


{'name': 'Ram Kumar', 'age': 25, 'gender': 'Male'}

# Default Parameter Function in Python


Ram is from Namakkal
Sam is from Salem

# Passing a List as an Argument in Function Python


Total : 352

# recursive function
Factorial : 120

Excersise
1)Write a Python script to display the various Date Time
formats -
a) Current date and time
b) Current year
c) Month of year
d) Week number of the year
e) Weekday of the week
f) Day of year
g) Day of the month
h) Day of week
# Import the time module
import time
# Import the datetime module
import datetime

# Print the current date and time using datetime


print("Current date and time: " , [Link]())

# Print the current year extracted from today's date


print("Current year: ", [Link]().strftime("%Y"))

# Print the month of the year extracted from today's date


print("Month of year: ", [Link]().strftime("%B"))

# Print the week number of the year extracted from today's date
print("Week number of the year: ",
[Link]().strftime("%W"))

# Print the weekday of the week extracted from today's date


print("Weekday of the week: ",
[Link]().strftime("%w"))

# Print the day of the year extracted from today's date


print("Day of year: ", [Link]().strftime("%j"))

# Print the day of the month extracted from today's date


print("Day of the month : ", [Link]().strftime("%d"))

# Print the day of the week extracted from today's date


print("Day of week: ", [Link]().strftime("%A"))
[Link] a Python program to convert a string to datetime.
Sample String : Jul 1 2014 2:43PM
Expected Output : 2014-07-01 14:43:00

# Import the datetime class from the datetime module


from datetime import datetime

# Parse the given date string 'Jul 1 2014 2:43PM' into a


datetime object
# using the specified format '%b %d %Y %I:%M%p'
date_object = [Link]('Jul 1 2014 2:43PM', '%b %d
%Y %I:%M%p')

# Print the parsed datetime object


print(date_object)

[Link] a Python program to print a 3-column calendar for an


entire year.
# Import the calendar module
import calendar
# Create a TextCalendar object starting from Sunday as the
first day of the week
cal = [Link]([Link])
# Specify the formatting parameters for the year calendar
# year: 2022
# column width: 2
# lines per week: 1
# number of spaces between month columns: 1
# 3: number of months per column
# Generate the formatted year calendar for 2022 using the
specified parameters
print([Link](2022, 2, 1, 1, 3))

3. Reverse Full Name Write a Python program that accepts


the user's first and last name and prints them in reverse order
with a space between them.
# Prompt the user to input their first name and store it in the
'fname' variable
fname = input("Input your First Name : ")

# Prompt the user to input their last name and store it in the
'lname' variable
lname = input("Input your Last Name : ")

# Display a greeting message with the last name followed by


the first name
print("Hello " + lname + " " + fname)
Sample Output:
Input your First Name : Dany
Input your Last Name : Boon
Hello Boon Dany

4. List and Tuple Generator


Write a Python program that accepts a sequence of comma-
separated numbers from the user and generates a list and a
tuple of those numbers.
# Prompt the user to input a sequence of comma-separated
numbers and store it in the 'values' variable
values = input("Input some comma-separated numbers: ")

# Split the 'values' string into a list using commas as separators


and store it in the 'list' variable
list = [Link](",")

# Convert the 'list' into a tuple and store it in the 'tuple' variable
tuple = tuple(list)

# Print the list


print('List : ', list)

# Print the tuple


print('Tuple : ', tuple)
output
Input some comma seprated numbers : 3,5,7,23
List : ['3', '5', '7', '23']
Tuple : ('3', '5', '7', '23')

5.
First and Last Colors
Write a Python program to display the first and last colors from
the following list.
color_list = ["Red","Green","White" ,"Black"]

# Create a list called 'color_list' containing color names


color_list = ["Red", "Green", "White", "Black"]
# Print the first and last elements of the 'color_list' using string
formatting
# The '%s' placeholders are filled with the values of
'color_list[0]' (Red) and 'color_list[-1]' (Black)
print("%s %s" % (color_list[0], color_list[-1]))
output:
Red Black
6. Exam Schedule Formatter
Write a Python program to display the examination schedule.
(extract the date from exam_st_date).
exam_st_date = (11, 12, 2014)
Sample Output: The examination will start from : 11 / 12 / 2014
# Define a tuple called 'exam_st_date' containing the exam
start date in the format (day, month, year)
exam_st_date = (11, 12, 2014)

# Print the exam start date using string formatting


# The '%i' placeholders are filled with the values from the
'exam_st_date' tuple
print("The examination will start from : %i / %i / %i" %
exam_st_date)

Copy
Sample Output:
The examination will start from : 11 / 12 / 2014

7. Monthly Calendar Display


Write a Python program that prints the calendar for a given
month and year.
Note: Use 'calendar' module.
Python [Link](theyear, themonth, w=0, l=0):
The function returns a month’s calendar in a multi-line string
using the formatmonth() of the TextCalendar class.
'l' specifies the number of lines that each week will use.

# Import the 'calendar' module


import calendar

# Prompt the user to input the year and month


y = int(input("Input the year : "))
m = int(input("Input the month : "))

# Print the calendar for the specified year and month


print([Link](y, m))
Sample Output:
Input the year : 2017
Input the month : 04
April 2017
Mo Tu We Th Fr Sa Su
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

8. Multi-line Here Document


Write a Python program to print the following 'here document'.
Sample string:
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
Sample Solution:
Python Code:
# Use triple double-quotes to create a multi-line string
print("""
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
""")

Copy
Sample Output:
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example

9. Character ASCII Value


Write a Python program to get the ASCII value of a character.
ASCII (Listeni/ˈæski/ ass-kee), abbreviated from American
Standard Code for Information Interchange, is a character
encoding standard. ASCII codes represent text in computers,
telecommunications equipment, and other devices. Most
modern character-encoding schemes are based on ASCII,
although they support many additional characters.
Pictorial Presentation:

Sample Solution:
Python Code:
# Print a newline character for spacing.
print()

# Print the Unicode code point of the character 'a'.


print(ord('a'))

# Print the Unicode code point of the character 'A'.


print(ord('A'))

# Print the Unicode code point of the character '1'.


print(ord('1'))

# Print the Unicode code point of the character '@'.


print(ord('@'))

# Print a newline character for spacing.


print()

Copy
Sample Output:
97
65
49
64

10. Python Basic: Exercise-62 with Solution

Time to Seconds Converter


Write a Python program to convert all units of time into
seconds.
Pictorial Presentation:
Sample Solution:-
Python Code:
# Prompt the user to input a number of days and store it in the
variable 'days'.
days = int(input("Input days: ")) * 3600 * 24
# Prompt the user to input a number of hours and store it in the
variable 'hours'.
hours = int(input("Input hours: ")) * 3600
# Prompt the user to input a number of minutes and store it in
the variable 'minutes'.
minutes = int(input("Input minutes: ")) * 60
# Prompt the user to input a number of seconds and store it in
the variable 'seconds'.
seconds = int(input("Input seconds: "))
# Calculate the total time in seconds by adding the converted
values.
time = days + hours + minutes + seconds
# Print the total time in seconds.
print("The amount of seconds:", time)

Copy
Sample Output:
Input days: 4
Input hours: 5
Input minutes: 20
Input seconds: 10
The amounts of seconds 364810

11. Python Conditional: Exercise-4 with Solution

Write a Python program to construct the following pattern,


using a nested for loop.
*
**
***
****
*****
****
***
**
*

Sample Solution:
Python Code:
# Set the value of 'n' to 5 (this will determine the number of
lines in the pattern)
n=5

# Iterate through the range of numbers from 0 to 'n' (exclusive)


for i in range(n):
# Iterate through the range of numbers from 0 to 'i'
(exclusive) for each 'i' in the outer loop
for j in range(i):
# Print '*' followed by a space without a new line (end=""
ensures printing in the same line)
print('* ', end="")
# Move to the next line after printing '*' characters for the
current 'i'
print('')

# Iterate through the range of numbers from 'n' down to 1


(inclusive), decreasing by 1 in each iteration
for i in range(n, 0, -1):
# Iterate through the range of numbers from 0 to 'i'
(exclusive) for each 'i' in the outer loop
for j in range(i):
# Print '*' followed by a space without a new line (end=""
ensures printing in the same line)
print('* ', end="")
# Move to the next line after printing '*' characters for the
current 'i'
print('')

Copy
Sample Output:
*
**
***
****
*****
****
***
**
*

12. Write a Python program to print the alphabet pattern 'A'.


Expected Output:
***
* *
* *
*****
* *
* *
* *
# Initialize an empty string named 'result_str'
result_str = ""
# Iterate through rows from 0 to 6 using the range function
for row in range(0, 7):
# Iterate through columns from 0 to 6 using the range
function
for column in range(0, 7):
# Check conditions to determine whether to place '*' or ' '
in the result string

# If conditions are met, place '*' in specific positions based


on row and column values
if (((column == 1 or column == 5) and row != 0) or ((row ==
0 or row == 3) and (column > 1 and column < 5))):
result_str = result_str + "*" # Append '*' to the
'result_str'
else:
result_str = result_str + " " # Append space (' ') to the
'result_str'

result_str = result_str + "\n" # Add a newline character after


each row in 'result_str'

# Print the final 'result_str' containing the pattern


print(result_str)

Copy
Sample Output:
***
* *
* *
*****
* *
* *
* *

13. Write a Python program to print the alphabet pattern 'M'.


Expected Output:
* *
* *
** **
* * *
* *
* *
* *
# Initialize an empty string named 'result_str'
result_str = ""

# Iterate through rows from 0 to 6 using the range function


for row in range(0, 7):
# Iterate through columns from 0 to 6 using the range
function
for column in range(0, 7):
# Check conditions to determine whether to place '*' or ' '
in the result string

# If conditions are met, place '*' in specific positions based


on row and column values
if (column == 1 or column == 5 or (row == 2 and (column
== 2 or column == 4)) or (row == 3 and column == 3)):
result_str = result_str + "* " # Append '*' followed by a
space (' ') to the 'result_str'
else:
result_str = result_str + " " # Append two spaces (' ')
to the 'result_str'

result_str = result_str + "\n" # Add a newline character after


each row in 'result_str'

# Print the final 'result_str' containing the pattern


print(result_str)

Copy
Sample Output:
* *
* *
** **
* * *
* *
* *
* *

14. Write a Python program to convert a month name to a


number of days.
Expected Output:
List of months: January, February, March, April, May, June,
July, August
, September, October, November, December
Input the name of Month: February
No. of days: 28/29 days
Write a Python program to convert a month name to a number
of days.
Sample Solution:
Python Code:
# Display a list of months to the user
print("List of months: January, February, March, April, May,
June, July, August, September, October, November,
December")

# Request input from the user to enter the name of a month


and assign it to the variable 'month_name'
month_name = input("Input the name of Month: ")

# Check the input 'month_name' and provide the number of


days based on the entered month
if month_name == "February":
print("No. of days: 28/29 days") # Display the number of
days in February (28 or 29 days for leap years)
elif month_name in ("April", "June", "September", "November"):
print("No. of days: 30 days") # Display the number of days
for months having 30 days
elif month_name in ("January", "March", "May", "July",
"August", "October", "December"):
print("No. of days: 31 days") # Display the number of days
for months having 31 days
else:
print("Wrong month name") # If the entered month name
doesn't match any of the above conditions, display an error
message
Sample Output:
List of months: January, February, March, April, May, June,
July, August, September, October, November, Decemb
er
Input the name of Month: April
No. of days: 30 days

15. a = 20

b = 30
result=a+b
print("Addition of two numbers")
print(a," and ",b," = ",result)

To download raw file Click Here

Output
Addition of two numbers
20 and 30 = 50

16. a=int(input("Enter Number 1 : "))


b=int(input("Enter Number 2 : "))

print("Arithmetic Operations")

print("Addition :",a + b)

print("Subtraction :",a - b)
print("Multiplication :",a * b)

print("Division :",a / b)

print("Modulo :",a % b)

print("Exponentiation :",a ** b)

print("Floor Division :",a // b)

To download raw file Click Here

Output
Enter Number 1 : 20
Enter Number 2 : 13

Arithmetic Operations

Addition : 33
Subtraction : 7
Multiplication : 260
Division : 1.5384615
Modulo : 7
Exponentiation : 81920000
Floor Division : 1

17.

Python qutions and answer

[Link] a Python function to find the maximum of three


numbers.
Sample Solution:
Python Code:
# Define a function that returns the maximum
of two numbers
def max_of_two(x, y):
# Check if x is greater than y
if x > y:
# If x is greater, return x
return x
# If y is greater or equal to x, return y
return y
# Define a function that returns the maximum
of three numbers
def max_of_three(x, y, z):
# Call max_of_two function to find the
maximum of y and z,
# then compare it with x to find the
overall maximum
return max_of_two(x, max_of_two(y, z))

# Print the result of calling max_of_three


function with arguments 3, 6, and -5
print(max_of_three(3, 6, -5))

Copy
Sample Output:
6
2. Find Maximum of two numbers in Python
Last Updated : 29 Nov, 2024


In this article, we will explore various methods to find


maximum of two numbers in Python. The simplest way
to find maximum of two numbers in Python is by using
built-in max() function.
Python

a=7
2

b=3
3

print(max(a, b))

Output
7
3. How to Add Two Numbers in Python
Input: num1 = 5, num2 = 3
Output: 8
Input: num1 = 13, num2 = 6
Output: 19
[Link] Two Numbers with “+” Operator
# Python3 program to add two numbers

num1 = 15

num2 = 12

# Adding two nos

sum = num1 + num2

# printing values

print("Sum of", num1, "and", num2 , "is", sum)


How can you create and use a Module in Python??
def greeting(name):
print("Hello, " + name)
Can you list Python's primary built-in data types,
in 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
How to check if a number is odd or even?
# Prompt the user to enter a number and
convert the input to an integer
num = int(input("Enter a number: "))

# Calculate the remainder when the number is


divided by 2
mod = num % 2

# Check if the remainder is greater than 0,


indicating an odd number
if mod > 0:
# Print a message indicating that the
number is odd
print("This is an odd number.")
else:
# Print a message indicating that the
number is even
print("This is an even number.")

[Link] Maximum of two numbers in Python?

[Link] to Add Two Numbers in Python?


[Link] Two Numbers with “+” Operator?

[Link] you list Python's primary built-in data types, in categories?

A)Text Type: B)Numeric Types:

5. How to check if a number is odd or even?


[Link] the following select one that is not a computer programming
language
a) Python
b) C++
c) Java
d) Scanner

[Link] the following select one computer programming language


a) Writer
b) GeoGebra
c) GIMP
d) Python

[Link] is the full form of IDE

[Link] the following choose the IDE that are used to write programms in
python language
a) IDLE
b) Geany
c) Turbo C++
d) VB IDE

[Link] when you execute a general purpose program in IDLE, the


output will be shown in window.
a) python shell window
b) python graphic window
c) python editor
d) None of these
[Link] the output a program written in python is graphical then it appears
in a window
a) python shell window
b) python graphic window
c) python editor
d) None of these

[Link] the following which in the associated software to create


geometric shapes in python
a) Turtle
b) Writer
c) Calc
d) None of these

[Link] command is used to add in the starting of a python program to


work graphic commands
a) from turtle import
b) from input import
c) from Gimp import
d) None of these

[Link] the following which command is equivalent to forward(100)


a) fw (100)
b) for (100)
c) fd (100)
d) fwd (100)

15.A loop statement contains another loop statement then it is called


………….
a) Nested loop
b) Direct loop
c) Indirect loop
d) None of these

Question 1.
From the following select one that is not a computer programming
language
a) Python
b) C++
c) Java
d) Scanner
Answer:
d) Scanner

Question 2.
From the following select one computer programming language
a) Writer
b) GeoGebra
c) GIMP
d) Python
Answer:
d) Python

The uml full form is the Unified Modeling Language.

Question 3.
What is the full form of IDE
Answer:
a) Integrated Development Environment

Question 4.
From the following choose the IDE that are used to write programms
in python language
a) IDLE
b) Geany
c) Turbo C++
d) VB IDE
Answer:
a and b

Question 5.
Noramlly when you execute a general purpose program in IDLE, the
output will be shown in window.
a) python shell window
b) python graphic window
c) python editor
d) None of these
Answer:
a) python shell window

Question 6.
If the output a program written in python is graphical then it appears
in a window
a) python shell window
b) python graphic window
c) python editor
d) None of these
Answer:
b) python graphic window

Question 7.
From the following which in the associated software to create
geometric shapes in python
a) Turtle
b) Writer
c) Calc
d) None of these
Answer:
a) Turtle

Question 8.
Which command is used to add in the starting of a python program
to work graphic commands
a) from turtle import
b) from input import
c) from Gimp import
d) None of these
Answer:
a) from turtle import

Question 9.
From the following which command is equivalent to forward(100)
a) fw (100)
b) for (100)
c) fd (100)
d) fwd (100)
Answer:
c) fd (100)

Question 10.
From the following which command is equivalent to right (90)
a) rt (90)
b) rgt (100)
c) rht (90)
d) rgt (90)
Answer:
a) rt (90)
Question 11.
A loop statement contains another loop statement then it is called
………….
a) Nested loop
b) Direct loop
c) Indirect loop
d) None of these
Answer:
a) Nested loop

You might also like