0% found this document useful (0 votes)
56 views10 pages

Exp4

The document outlines an academic experiment focused on understanding For Loops in Python, detailing the theory, program examples, and practice problems. It includes objectives, prerequisites, and references for further learning. The experiment is part of a course on Creative Coding in Python at Fr. Conceicao Rodrigues College of Engineering for the academic year 2024-2025.

Uploaded by

lahaho6097
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)
56 views10 pages

Exp4

The document outlines an academic experiment focused on understanding For Loops in Python, detailing the theory, program examples, and practice problems. It includes objectives, prerequisites, and references for further learning. The experiment is part of a course on Creative Coding in Python at Fr. Conceicao Rodrigues College of Engineering for the academic year 2024-2025.

Uploaded by

lahaho6097
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

FR.

CONCEICAO RODRIGUES COLLEGE OF ENGINEERIG


Department of Mechanical Engineering

Academic Year 2024-2025 Estimated Experiment No. 4 – 02 Hours


Time
Course & Semester F.E. CE Subject Name Creative Coding in Python
Module No. 03 Chapter Title Decision Flow Control Statements
Experiment Type Software Subject Code VSE11ME02
Performance

Name of Olin Xavier Lemos Roll No. 10303


Student

Date of 09/01/2025 Date of 09/01/2025


Performance.: Submission.
:
CO Mapping CO2: Demonstrate basic concepts of python programming.

Objective of Experiment: The aim of this experiment is to understand the concepts of For Loops in python.

Pre-Requisite:
Tools: Any IDLE, Juypter Notebook / google colab/pycharm/VScode etc

Theory:
A for loop is used for iterating over a sequence (that is either a list, a dictionary, or a string etc).
This is less like the for keyword in other programming languages, and works more like an iterator method as
found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, dictionary, string etc
Example: Looping Through a With the continue statement we The range() Function
list can stop the current iteration of To loop through a set of code a
fruits = the loop, and continue with the specified number of times, we can
["apple", "banana", "cherry"] next: use the range() function,
for x in fruits: The range() function returns a
print(x) fruits = sequence of numbers, starting
["apple", "banana", "cherry"] from 0 by default, and increments
The for loop does not require an for x in fruits: by 1 (by default), and ends at a
indexing variable to be set if x == "banana": specified number.
Looping Through a String continue Example
for x in "banana": print(x) Using the range() function:
print(x) for x in range(6):
Continue in Python For Loop print(x)
With the break statement we Python continue Statement returns
can stop the loop before it has the control to the beginning of the The range() function defaults to 0
looped through all the items: loop. as a starting value, however it is
for x in fruits: # Prints all letters except 'e' and possible to specify the starting
print(x) 's' value by adding a
if x == "banana": parameter: range(2, 6), which
break for letter in 'I like java and means values from 2 to 6 (but not
python': including 6):

if letter == 'a' or letter == 'o': for x in range(2, 6):


continue print(x)
print('Current Letter :', letter)
The range() function defaults to Else in For Loop A nested loop is a loop inside a
increment the sequence by 1, The else keyword in a for loop loop.
however it is possible to specify specifies a block of code to be
the increment value by adding a executed when the loop is adj = ["red", "big", "tasty"]
third parameter: range(2, 30, 3): finished: fruits =
Example ["apple", "banana", "cherry"]
Example Print all numbers from 0 to 5, and
Increment the sequence with 3 print a message when the loop has for x in adj:
(default is 1): ended: for y in fruits:
for x in range(2, 30, 3): for x in range(6): print(x, y)
print(x) print(x)
else:
print("Finally finished!")

Example
Break the loop when x is 3, and
see what happens with
the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")

The pass Statement Python for loop in One Line Python For Loop with Zip()
for loops cannot be empty, but if This code uses the zip function to
you for some reason have Numbers =[x for x in range(11)] iterate over two lists in parallel.
a for loop with no content, put in print(Numbers)
the pass statement to avoid getting fruits = ["apple", "banana",
an error. # Iterating over dictionary "cherry"]
print("Dictionary Iteration") colors = ["red", "yellow", "green"]
for x in [0, 1, 2]: for fruit, color in zip(fruits,
pass people=[ colors):
{"name": "nayana", "age": 21}, print(fruit, "is", color)
In Python, {"name": "shweta", "age": 32},
the enumerate() function is used {"name": "rohan", "age": 22} Output :
with the for loop to iterate over an ] apple is red
iterable while also keeping track for person in people: banana is yellow
of the index of each item. for key, value in [Link](): cherry is green
The enumerate() function print(key, value)
provides both the index (count)
and the element (ele) for each
iteration.

l1 = ["eat", "sleep", "repeat"]


for count, ele in enumerate(l1):
print (count, ele)
Program
1.
def binary_to_decimal(binary_str):
"""Convert binary string to decimal."""
return int(binary_str, 2)

def decimal_to_binary(decimal_num):
"""Convert decimal number to binary string."""
return bin(decimal_num)[2:]

def binary_to_hexadecimal(binary_str):
"""Convert binary string to hexadecimal."""
decimal_num = binary_to_decimal(binary_str)
return hex(decimal_num)[2:]

def hexadecimal_to_binary(hex_str):
"""Convert hexadecimal string to binary."""
decimal_num = int(hex_str, 16)
return decimal_to_binary(decimal_num)

def decimal_to_hexadecimal(decimal_num):
"""Convert decimal number to hexadecimal."""
return hex(decimal_num)[2:]

def hexadecimal_to_decimal(hex_str):
"""Convert hexadecimal string to decimal."""
return int(hex_str, 16)

def ascii_to_binary(ascii_str):
"""Convert ASCII string to binary string."""
return ' '.join(format(ord(char), '08b') for char in ascii_str)

def binary_to_ascii(binary_str):
"""Convert binary string to ASCII string."""
binary_values = binary_str.split(' ')
ascii_chars = [chr(int(bv, 2)) for bv in binary_values]
return ''.join(ascii_chars)

def main():
"""Main function to run the conversion app."""
print("Welcome to the Binary Hexadecimal Conversion App!")
print("Choose the conversion type:")
print("1. Binary to Decimal")
print("2. Decimal to Binary")
print("3. Binary to Hexadecimal")
print("4. Hexadecimal to Binary")
print("5. Decimal to Hexadecimal")
print("6. Hexadecimal to Decimal")
print("7. ASCII to Binary")
print("8. Binary to ASCII")

choice = input("Enter your choice (1-8): ")

if choice == '1':
binary_str = input("Enter binary number: ")
print("Decimal:", binary_to_decimal(binary_str))
elif choice == '2':
decimal_num = int(input("Enter decimal number: "))
print("Binary:", decimal_to_binary(decimal_num))
elif choice == '3':
binary_str = input("Enter binary number: ")
print("Hexadecimal:", binary_to_hexadecimal(binary_str))
elif choice == '4':
hex_str = input("Enter hexadecimal number: ")
print("Binary:", hexadecimal_to_binary(hex_str))
elif choice == '5':
decimal_num = int(input("Enter decimal number: "))
print("Hexadecimal:", decimal_to_hexadecimal(decimal_num))
elif choice == '6':
hex_str = input("Enter hexadecimal number: ")
print("Decimal:", hexadecimal_to_decimal(hex_str))
elif choice == '7':
ascii_str = input("Enter ASCII string: ")
print("Binary:", ascii_to_binary(ascii_str))
elif choice == '8':
binary_str = input("Enter binary string (space-separated): ")
print("ASCII:", binary_to_ascii(binary_str))
else:
print("Invalid choice. Please select a number between 1 and
8.")

if __name__ == "__main__":
main()

2. import sys
import time
def rotating_spinner(duration):
"""Display a rotating line animation for a specified duration."""
spinner_symbols = ['|', '/', '-', '\\']
end_time = [Link]() + duration

while [Link]() < end_time:


for symbol in spinner_symbols:
[Link]('\r' + symbol) # Use '\r' to return to
the start of the line
[Link]() # Flush the output buffer
[Link](0.2) # Control the speed of the rotation

# Clear the spinner after the animation ends


[Link]('\r ') # Overwrite the last symbol with a space
[Link]()

if __name__ == "__main__":
print("Loading... Please wait.")
rotating_spinner(5) # Run the spinner for 5 seconds
print("\nDone!")

Output:1.

2.

Practice Programs:
1. Print the first 10 natural numbers using for loop.
2. Python program to print all the even numbers within the given range.
3. Python program to calculate the sum of all numbers from 1 to a given number.
4. Python program to calculate the sum of all the odd numbers within the given range.
5. Python program to print a multiplication table of a given number
6. Python program to display numbers from a list using a for loop.
7. Python program to count the total number of digits in a number.
8. Python program to check if the given string is a palindrome.
9. Python program that accepts a word from the user and reverses it.
10. Python program to check if a given number is an Armstrong number
11. Python program to count the number of even and odd numbers from a series of
numbers.
12. Python program to display all numbers within a range except the prime numbers.
13. Python program to get the Fibonacci series between 0 to 50.
14. Python program to find the factorial of a given number.
15. Python program that accepts a string and calculates the number of digits and letters.
16. Write a Python program that iterates the integers from 1 to 25.
17. Python program to check the validity of password input by users.
18. Python program to convert the month name to a number of days.

Programs and Outputs


1. Print the first 10 natural numbers using for loop.

2. Python program to print all the even numbers within the given range
[Link] program to calculate the sum of all numbers from 1 to a given number.

4. Python program to calculate the sum of all the odd numbers within the given range.
5. Python program to print a multiplication table of a given number

[Link] program to display numbers from a list using a for loop


Correctness & Logic & Problem Use of Python Timeline Total
Functionality Solving Approach Features (1 Marks) (10)
(3 Marks) with creativity (3 Marks)
(3 Marks)

References:
Study Materials Online repositories:
1. Yashvant Kanetkar, “Let us Python: Python is 1. Python 3 Documentation: [Link]
Future, Embrace it fast”, BPB Publications;1 3. "The Python Tutorial",
st edition (8 July 2019). [Link]
2. Dusty Phillips, “Python 3 object-oriented 4. [Link]
Programming”, Second Edition PACKT 5. Python 3 Tkinter library Documentation:
Publisher, August 2015. [Link]
3. John Grayson, “Python and Tkinter 6. Numpy Documentation: [Link]
Programming”, Manning Publications (1 March 7. Pandas Documentation: [Link]
1999). 8. Matplotlib Documentation:
4. Core Python Programming, Dr. R. Nageswara [Link]
Rao, Dreamtech Press 9. Scipy Documentation :
5. Beginning Python: Using Python 2.6 and [Link]
Python 3.1. James Payne, Wrox publication 10. Machine Learning Algorithm Documentation:
6. Introduction to computing and problem [Link]
solving using python, E. Balagurusamy, 11. [Link]
McGrawHill Education 12. NPTEL course: “The Joy of Computing using
Python”
13. [Link]
14. [Link]
methods/
15.
[Link]
-loop-in-python-examples/

Video Channels:
[Link]

[Link]

Data Visualization:
[Link]

You might also like