0% found this document useful (0 votes)
13 views12 pages

Python Lab Manual for CS-506 Students

The document is a lab manual for a Python course at Takshshila Institute of Engineering & Technology, detailing various programming exercises. It includes objectives, source code, and outputs for ten different Python scripts, covering topics such as arithmetic operations, factorial calculation, Armstrong numbers, and Fibonacci sequences. Each program is designed to help students practice and understand fundamental programming concepts in Python.

Uploaded by

aatul6419
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)
13 views12 pages

Python Lab Manual for CS-506 Students

The document is a lab manual for a Python course at Takshshila Institute of Engineering & Technology, detailing various programming exercises. It includes objectives, source code, and outputs for ten different Python scripts, covering topics such as arithmetic operations, factorial calculation, Armstrong numbers, and Fibonacci sequences. Each program is designed to help students practice and understand fundamental programming concepts in Python.

Uploaded by

aatul6419
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

TAKSHSHILA INSTITUTE OF

ENGINEERING & TECHNOLOGY,


JABALPUR(M.P)

LAB MANUAL

PYTHON

CS-506

Submitted By: Submitted To:


Prof. Harsha Kohli
Name:
Enrollment No: Asst. Professor
CSE DEPARTMENT

RAJIV GANDHI PRODYOGIKI


VISHWAVIDYALAY, BHOPAL,(M.P)

Department of Computer Science & Engineering [1]


INDEX:

[Link]. List Of Experiments Date Signature


1. Write a python script to take input
for a number calculate and
print its square and cube?

2. Write a python script to take input


for 2 numbers calculate and print
their sum, product and difference?
3. Write a python script to take input
for 3 numbers, check and print
the largest number?

4. Write a python script to take input


for 2 numbers and an operator
(+ , – , * , / ). Based on the operator
calculate and print the result?

5. Write a python script to take input


for a number and print its
table?

6. Write a python script to take input


for a number and print its
factorial?

7. Write a python script to take input


for a number check if the
entered number is Armstrong or
not.

8. Write a python script to take input


for a number and print its
factorial using recursion?

9. Write a python script to Display


Fibonacci Sequence Using
Recursion?

10. Write a Python script that prints


prime numbers less than 20.

Department of Computer Science & Engineering [2]


PROGRAM-1
OBJECTIVE- Write a python script to take input for a number calculate and
print its square and cube?

SOURCE CODE-

n = input("Enter the value :--> ")


n = int(n)
square = n ** 2
cube = n ** 3
print("\nSquare of the number :-->", square)
print("Cube of the number :-->", cube)

OUTPUT-

Enter the value :--> 2

Square of the number :--> 4


Cube of the number :--> 8

Department of Computer Science & Engineering [3]


PROGRAM-2
OBJECTIVE- Write a python script to take input for 2 numbers calculate and print their sum,
product and difference?

SOURCE CODE-
# Input the two numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Calculate the sum, difference, and product


sum_result = num1 + num2
diff_result = num1 - num2
prod_result = num1 * num2

# Display the results


print("Sum:", sum_result)
print("Difference:", diff_result)
print("Product:", prod_result)

OUTPUT-

Enter first number: 34


Enter second number: 23
Sum: 57.0
Difference: 11.0
Product: 782.0

Department of Computer Science & Engineering [4]


PROGRAM-3
OBJECTIVE- Write a python script to take input for 3 numbers, check and print

the largest number?

SOURCE CODE-

# Taking user input


num1 = int(input("Enter a first number : "))
num2 = int(input("Enter a second number : "))
num3 = int(input("Enter a third number : "))

# Condition checking

if num1>num2 and num1>num3:


print(f"First number ({num1}) is the largest.")
elif num2>num1 and num2>num3:
print(f"Second number ({num2}) is the largest.")
else:
print(f"Third number ({num3}) is the largest.")

OUTPUT-

Enter a first number : 23


Enter a second number : 45
Enter a third number : 1
Second number (45) is the largest.

=== Code Execution Successful ===

Department of Computer Science & Engineering [5]


PROGRAM-4
OBJECTIVE- Write a python script to take input for 2 numbers and an operator

(+ , – , * , / ). Based on the operator calculate and print the result?

SOURCE CODE-

a=int(input("Enter 1st number : "))


b=int(input("Enter 2nd number : "))
c=input("Enter the Operator +,-,*,/ : ")
if c=='+':
print("The Result is : ",a+b)
elif c=='-':
print("The Result is : ",a-b)
elif c=='*':
print("The Result is : ",a*b)
elif c=='/':
print("The Result is : ",a/b)
else:
print("Wrong Operator Entered")

OUTPUT-

Enter 1st number : 2


Enter 2nd number : 3
Enter the Operator +,-,*,/ : *
The Result is : 6

Department of Computer Science & Engineering [6]


PROGRAM-5
OBJECTIVE- Write a python script to take input for a number and print its

table?

SOURCE CODE-

n=int(input("Enter the number to print the tables for:"))


for i in range(1,11):
print(n,"x",i,"=",n*i)

OUTPUT-

Enter the number to print the tables for:2


2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

=== Code Execution Successful ===

Department of Computer Science & Engineering [7]


PROGRAM-6

OBJECTIVE- Write a python script to take input for a number and print its

factorial?

SOURCE CODE-
#Enter the number
n = int(input("Enter the number : "))

fac = 1
if n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, n + 1):
fac = fac * i
print("The factorial of the above number is",fac)

OUTPUT-

Enter the number : 4


The factorial of the above number is 24

=== Code Execution Successful ===

Department of Computer Science & Engineering [8]


PROGRAM-7
OBJECTIVE- Write a python script to take input for a number check if the

entered number is Armstrong or not.

SOURCE CODE-
take input from the user
num = int(input("Enter a number: "))

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


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

OUTPUT-

Enter a number: 23
23 is not an Armstrong number

=== Code Execution Successful ===

Department of Computer Science & Engineering [9]


PROGRAM-8
OBJECTIVE- Write a python script to take input for a number and print its

factorial using recursion?

SOURCE CODE-
# Factorial of a number using recursion

def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 7

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

OUTPUT-

The factorial of 7 is 5040

=== Code Execution Successful ===

Department of Computer Science & Engineering [10]


PROGRAM-9
OBJECTIVE- Write a python script to Display Fibonacci Sequence Using

Recursion?

SOURCE CODE-

def fibonacci(n):
if n <= 0:
return "Invalid input. The input should be a positive integer."
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
def print_fibonacci_series(n):
if n <= 0:
print("Invalid input. The input should be a positive integer.")
else:
print("Fibonacci Series:")
for i in range(1, n + 1):
print(fibonacci(i), end=" ")
# Test the program
n_terms = 10 # Change this value to generate more or fewer terms in the series
print_fibonacci_series(n_terms)

OUTPUT-

Fibonacci Series:
0 1 1 2 3 5 8 13 21 34
=== Code Execution Successful ===

Department of Computer Science & Engineering [11]


PROGRAM-10
OBJECTIVE- Write a Python script that prints prime numbers less than 20.

SOURCE CODE-

print("Prime numbers between 1 and 20 are:")


ulmt=20;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)

OUTPUT-

Prime numbers between 1 and 20 are:


2
3
5
7
11
13
17
19

=== Code Execution Successful ===

Department of Computer Science & Engineering [12]

Common questions

Powered by AI

Recursion is preferred for generating Fibonacci sequences due to its ability to clearly and concisely express the math problem. Each call in recursion directly corresponds to a term in the sequence, leading to more straightforward, readable code . However, recursion has drawbacks such as increased resource use and potential stack overflow for a large number of terms, since Python keeps a stack frame for each call. Iterative approaches are generally more memory-efficient and faster but at the cost of reduced code simplicity and elegance .

Recursion involves the function calling itself with a reduced problem size until it reaches a base case, as shown in calculating factorials where a function calls itself with decrements of the original number . Iteration, on the other hand, uses loops to repeat calculations until a condition is met. In Python, recursion can lead to stack overflow for large inputs due to limited stack size and can be less efficient in terms of memory usage when compared to iteration. However, recursion can simplify code and enhance readability for problems naturally expressible through self-reference, such as tree traversals or problems like the Fibonacci sequence .

In recursion, scope and variable lifetimes are crucial as each function call creates a new frame on the call stack where variables are established anew, independent of other calls. As illustrated in the recursive factorial calculation, each call to the recursive function handles its own variable 'n', maintaining all previous values on the stack until they are no longer needed, which is when the function execution completes . This ensures variables have lifetimes limited to their respective scope, allowing recursive calls to execute without mutual interference. This behavior enables recursion to naturally break down and rebuild a solution yet also risks stack overflow if the recursive depth is too great.

User input validation is crucial for Python scripts that require numerical inputs to ensure data integrity and prevent runtime errors. By validating inputs, one can ensure they are of the correct type, non-negative, or within a specified range, as demonstrated in the scripts for arithmetic operations and recursive processes where numerical correctness is pivotal . Failure to validate may lead to program crashes or incorrect calculations, making input validation a fundamental practice in robust script development.

To ensure correctness and handle errors while performing arithmetic operations in Python, it's essential to validate user inputs and manage exceptions. This can include checking the input type, ensuring division by zero is not attempted, validating operators in arithmetic expressions, and using try-except blocks to catch and handle any runtime errors. Moreover, providing informative messages when incorrect inputs or operations are detected can prevent exceptions from crashing the program, as demonstrated with operator validation in the arithmetic script .

An Armstrong number is one where the sum of its digits, each raised to the power of the number of digits, equals the number itself. In Python, the process involves iterating through each digit, calculating its cube (for a three-digit number), and then summing these cubes. The resulting sum is compared to the original number to determine if it is an Armstrong number. The provided script checks each digit and sums their cubes to decide the Armstrong status .

Safely handling division operations in Python involves checking the divisor before executing the division. In the arithmetic calculator example, it's essential to pre-condition the script to verify that the divisor is non-zero before performing any division to prevent runtime errors. Furthermore, implementing exception handling with try-except blocks can catch and manage such errors if they occur, ensuring the script can recover gracefully and provides informative error messages to guide user input while preventing crashes .

The 'else' clause in a for loop executes only when the loop completes all iterations without encountering a break statement. In the context of printing prime numbers, the 'else' clause ensures that a number is printed as prime if and only if no factors are found during the loop checks. This use of 'else' helps differentiate between numbers that complete all checks (and are prime) versus those that leave early due to finding a factor . This pattern is particularly useful for prime number detection as it simplifies the logic needed to assess primality.

Designing a Python script to determine the largest of three input numbers involves using comparison operators and conditional statements. The key constructs include reading inputs, applying conditions using if-elif-else statements to compare the numbers, and using logical operators to ensure each condition correctly identifies the largest number . This approach allows the program to check each pair of numbers and outputs the largest based on the set conditions.

Logical operators are vital in control flow as they allow compound conditions to be evaluated, enabling decision-making processes. In determining the largest number among three, logical operators such as 'and' help form complex conditions to verify multiple simultaneous inequalities. These operators thus ensure that conditional statements can correctly identify the precise conditions under which each number should be considered the largest, improving the clarity and reliability of logical decision blocks in the script .

You might also like