Skip to main content

Posts

Showing posts with the label add

Python - Set Functions - add, clear, difference, discard, intersection, checks, union, update

🐍 Advanced Sets Let's create a blank set and learn by example. Input s = Set() Add Elements to Set Input s.add(1) s.add(2) s Output {1, 2} This adds new elements to our existing set. Clear Input s.clear() s Output set() This empties the set. It deletes all elements. Copy Input s = {1,2,3} sc = s.copy() print(s,sc) Output {1, 3, 4} {1, 2, 3} This copies elements from one set to another. Difference Syntax set1.difference(set2) Input s.add(4) s.difference(sc) Output {4} This returns elements that are not common in the two sets. Difference Update Syntax set1.difference_update(set2) Input s1 = {1,2,3} s2 = {1,4,5} s1.difference_update(s2) s1 Output {2, 3} This updates set1 to the difference between set1 and set2. Discard Syntax set.discard(element) Input s = {1,2,3,4} s.discard(2) s Output {1, 3, 4} This deletes an element from the set, if that element exists in the set. Intersection Syntax set1.intersection(set2) Input s1 = {1,2,3} s2 = {2,3,4} s1.intersection(s2) Output {2, 3} It ret...

Python - Basic Mathematical Calculator

🐍  In Python, write a code to let users carry out basic mathematical calculations that include addition, subtraction, multiplication, and division. Solution def basic_operation(a, b, opp):     if opp[0] == '+':         return a+b     elif opp[0] == '-':         return a-b     elif opp[0] == '*':         return a*b     elif opp[0] == '/':         return a/b if __name__ == '__main__':     a = float(input('Enter first number: '))     opp = input("+ - * / ")     b = float(input('Enter second number: '))     print(basic_operation(a, b, opp))