Given a set of numbers as an input to the Python program you have to create a Python set and keep adding all the numbers into a set, Python set is a collection of unique items, items may be integer character string or any type.
Let's accept the integer type as an input to the right on the set and display all the items present in the set.
Write A Python Script To Add Members In A Set
Take a variable named length, the length variable is used to show the set length. ask a user to enter the length of the set using the input function call and convert it into an integer.
Take another variable named as unique and initialize it to an empty set as shown below.
length = int(input("Enter Set Length : "))
unique = set()
Using the for loop iterate from zero to the set length, inside the for loop ask a user to enter the set item and convert it into an integer and then use the built in function to add the item to the set. This will add members into a set.
for _ in range(length):
item = int(input("Enter Item to Add in Set : "))
unique.add(item)
Using the print function, call print and print a user-friendly message that is the “contents of the set”. Use another for loop to iterate all the members present in a set and print the members.
print("The contents of Set is : ")
for item in unique:
print(item)
Python Code
====================
length = int(input("Enter Set Length : "))
unique = set()
for _ in range(length):
item = int(input("Enter Item to Add in Set : "))
unique.add(item)
print("The contents of Set is : ")
for item in unique:
print(item)
Output
==================
Enter Set Length : 5
Enter Item to Add in Set : 1
Enter Item to Add in Set : 2
Enter Item to Add in Set : 3
Enter Item to Add in Set : 3
Enter Item to Add in Set : 4
The contents of Set is :
1
2
3
4
Conclusion
=================
Execute the above Python program and provide the set members as integer data type, note down the results
Comment down below if you have any suggestions to improve the above Python program
0 Comments