diff --git a/Beginner_Level/Abstract Class.py b/Beginner_Level/Abstract Class.py new file mode 100644 index 0000000..3920d0c --- /dev/null +++ b/Beginner_Level/Abstract Class.py @@ -0,0 +1,23 @@ + +from abc import ABC, abstractclassmethod # abc - abstract base class & python don't provide any abstract class there is a built-in modules which is in this line + + +class Shape(ABC): + @abstractclassmethod # its decorator + def area(self): pass # empty method + + #@abstractclassmethod # abstractmethod is a mthd which must be implemented in subclass + def perimeter(self):pass + +class Square(Shape): + def __init__(self, side): + self.__side = side + def area(self): + return self.__side * self.__side + def perimeter(self): + return 4 * self.__side + + +square = Square(5) # it can't be intantiated bcoz its abstract class +print(square.area()) +print(square.perimeter()) \ No newline at end of file diff --git a/Beginner_Level/Class.py b/Beginner_Level/Class.py new file mode 100644 index 0000000..ee6bea8 --- /dev/null +++ b/Beginner_Level/Class.py @@ -0,0 +1,50 @@ +class Human: + def __init__(self, n, o): + self.name = n + self.occupation = o + + def do_work(self): + if self.occupation == "Tennis Player": + print(self.name,"plays tennis") + elif self.occupation == "Cricket Player": + print(self.name,"Plays Cricket") + + def speak(self): + print(self.name,"\nsay how are you?") + +sachin = Human("Sachin Tendulkar","Cricker") +sachin.do_work() +sachin.speak() + +print('\n') + +maria = Human("Maria sharapova","Tennis") +sachin.do_work() +sachin.speak() + +print('\n') + + +# built-in class modules + +class Employee: + 'Common base class for all employees' + empCount = 0 + + def __init__(self, name, salary): + self.name = name + self.salary = salary + Employee.empCount += 1 + + def displayCount(self): + print("Total Employee %d" % Employee.empCount) + + def displayEmployee(self): + print("Name : ", self.name, ", Salary: ", self.salary) + + +print("Employee.__doc__:", Employee.__doc__) +print("Employee.__name__:", Employee.__name__) +print("Employee.__module__:", Employee.__module__) +print("Employee.__bases__:", Employee.__bases__) +print("Employee.__dict__:", Employee.__dict__) diff --git a/Beginner_Level/Closure + Nested Function/anotherclosureexample.py b/Beginner_Level/Closure + Nested Function/anotherclosureexample.py new file mode 100644 index 0000000..bf1bd45 --- /dev/null +++ b/Beginner_Level/Closure + Nested Function/anotherclosureexample.py @@ -0,0 +1,28 @@ + +def nth_power(exponent ): + def pow_of(base): + return pow(base, exponent) + return pow_of # note that we are returning function without function + +square = nth_power(2) +print(square(31)) +print(square(32)) +print(square(33)) +print(square(34)) +print(square(35)) +print(square(36)) +print(square(37)) +print(square(38)) +print(square(39)) + +print('------') + +cube = nth_power(3) +print(cube(2)) +print(cube(3)) +print(cube(4)) +print(cube(5)) +print(cube(6)) +print(cube(7)) +print(cube(8)) +print(cube(9)) \ No newline at end of file diff --git a/Beginner_Level/Closure + Nested Function/closure.py b/Beginner_Level/Closure + Nested Function/closure.py new file mode 100644 index 0000000..5c95976 --- /dev/null +++ b/Beginner_Level/Closure + Nested Function/closure.py @@ -0,0 +1,12 @@ +# nested function u can define function inside a fucntion + +# closures are sometimes uses in the placeof classes which usually have only one method or few method . Closures are highly used in decorators + +def outterFunction(text): + def innerFunction(): + print(text) + return innerFunction # to make closure fucntion from nested function you have to return function without paranthesis + +a = outterFunction("Hello") +del outterFunction +a() # after deleting outterfunction o/p - Hello means a variable is sotring some spaces for innerfunction even outterfunction is deleted this is magic of 'closure' \ No newline at end of file diff --git a/Beginner_Level/Closure + Nested Function/nested.py b/Beginner_Level/Closure + Nested Function/nested.py new file mode 100644 index 0000000..313c164 --- /dev/null +++ b/Beginner_Level/Closure + Nested Function/nested.py @@ -0,0 +1,11 @@ +def pop(list): + def get_last_item(my_list): + return my_list[len(list) - 1] + + list.remove(get_last_item(list)) + return list + +a = [1,2,3,4,5] +print(pop(a)) +print(pop(a)) +print(pop(a)) \ No newline at end of file diff --git a/Beginner_Level/Decorators In Python/Decorator _2(Divide).py b/Beginner_Level/Decorators In Python/Decorator _2(Divide).py new file mode 100644 index 0000000..c7d42b6 --- /dev/null +++ b/Beginner_Level/Decorators In Python/Decorator _2(Divide).py @@ -0,0 +1,16 @@ + +def decorator_divide(func): + def wrapper_func(a,b): + print('divide', a, ' and ', b) + if b == 0: + print("Division With Zero Not Alloawed Dusra Positive Number Daal ") + return + return a / b + return wrapper_func # RETURN WITHOUT PARANTHESIS + + +@decorator_divide +def divide(x,y): + return x/y + +print(divide(15,0)) \ No newline at end of file diff --git a/Beginner_Level/Decorators In Python/Decorator_1.py b/Beginner_Level/Decorators In Python/Decorator_1.py new file mode 100644 index 0000000..2402c61 --- /dev/null +++ b/Beginner_Level/Decorators In Python/Decorator_1.py @@ -0,0 +1,30 @@ +# Decorators wrap a function and modify its behaviour in one way or the another without having to directly change the source code of the function being decorated. + +def decorator_X(func): + def wrapper_func(): + print('X' * 20) + func() + print('X' * 20) + + return wrapper_func() + +def decorator_Y(func): + def wrapper_func(): + print('Y' * 20) + func() + print('Y' * 20) + + return wrapper_func # RETURN WITHOUT PARANTHESIS + + # @decorator_func # --1st + +@decorator_X # --2ND +@decorator_Y +def say_hello(): + print('Hello World') + + +# hello = decorator_func(say_hello()) # this is same as --1st +# hello = decorator_Y(decorator_X(say_hello)) # --2ND +# hello() + diff --git a/Beginner_Level/Decorators In Python/Decorator_3(Generic)].py b/Beginner_Level/Decorators In Python/Decorator_3(Generic)].py new file mode 100644 index 0000000..97387eb --- /dev/null +++ b/Beginner_Level/Decorators In Python/Decorator_3(Generic)].py @@ -0,0 +1,22 @@ + +from time import time +def timing(func): + def wrapper_func(*args, **kwargs): + start = time() + result = func(*args, **kwargs) + end = time() + print(end) + print(' Elapsed Time {}'.format(end - start)) + return result + + return wrapper_func # RETURN WITHOUT PARANTHESIS + +@timing +def my_func(num): + sum = 0 + for i in range(num+1): + sum +=i + + return sum + +print(my_func(200000)) \ No newline at end of file diff --git a/Beginner_Level/Frozen Set.py b/Beginner_Level/Frozen Set.py new file mode 100644 index 0000000..b5c096c --- /dev/null +++ b/Beginner_Level/Frozen Set.py @@ -0,0 +1,56 @@ +Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 +Type "help", "copyright", "credits" or "license()" for more information. +>>> # Frozen Set +>>> numbers = [1,2,3,4,1,5,6,4,2,3] +>>> fs = frozenset(numbers) +>>> fs +frozenset({1, 2, 3, 4, 5, 6}) +>>> fs.add(7) +Traceback (most recent call last): + File "", line 1, in + fs.add(7) +AttributeError: 'frozenset' object has no attribute 'add' +>>> +>>> +>>> +>>> # some basic operation with set +>>> +>>> x ={"a","b","c"} +>>> +>>> "a" in x +True +>>> "g" in x +False +>>> for i in x: + print(i) + + +a +c +b +>>> x +{'a', 'c', 'b'} +>>> y = {"a","h",g"} + +SyntaxError: EOL while scanning string literal +>>> y = {"a","h","g"} +>>> x +{'a', 'c', 'b'} +>>> y +{'g', 'h', 'a'} +>>> # to find union +>>> x|y +{'g', 'c', 'a', 'b', 'h'} +>>> # to find intersection +>>> x&y +{'a'} +>>> # to find difference +>>> x-y +{'c', 'b'} +>>> # to find subset +>>> x>> x={"h","g"} +>>> x>> \ No newline at end of file diff --git a/Beginner_Level/How To Create Modules/ClassModules/main.py b/Beginner_Level/How To Create Modules/ClassModules/main.py new file mode 100644 index 0000000..2fcb337 --- /dev/null +++ b/Beginner_Level/How To Create Modules/ClassModules/main.py @@ -0,0 +1,11 @@ + + +from rectangle import Rectangle +from triangle import Triangle + +rec = Rectangle() +tri = Triangle() +rec.set_values(50, 60) +tri.set_values(10, 45) +print(rec.area()) +print(tri.area()) \ No newline at end of file diff --git a/Beginner_Level/How To Create Modules/ClassModules/polygon.py b/Beginner_Level/How To Create Modules/ClassModules/polygon.py new file mode 100644 index 0000000..4f9272d --- /dev/null +++ b/Beginner_Level/How To Create Modules/ClassModules/polygon.py @@ -0,0 +1,13 @@ +class Polygon: + + __width = None + __height = None + + def set_values(self, width, height): + self.__width = width + self.__height = height + + def get_width(self): + return self.__width + def get_height(self): + return self.__height \ No newline at end of file diff --git a/Beginner_Level/How To Create Modules/ClassModules/rectangle.py b/Beginner_Level/How To Create Modules/ClassModules/rectangle.py new file mode 100644 index 0000000..67dd3ff --- /dev/null +++ b/Beginner_Level/How To Create Modules/ClassModules/rectangle.py @@ -0,0 +1,7 @@ + + +from polygon import Polygon + +class Rectangle(Polygon): + def area(self): + return self.get_width() * self.get_height() diff --git a/Beginner_Level/How To Create Modules/ClassModules/triangle.py b/Beginner_Level/How To Create Modules/ClassModules/triangle.py new file mode 100644 index 0000000..f5cddc3 --- /dev/null +++ b/Beginner_Level/How To Create Modules/ClassModules/triangle.py @@ -0,0 +1,7 @@ + +from polygon import Polygon: + + +class Triangle(Polygon): + def area(self): + return self.get_width() * self.get_height() / 2 \ No newline at end of file diff --git a/Beginner_Level/How To Create Modules/CreateModules.py b/Beginner_Level/How To Create Modules/CreateModules.py new file mode 100644 index 0000000..ec49016 --- /dev/null +++ b/Beginner_Level/How To Create Modules/CreateModules.py @@ -0,0 +1,17 @@ + +# module is nothing but a python file + +#from dir import imp --1st u caan also use as in this line # this code will auto appear after shifting the python file i.e. imp.py into new directory + +# above same code function can done with simple way of 1 line which is below + + +import dir.imp as rahul # as keyword for using short notation without as it was print((dir.imp.add(10,20))) + +print((rahul.add(56, 15))) +print((rahul.mul(56, 15))) + + + +# print((imp.add(56, 15))) --1st +# print((imp.mul(46, 57))) --1st \ No newline at end of file diff --git a/Beginner_Level/How To Create Modules/dir/imp.py b/Beginner_Level/How To Create Modules/dir/imp.py new file mode 100644 index 0000000..cc007f0 --- /dev/null +++ b/Beginner_Level/How To Create Modules/dir/imp.py @@ -0,0 +1,7 @@ + + +def add(a ,b): + return a+b + +def mul(a, b): + return a * b \ No newline at end of file diff --git a/Beginner_Level/Inheritance.py b/Beginner_Level/Inheritance.py new file mode 100644 index 0000000..3940df9 --- /dev/null +++ b/Beginner_Level/Inheritance.py @@ -0,0 +1,104 @@ +class Vehicle: + def genral_usage(self): + print("use for transportation") + +class Car(Vehicle): + def __init__(self): + print("I'm a car") + self.wheels = 4 + self.has_roof = True + + def specific_usage(self): + self.genral_usage() + print("specific usage: commute to work, vacation with family") + +class Motorcycle(Vehicle): + def __init__(self): + print("I'm a Motorcycle") + self.wheels = 2 + self.has_roof = False + + def specific_usage(self): + self.genral_usage() + print("specific usage: road trip, racing") + +c = Car() +#c.genral_usage() # if you don't want to call general_usage() explicitly, you can call inside class as above +c.specific_usage() +print('\n') +m = Motorcycle() +#m.genral_usage() +m.specific_usage() + +print('\n') + +print(isinstance(c,Car)) # check and return bool value +print(isinstance(c,Motorcycle)) + +print('\n') + +# another example + +class Parent: # define parent class + parentAttr = 100 + def __init__(self): + print("Calling parent constructor") + + def parentMethod(self): + print('Calling parent method') + + def setAttr(self, attr): + Parent.parentAttr = attr + + def getAttr(self): + print("Parent attribute :", Parent.parentAttr) + +class Child(Parent): # define child class + def __init__(self): + print("Calling child constructor") + + def childMethod(self): + print('Calling child method') + +c = Child() # instance of child +c.childMethod() # child calls its method +c.parentMethod() # calls parent's method +c.setAttr(200) # again call parent's method +c.getAttr() # again call parent's method + +print('\n') + +# method overriding + +class Parent: # define parent class + def myMethod(self): + print('Calling parent method') + +class Child(Parent): # define child class + def myMethod(self): + print('Calling child method') + +c = Child() # instance of child +c.myMethod() # child calls overridden method + +print('\n') + +# Multiple Inheritance + +class Father: + def skills(self): + print("Gardening & Programming") + +class Mother: + def skills(self): + print("cooking & art") + +class child(Father,Mother): + def skills(self): + Father.skills(self) + Mother.skills(self) + print("sports & gaming") + +c = child() +c.skills() + diff --git a/Beginner_Level/List,Set&Dictionary_Comprehension.py b/Beginner_Level/List,Set&Dictionary_Comprehension.py new file mode 100644 index 0000000..b222bd9 --- /dev/null +++ b/Beginner_Level/List,Set&Dictionary_Comprehension.py @@ -0,0 +1,61 @@ +Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 +Type "help", "copyright", "credits" or "license()" for more information. +>>> numbers = [1,2,3,4,5,6,7,8,9] +>>> even = [] +>>> for i in numbers: + if i%2==0: + even.append(i) + + +>>> even +[2, 4, 6, 8] +>>> # syntax [output for-loop condition] +>>> even = [i for i in numbers if i%2==0] +>>> even +[2, 4, 6, 8] +>>> cube_numbers = [i*i*i for i in numbers] +>>> cube_numbers +[1, 8, 27, 64, 125, 216, 343, 512, 729] +>>> +>>> +>>> +>>> +>>> +>>> # Set Comprehension +>>> s = set{[1,2,3,4,5,2,3]} +SyntaxError: invalid syntax +>>> s = set([1,2,3,4,5,2,3]) +>>> s +{1, 2, 3, 4, 5} +>>> type(s) + +>>> even = { i for in s if i%2==0} +SyntaxError: invalid syntax +>>> even +[2, 4, 6, 8] +>>> +>>> +>>> +>>> +>>> # Dictionary Comprehension +>>> +>>> cities = ["Mumbai","new york","tokyo"] +>>> country = ["India","USA","Japan"] +>>> z = zip(cities,country) +>>> z + +>>> for a in z: + print(a) + + +('Mumbai', 'India') +('new york', 'USA') +('tokyo', 'Japan') +>>> d = {city:country for city, country in zip(cities,country)} +>>> d +{'Mumbai': 'India', 'new york': 'USA', 'tokyo': 'Japan'} +>>> type(d) + +>>> dir(d) +['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] +>>> \ No newline at end of file diff --git a/Beginner_Level/More on function - Default arguments.py b/Beginner_Level/More on function - Default arguments.py new file mode 100644 index 0000000..47dcc06 --- /dev/null +++ b/Beginner_Level/More on function - Default arguments.py @@ -0,0 +1,23 @@ + +# Deualt arguments *args and *kwargs + + +#def student(name = 'unknown name', age = 0): --1st + + +def student(name, age, **marks): #*marks): # u can use double Asterix to declare key value pair # provide this type i.e. marks at the last so it can readable easily # USING METRIX IN FRONT OF ARGUMENTS IN PYHTON MEANS U CAN PROVIDE MULTIPLE ARGUMENTS + + print("name : ", name) + print('age : ', age ) + print('marks :', marks) + + + +# u can use for loop with marks even + + + +#student() # defuallt values when u don't provide values -- 1st + + +student('rahul', 18,cs= 196, physics = 80, che = 74,maths = 67,english = 61, evs = 46) # whenever u use double asterix then it will print in the form of dictionary # IT WILL PRINT IN THE FORM OF TUPPLES diff --git a/Beginner_Level/Polymorphism.py b/Beginner_Level/Polymorphism.py new file mode 100644 index 0000000..60a806f --- /dev/null +++ b/Beginner_Level/Polymorphism.py @@ -0,0 +1,28 @@ +class India(): + def capital(self): + print("New Delhi is the capital of India.") + + def language(self): + print("Hindi is the most widely spoken language of India.") + + def type(self): + print("India is a developing country.") + + +class USA(): + def capital(self): + print("Washington, D.C. is the capital of USA.") + + def language(self): + print("English is the primary language of USA.") + + def type(self): + print("USA is a developed country.") + + +obj_ind = India() +obj_usa = USA() +for country in (obj_ind, obj_usa): + country.capital() + country.language() + country.type() \ No newline at end of file diff --git a/Beginner_Level/Set.py b/Beginner_Level/Set.py new file mode 100644 index 0000000..4a1ff6a --- /dev/null +++ b/Beginner_Level/Set.py @@ -0,0 +1,40 @@ +Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 +Type "help", "copyright", "credits" or "license()" for more information. +>>> basket = {"apple","mango","orange","pear","banana","apple"} +>>> basket +{'apple', 'pear', 'banana', 'orange', 'mango'} +>>> a = set() +>>> a.add(11) +>>> a.add(22) +>>> a.add(33) +>>> a.add(44) +>>> a +{33, 11, 44, 22} +>>> # don't initialize empty set bcoz python consider it set dictionary +>>> b = {} +>>> type(b) + +>>> b = {'somrthing'} +>>> b +{'somrthing'} +>>> type(b) + +>>> # since set is unordered that means you can't access using index +>>> basket[0] +Traceback (most recent call last): + File "", line 1, in + basket[0] +TypeError: 'set' object is not subscriptable +>>> +>>> +>>> +>>> +>>> # creating set from list by passing list as argument in constructor of set +>>> numbers = [1,2,3,4,5,2,1,3,5] +>>> set_numbers = set(numbers) +>>> set_numbers +{1, 2, 3, 4, 5} +>>> set_numbers.add(6) +>>> set_numbers +{1, 2, 3, 4, 5, 6} +>>> \ No newline at end of file diff --git a/Beginner_Level/__name__ = __main__/caller.py b/Beginner_Level/__name__ = __main__/caller.py new file mode 100644 index 0000000..ca905d2 --- /dev/null +++ b/Beginner_Level/__name__ = __main__/caller.py @@ -0,0 +1,3 @@ +import main +print("I'm in caller.py") +main.calculate_volume(12) \ No newline at end of file diff --git a/Beginner_Level/__name__ = __main__/main.py b/Beginner_Level/__name__ = __main__/main.py new file mode 100644 index 0000000..8590848 --- /dev/null +++ b/Beginner_Level/__name__ = __main__/main.py @@ -0,0 +1,8 @@ +def calculate_volume(radius): + print("__name__:",__name__) + return 1.33*3.14*radius*radius*radius + +if __name__ == "__main__": + print("I'm in main.py") + v = calculate_volume(10) + print("Volume:",v) diff --git a/Beginner_Level/aggregation.py b/Beginner_Level/aggregation.py new file mode 100644 index 0000000..721fe2e --- /dev/null +++ b/Beginner_Level/aggregation.py @@ -0,0 +1,27 @@ + +# COMPOSITION HAS relation of 'PART - OF ' # +# AGGREGATION HAS relation of 'HAS - A' # + +class Salary: + + def __init__(self, pay, bonus): + self.pay = pay + self.bonus = bonus + + def annual_salary(self): + return (self.pay*12) + self.bonus + +class Employee: + def __init__(self, name, age , salary): + self.name= name + self.age= age + self.obj_salary = salary; + + def total_salary(self): + return self.obj_salary.annual_salary() + + +salary = Salary(15000, 10000) +emp = Employee('easynamila', 25, salary) # Its unidirectional only salary is passing not name and age # don't forget to pass salary object + +print(emp.total_salary()) \ No newline at end of file diff --git a/Beginner_Level/composition.py b/Beginner_Level/composition.py new file mode 100644 index 0000000..208a899 --- /dev/null +++ b/Beginner_Level/composition.py @@ -0,0 +1,24 @@ + +# in composition we have delegates some responisibilities from subclass to superclass or vice versa if it don't have is-a relation for eg. employee and salary + +class Salary: + + def __init__(self, pay, bonus): + self.pay = pay + self.bonus = bonus + + def annual_salary(self): + return (self.pay*12) + self.bonus + +class Employee: + def __init__(self, name, age , pay, bonus): + self.name= name + self.age= age + self.obj_salary = Salary(pay, bonus) + + def total_salary(self): + return self.obj_salary.annual_salary() + +emp = Employee('rahul', 25 , 15000, 10000) + +print(emp.total_salary()) \ No newline at end of file diff --git a/Beginner_Level/idea behind if __name__ == __main__/mymath.py b/Beginner_Level/idea behind if __name__ == __main__/mymath.py new file mode 100644 index 0000000..2973fdd --- /dev/null +++ b/Beginner_Level/idea behind if __name__ == __main__/mymath.py @@ -0,0 +1,9 @@ + + # see result by right click and run on both mymath.py and test.py and see difference + +def add(a, b): + return a+b + +print(__name__) +if __name__ == "__main__": # this is same as main method in c++ or other pro. lang. + print(add(10,16)) \ No newline at end of file diff --git a/Beginner_Level/idea behind if __name__ == __main__/see it .png b/Beginner_Level/idea behind if __name__ == __main__/see it .png new file mode 100644 index 0000000..3d6dd2e Binary files /dev/null and b/Beginner_Level/idea behind if __name__ == __main__/see it .png differ diff --git a/Beginner_Level/idea behind if __name__ == __main__/test.py b/Beginner_Level/idea behind if __name__ == __main__/test.py new file mode 100644 index 0000000..5d1270c --- /dev/null +++ b/Beginner_Level/idea behind if __name__ == __main__/test.py @@ -0,0 +1,5 @@ + + +import mymath + +print(mymath.add(7,6)) \ No newline at end of file diff --git a/Beginner_Level/lambda in filter,map & reduce.py b/Beginner_Level/lambda in filter,map & reduce.py new file mode 100644 index 0000000..a84a5d4 --- /dev/null +++ b/Beginner_Level/lambda in filter,map & reduce.py @@ -0,0 +1,49 @@ + +# Lambda Functions is also known as Anonymous function bcoz they don't have any name some tym they also called oneline function bcoz they written in oneline of code +# function returning from function thats where lambda function are used + +from functools import reduce + +# def double(x): +# return x*2 +# +# def add(x,y): +# return x+y +# +# def pro(x,y,z): +# return x*y*z + + +# Lambda function of above functions + +double = lambda x : x * 2 +add = lambda x, y : x + y +pro = lambda x, y, z : x * y * z + +print(double(10)) +print(add(10,20)) +print(pro(10,20,30)) + +# map, filter, reduce + +my_list1 = [2,5,8,10,9,3] +my_list2 = [1,4,7,8,5,1] + +a = map(lambda x : x * 2, my_list1) +print(list(a)) # u must to cast list otherwise it will give wierd hexadecimal instead of list + +b = map(lambda x, y : x + y, my_list1 , my_list2) +print(list(b)) + +# filter function gives boolean value and it take function as 1st argument + +c= filter(lambda x : x%2 ==0, my_list1) +print(list(c)) + +d= filter(lambda x : True if x > 5 else False, my_list1) # using if else inside filter +print(list(d)) + +# to use reduce we have import functool at the top + +e = reduce(lambda x, y : x+y, my_list1) +print(e) \ No newline at end of file diff --git a/Beginner_Level/multiple constructor.py b/Beginner_Level/multiple constructor.py new file mode 100644 index 0000000..11cf9dd --- /dev/null +++ b/Beginner_Level/multiple constructor.py @@ -0,0 +1,16 @@ + + +# IT ISN'T NOT POSSIBLE TO DECLARE MULTIPLE INIT METHOD IF U DECLARE MULTIPLE INIT MTHD THEN PYTHON WILL CONSIDERED LAST INIT METHOD AS MAIN AND PREVIOUS INIT METHOD IS OVERWRITTEN BY LAST INIT METHOD + +class Hello: + # def __init__(self): pass # it is an empty method + # def __init__(self, name): pass + # def __init__(self, *args, **kwargs): pass # -- 1st + + def __init__(self,name): + self.name = name + self.age = 10 # it is possible to declare attributes without passing as arguments in the function + + +hello = Hello() +hello = Hello('name', 'age', name = 'chaman') # -- 1st \ No newline at end of file diff --git a/Beginner_Level/super( ).py b/Beginner_Level/super( ).py new file mode 100644 index 0000000..d2ca0d0 --- /dev/null +++ b/Beginner_Level/super( ).py @@ -0,0 +1,21 @@ + +class Parent: + def __init__(self, name): + print('Parent __init__', name) + + +class Parent2: + def __init__(self, name): + print('Parent2 __init__', name) + +class Child(Parent, Parent2): + def __init__(self): + print('Child __init__') + super().__init__('chamn') # to call the __init__ of superclas + # Parent.__init__(self, 'ram') + # Parent2.__init__(self, 'max') + +child = Child() +print(Child.__mro__) # mro method resoution order. After running u can see that 1st method of child class executed then parents class method + + diff --git a/Beginner_Level/swap_two_variables.py b/Beginner_Level/swap_two_variables.py new file mode 100644 index 0000000..9be27d4 --- /dev/null +++ b/Beginner_Level/swap_two_variables.py @@ -0,0 +1,16 @@ +# Python program to swap two variables + +x = 5 +y = 10 + +# To take inputs from the user +#x = input('Enter value of x: ') +#y = input('Enter value of y: ') + +# create a temporary variable and swap the values +temp = x +x = y +y = temp + +print('The value of x after swapping: {}'.format(x)) +print('The value of y after swapping: {}'.format(y)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/ATM_System.py b/Beginner_Level_Python_programs/ATM_System.py new file mode 100644 index 0000000..ec63432 --- /dev/null +++ b/Beginner_Level_Python_programs/ATM_System.py @@ -0,0 +1,120 @@ +import random + + +class Account: + # Construct an Account object + def __init__(self, id, balance=0, annualInterestRate=3.4): + self.id = id + self.balance = balance + self.annualInterestRate = annualInterestRate + + def getId(self): + return self.id + + def getBalance(self): + return self.balance + + def getAnnualInterestRate(self): + return self.annualInterestRate + + def getMonthlyInterestRate(self): + return self.annualInterestRate / 12 + + def withdraw(self, amount): + self.balance -= amount + + def deposit(self, amount): + self.balance += amount + + def getMonthlyInterest(self): + return self.balance * self.getMonthlyInterestRate() + + +def main(): + # Creating accounts + accounts = [] + for i in range(1000, 9999): + account = Account(i, 0) + accounts.append(account) + + # ATM Processes + + +while True: + + # Reading id from user + id = int(input("\nEnter account pin: ")) + + # Loop till id is valid + while id < 1000 or id > 9999: + id = int(input("\nInvalid Id.. Re-enter: ")) + + # Iterating over account session + while True: + + # Printing menu + print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ") + + # Reading selection + selection = int(input("\nEnter your selection: ")) + + # Getting account object + for acc in accounts: + # Comparing account id + if acc.getId() == id: + accountObj = acc + break + + # View Balance + if selection == 1: + # Printing balance + print(accountObj.getBalance()) + + # Withdraw + elif selection == 2: + # Reading amount + amt = float(input("\nEnter amount to withdraw: ")) + ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ") + + if ver_withdraw == "Yes": + print("Verify withdraw") + else: + break + + if amt < accountObj.getBalance(): + # Calling withdraw method + accountObj.withdraw(amt) + # Printing updated balance + print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n") + else: + print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n") + print("\nPlease make a deposit."); + + # Deposit + elif selection == 3: + # Reading amount + amt = float(input("\nEnter amount to deposit: ")) + ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ") + + if ver_deposit == "Yes": + # Calling deposit method + accountObj.deposit(amt); + # Printing updated balance + print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n") + else: + break + + elif selection == 4: + print("nTransaction is now complete.") + print("Transaction number: ", random.randint(10000, 1000000)) + print("Current Interest Rate: ", accountObj.annualInterestRate) + print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12) + print("Thanks for choosing us as your bank") + exit() + + # Any other choice + else: + print("nThat's an invalid choice.") + +# Main function +main() \ No newline at end of file diff --git a/Beginner_Level_Python_programs/Floyd's_Triangle.py b/Beginner_Level_Python_programs/Floyd's_Triangle.py new file mode 100644 index 0000000..d1947dc --- /dev/null +++ b/Beginner_Level_Python_programs/Floyd's_Triangle.py @@ -0,0 +1,11 @@ +# Python Program to Print Floyd's Triangle + +rows = int(input("Please Enter the total Number of Rows : ")) +number = 1 + +print("Floyd's Triangle") +for i in range(1, rows + 1): + for j in range(1, i + 1): + print(number, end = ' ') + number = number + 1 + print() \ No newline at end of file diff --git a/Beginner_Level_Python_programs/Leap_year.py b/Beginner_Level_Python_programs/Leap_year.py new file mode 100644 index 0000000..493555b --- /dev/null +++ b/Beginner_Level_Python_programs/Leap_year.py @@ -0,0 +1,17 @@ +# Python program to check if year is a leap year or not + +year = 2000 + +# To get year (integer input) from the user +# year = int(input("Enter a year: ")) + +if (year % 4) == 0: + if (year % 100) == 0: + if (year % 400) == 0: + print("{0} is a leap year".format(year)) + else: + print("{0} is not a leap year".format(year)) + else: + print("{0} is a leap year".format(year)) +else: + print("{0} is not a leap year".format(year)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/Matrix_transpose.py b/Beginner_Level_Python_programs/Matrix_transpose.py new file mode 100644 index 0000000..6c5ad7b --- /dev/null +++ b/Beginner_Level_Python_programs/Matrix_transpose.py @@ -0,0 +1,17 @@ +# Program to transpose a matrix using a nested loop + +X = [[12,7], + [4 ,5], + [3 ,8]] + +result = [[0,0,0], + [0,0,0]] + +# iterate through rows +for i in range(len(X)): + # iterate through columns + for j in range(len(X[0])): + result[j][i] = X[i][j] + +for r in result: + print(r) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/MergeMails.py b/Beginner_Level_Python_programs/MergeMails.py new file mode 100644 index 0000000..396be03 --- /dev/null +++ b/Beginner_Level_Python_programs/MergeMails.py @@ -0,0 +1,20 @@ +# Python program to mail merger +# Names are in the file names.txt +# Body of the mail is in body.txt + +# open names.txt for reading +with open("names.txt", 'r', encoding='utf-8') as names_file: + + # open body.txt for reading + with open("body.txt", 'r', encoding='utf-8') as body_file: + + # read entire content of the body + body = body_file.read() + + # iterate over names + for name in names_file: + mail = "Hello " + name.strip() + "\n" + body + + # write the mails to individual files + with open(name.strip()+".txt", 'w', encoding='utf-8') as mail_file: + mail_file.write(mail) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/Temperature_conversion.py b/Beginner_Level_Python_programs/Temperature_conversion.py new file mode 100644 index 0000000..e7897f9 --- /dev/null +++ b/Beginner_Level_Python_programs/Temperature_conversion.py @@ -0,0 +1,8 @@ +# Python Program to convert temperature in celsius to fahrenheit + +# change this value for a different result +celsius = 37.5 + +# calculate fahrenheit +fahrenheit = (celsius * 1.8) + 32 +print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/To_find_ASCII.py b/Beginner_Level_Python_programs/To_find_ASCII.py new file mode 100644 index 0000000..dc18665 --- /dev/null +++ b/Beginner_Level_Python_programs/To_find_ASCII.py @@ -0,0 +1,4 @@ +# Program to find the ASCII value of the given character + +c = 'p' +print("The ASCII value of '" + c + "' is", ord(c)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/To_find_GCD.py b/Beginner_Level_Python_programs/To_find_GCD.py new file mode 100644 index 0000000..0b8b731 --- /dev/null +++ b/Beginner_Level_Python_programs/To_find_GCD.py @@ -0,0 +1,19 @@ +# Python program to find H.C.F of two numbers + +# define a function +def compute_hcf(x, y): + +# choose the smaller number + if x > y: + smaller = y + else: + smaller = x + for i in range(1, smaller+1): + if((x % i == 0) and (y % i == 0)): + hcf = i + return hcf + +num1 = 54 +num2 = 24 + +print("The H.C.F. is", compute_hcf(num1, num2)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/area_of_circle.py b/Beginner_Level_Python_programs/area_of_circle.py new file mode 100644 index 0000000..0ea4625 --- /dev/null +++ b/Beginner_Level_Python_programs/area_of_circle.py @@ -0,0 +1,10 @@ + +#Area = pi * r2 +#where r is radius of circle + +def findArea(r): + PI = 3.142 + return PI * (r*r) + +num = int(input("Enter radius: ")) +print("Area is %.6f" % findArea(num)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/armstrong_number.py b/Beginner_Level_Python_programs/armstrong_number.py new file mode 100644 index 0000000..59bb720 --- /dev/null +++ b/Beginner_Level_Python_programs/armstrong_number.py @@ -0,0 +1,15 @@ +num = int(input("Enter a number: ")) + +sum = 0 + +temp = num +while temp > 0: + digit = temp % 10 + sum += digit ** 3 + temp //= 10 + + +if num == sum: + print(num,"is an Armstrong number") +else: + print(num,"is not an Armstrong number") \ No newline at end of file diff --git a/Beginner_Level_Python_programs/bitcoin_mining.py b/Beginner_Level_Python_programs/bitcoin_mining.py new file mode 100644 index 0000000..d289b0c --- /dev/null +++ b/Beginner_Level_Python_programs/bitcoin_mining.py @@ -0,0 +1,30 @@ +from hashlib import sha256 +MAX_NONCE = 100000000000 + +def SHA256(text): + return sha256(text.encode("ascii")).hexdigest() + +def mine(block_number, transactions, previous_hash, prefix_zeros): + prefix_str = '0'*prefix_zeros + for nonce in range(MAX_NONCE): + text = str(block_number) + transactions + previous_hash + str(nonce) + new_hash = SHA256(text) + if new_hash.startswith(prefix_str): + print(f"Yay! Successfully mined bitcoins with nonce value:{nonce}") + return new_hash + + raise BaseException(f"Couldn't find correct has after trying {MAX_NONCE} times") + +if __name__=='__main__': + transactions=''' + Dhaval->Bhavin->20, + Mando->Cara->45 + ''' + difficulty=4 # try changing this to higher number and you will see it will take more time for mining as difficulty increases + import time + start = time.time() + print("start mining") + new_hash = mine(5,transactions,'0000000xa036944e29568d0cff17edbe038f81208fecf9a66be9a2b8321c6ec7', difficulty) + total_time = str((time.time() - start)) + print(f"end mining. Mining took: {total_time} seconds") + print(new_hash) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/compound_interest.py b/Beginner_Level_Python_programs/compound_interest.py new file mode 100644 index 0000000..e96c683 --- /dev/null +++ b/Beginner_Level_Python_programs/compound_interest.py @@ -0,0 +1,11 @@ +def compound_interest(principle, rate, time): + + # Calculates compound interest + Amount = principle * (pow((1 + rate / 100), time)) + CI = Amount - principle + print('The principal is', principle) + print('The time period is', rate) + print('The rate of interest is',time) + print("Compound interest is", CI) + +compound_interest(10000, 10.25, 5) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/decimal_conversion.py b/Beginner_Level_Python_programs/decimal_conversion.py new file mode 100644 index 0000000..4995175 --- /dev/null +++ b/Beginner_Level_Python_programs/decimal_conversion.py @@ -0,0 +1,7 @@ +# Python program to convert decimal into other number systems +dec = 344 + +print("The decimal value of", dec, "is:") +print(bin(dec), "in binary.") +print(oct(dec), "in octal.") +print(hex(dec), "in hexadecimal.") \ No newline at end of file diff --git a/Beginner_Level_Python_programs/factorial.py b/Beginner_Level_Python_programs/factorial.py new file mode 100644 index 0000000..e1cb039 --- /dev/null +++ b/Beginner_Level_Python_programs/factorial.py @@ -0,0 +1,8 @@ +def factorial(n): + + return 1 if (n==1 or n==0) else n * factorial(n - 1) + + +num=input("Please enter number to calculate factorial:") + +print ("Factorial of",num,"is",factorial(int(num))) diff --git a/Beginner_Level_Python_programs/fibonacci_sequence.py b/Beginner_Level_Python_programs/fibonacci_sequence.py new file mode 100644 index 0000000..e448a53 --- /dev/null +++ b/Beginner_Level_Python_programs/fibonacci_sequence.py @@ -0,0 +1,33 @@ +#Fibonacci sequence starts with 0 and 1 as the first numbers and the consequetive numbers are calculated by adding up the two numbers before them +#0, 1, 1, 2, 3, 5, 8, 13 ... + +# Function to claculate list of fibonacci numbers +def fibonacci_calc(num): + result = list() + count = 0 + # Invalid input + if num <= 0: + print("Please enter a positive integer (input>0)") + return result + # Input 1 + elif num == 1: + result.append(0) + return result + else: + #starting values + n1, n2 = 0, 1 + while count < num: + result.append(n1) + nth = n1 + n2 + n1 = n2 + n2 = nth + count += 1 + return result + + +if __name__ == "__main__": + fibo_list = list() + n = int(input("Please enter the sequence number: ")) + fibo_list = fibonacci_calc(n) + for i in fibo_list: + print(i) diff --git a/Beginner_Level_Python_programs/find_resolution_of_image.py b/Beginner_Level_Python_programs/find_resolution_of_image.py new file mode 100644 index 0000000..c4d89e2 --- /dev/null +++ b/Beginner_Level_Python_programs/find_resolution_of_image.py @@ -0,0 +1,24 @@ +def jpeg_res(filename): + """"This function prints the resolution of the jpeg image file passed into it""" + + # open image for reading in binary mode + with open(filename,'rb') as img_file: + + # height of image (in 2 bytes) is at 164th position + img_file.seek(163) + + # read the 2 bytes + a = img_file.read(2) + + # calculate height + height = (a[0] << 8) + a[1] + + # next 2 bytes is width + a = img_file.read(2) + + # calculate width + width = (a[0] << 8) + a[1] + + print("The resolution of the image is",width,"x",height) + +jpeg_res("img1.jpg") \ No newline at end of file diff --git a/Beginner_Level_Python_programs/generate_random.py b/Beginner_Level_Python_programs/generate_random.py new file mode 100644 index 0000000..341f612 --- /dev/null +++ b/Beginner_Level_Python_programs/generate_random.py @@ -0,0 +1,6 @@ +# Program to generate a random number between 0 and 9 + +# importing the random module +import random + +print(random.randint(0,9)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/kilometers_to_miles.py b/Beginner_Level_Python_programs/kilometers_to_miles.py new file mode 100644 index 0000000..b839641 --- /dev/null +++ b/Beginner_Level_Python_programs/kilometers_to_miles.py @@ -0,0 +1,9 @@ +# Taking kilometers input from the user +kilometers = float(input("Enter value in kilometers: ")) + +# conversion factor +conv_fac = 0.621371 + +# calculate miles +miles = kilometers * conv_fac +print('%0.2f kilometers is equal to %0.2f miles' %(kilometers,miles)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/multiplication_table.py b/Beginner_Level_Python_programs/multiplication_table.py new file mode 100644 index 0000000..434e31b --- /dev/null +++ b/Beginner_Level_Python_programs/multiplication_table.py @@ -0,0 +1,10 @@ +# Multiplication table (from 1 to 10) in Python + +num = 12 + +# To take input from the user +# num = int(input("Display multiplication table of? ")) + +# Iterate 10 times from i = 1 to 10 +for i in range(1, 11): + print(num, 'x', i, '=', num*i) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/multiply_two_matrix.py b/Beginner_Level_Python_programs/multiply_two_matrix.py new file mode 100644 index 0000000..d0a0cf2 --- /dev/null +++ b/Beginner_Level_Python_programs/multiply_two_matrix.py @@ -0,0 +1,25 @@ +# Program to multiply two matrices using nested loops + +# 3x3 matrix +X = [[12,7,3], + [4 ,5,6], + [7 ,8,9]] +# 3x4 matrix +Y = [[5,8,1,2], + [6,7,3,0], + [4,5,9,1]] +# result is 3x4 +result = [[0,0,0,0], + [0,0,0,0], + [0,0,0,0]] + +# iterate through rows of X +for i in range(len(X)): + # iterate through columns of Y + for j in range(len(Y[0])): + # iterate through rows of Y + for k in range(len(Y)): + result[i][j] += X[i][k] * Y[k][j] + +for r in result: + print(r) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/prime_number.py b/Beginner_Level_Python_programs/prime_number.py new file mode 100644 index 0000000..3401432 --- /dev/null +++ b/Beginner_Level_Python_programs/prime_number.py @@ -0,0 +1,17 @@ +# Program to check if a number is prime or not + +num = int(input("Enter a number: ")) + + +if num > 1: + + for i in range(2,num): + if (num % i) == 0: + print(num,"is not a prime number") + print(i,"times",num//i,"is",num) + break + else: + print(num,"is a prime number") + +else: + print(num,"is not a prime number") \ No newline at end of file diff --git a/Beginner_Level_Python_programs/quadratic_root.py b/Beginner_Level_Python_programs/quadratic_root.py new file mode 100644 index 0000000..13652d3 --- /dev/null +++ b/Beginner_Level_Python_programs/quadratic_root.py @@ -0,0 +1,17 @@ +# Solve the quadratic equation ax**2 + bx + c = 0 + +# import complex math module +import cmath + +a = 1 +b = 5 +c = 6 + +# calculate the discriminant +d = (b**2) - (4*a*c) + +# find two solutions +sol1 = (-b-cmath.sqrt(d))/(2*a) +sol2 = (-b+cmath.sqrt(d))/(2*a) + +print('The solution are {0} and {1}'.format(sol1,sol2)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/remove_punctuation.py b/Beginner_Level_Python_programs/remove_punctuation.py new file mode 100644 index 0000000..51c8b93 --- /dev/null +++ b/Beginner_Level_Python_programs/remove_punctuation.py @@ -0,0 +1,16 @@ +# define punctuation +punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' + +my_str = "Hello!!!, he said ---and went." + +# To take input from the user +# my_str = input("Enter a string: ") + +# remove punctuation from the string +no_punct = "" +for char in my_str: + if char not in punctuations: + no_punct = no_punct + char + +# display the unpunctuated string +print(no_punct) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/shuffle_cards.py b/Beginner_Level_Python_programs/shuffle_cards.py new file mode 100644 index 0000000..74d3421 --- /dev/null +++ b/Beginner_Level_Python_programs/shuffle_cards.py @@ -0,0 +1,15 @@ +# Python program to shuffle a deck of card + +# importing modules +import itertools, random + +# make a deck of cards +deck = list(itertools.product(range(1,14),['Spade','Heart','Diamond','Club'])) + +# shuffle the cards +random.shuffle(deck) + +# draw five cards +print("You got:") +for i in range(5): + print(deck[i][0], "of", deck[i][1]) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/simple_calculator.py b/Beginner_Level_Python_programs/simple_calculator.py new file mode 100644 index 0000000..6a9451c --- /dev/null +++ b/Beginner_Level_Python_programs/simple_calculator.py @@ -0,0 +1,48 @@ +# Program make a simple calculator + +# This function adds two numbers +def add(x, y): + return x + y + +# This function subtracts two numbers +def subtract(x, y): + return x - y + +# This function multiplies two numbers +def multiply(x, y): + return x * y + +# This function divides two numbers +def divide(x, y): + return x / y + + +print("Select operation.") +print("1.Add") +print("2.Subtract") +print("3.Multiply") +print("4.Divide") + +while True: + # Take input from the user + choice = input("Enter choice(1/2/3/4): ") + + # Check if choice is one of the four options + if choice in ('1', '2', '3', '4'): + num1 = float(input("Enter first number: ")) + num2 = float(input("Enter second number: ")) + + if choice == '1': + print(num1, "+", num2, "=", add(num1, num2)) + + elif choice == '2': + print(num1, "-", num2, "=", subtract(num1, num2)) + + elif choice == '3': + print(num1, "*", num2, "=", multiply(num1, num2)) + + elif choice == '4': + print(num1, "/", num2, "=", divide(num1, num2)) + break + else: + print("Invalid Input") \ No newline at end of file diff --git a/Beginner_Level_Python_programs/simple_interest.py b/Beginner_Level_Python_programs/simple_interest.py new file mode 100644 index 0000000..a3f7a90 --- /dev/null +++ b/Beginner_Level_Python_programs/simple_interest.py @@ -0,0 +1,12 @@ +def simple_interest(principle,time,rate): + print('The principal is', principle) + print('The time period is', time) + print('The rate of interest is',rate) + + si = (principal * time * rate)/100 + + print('The Simple Interest is', si) + return si + + +simple_interest(8, 6, 8) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/sort_alphabet.py b/Beginner_Level_Python_programs/sort_alphabet.py new file mode 100644 index 0000000..0390526 --- /dev/null +++ b/Beginner_Level_Python_programs/sort_alphabet.py @@ -0,0 +1,8 @@ +my_str = input("Enter a string: ") +# breakdown the string into a list of words +words = my_str.split() +# sort the list +words.sort() +# display the sorted words +for word in words: + print(word) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/square_root.py b/Beginner_Level_Python_programs/square_root.py new file mode 100644 index 0000000..24091e4 --- /dev/null +++ b/Beginner_Level_Python_programs/square_root.py @@ -0,0 +1,10 @@ +# Python Program to calculate the square root + +# Note: change this value for a different result +num = 8 + +# To take the input from the user +#num = float(input('Enter a number: ')) + +num_sqrt = num ** 0.5 +print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/string_swap.py b/Beginner_Level_Python_programs/string_swap.py new file mode 100644 index 0000000..9927331 --- /dev/null +++ b/Beginner_Level_Python_programs/string_swap.py @@ -0,0 +1,8 @@ +s=input() +s=list(s) +res="" +for i in range(0,len(s)-1,2): + temp=s[i+1] + s[i+1]=s[i] + s[i]=temp +print(res.join(s)) diff --git a/Beginner_Level_Python_programs/sum_cosine_series.py b/Beginner_Level_Python_programs/sum_cosine_series.py new file mode 100644 index 0000000..1bc87ae --- /dev/null +++ b/Beginner_Level_Python_programs/sum_cosine_series.py @@ -0,0 +1,13 @@ +import math +def cosine(x,n): + cosx = 1 + sign = -1 + for i in range(2, n, 2): + pi=22/7 + y=x*(pi/180) + cosx = cosx + (sign*(y**i))/math.factorial(i) + sign = -sign + return cosx +x=int(input("Enter the value of x in degrees:")) +n=int(input("Enter the number of terms:")) +print(round(cosine(x,n),2)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/sum_sine_series.py b/Beginner_Level_Python_programs/sum_sine_series.py new file mode 100644 index 0000000..09695e2 --- /dev/null +++ b/Beginner_Level_Python_programs/sum_sine_series.py @@ -0,0 +1,12 @@ +import math +def sin(x,n): + sine = 0 + for i in range(n): + sign = (-1)**i + pi=22/7 + y=x*(pi/180) + sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign + return sine +x=int(input("Enter the value of x in degrees:")) +n=int(input("Enter the number of terms:")) +print(round(sin(x,n),2)) \ No newline at end of file diff --git a/Beginner_Level_Python_programs/translator.py b/Beginner_Level_Python_programs/translator.py new file mode 100644 index 0000000..f50bc5d --- /dev/null +++ b/Beginner_Level_Python_programs/translator.py @@ -0,0 +1,5 @@ +## don't forget to install - pip install translate +from translate import Translator +translator= Translator(to_lang="hi") +translation = translator.translate("Good Morning!") +print(translation) diff --git a/README.md b/README.md index 65d0120..0c55822 100644 --- a/README.md +++ b/README.md @@ -6,15 +6,21 @@ src:-https://dotnettutorials.net/lesson/tuples-in-python/ -## File Modes in Python🐍 -![file2](https://user-images.githubusercontent.com/67586773/104689438-84028c80-5728-11eb-97cf-7cf8882c157c.png) - - -src:- http://net-informations.com/python/file/default.htm ## if-else flow chart ![ifelse](https://user-images.githubusercontent.com/67586773/104689765-1efb6680-5729-11eb-8868-05db14dba8af.png) src:- https://www.educba.com/if-else-in-python/ + +## while-loop flow chart + +![flow-chart-while-loop](https://user-images.githubusercontent.com/67586773/105038967-fe634180-5a85-11eb-8f2f-87be0ff80433.jpg) + + +## for-loop flow chart + +![forLoop](https://user-images.githubusercontent.com/67586773/105038972-ff946e80-5a85-11eb-8d3d-1e50a1eb4636.jpg) + +More updating soon..!