Skip to main content

Posts

Showing posts with the label Python Function

PYTHON STRING FORMATTING

S TRING FORMATTING quantity = 3 itemno = 567 price = 49 myorder = "I want {} pieces of item number {} for {:.2f} dollars." print(myorder.format(quantity, itemno, price)) I want 3 pieces of item number 567 for 49.00 dollars. myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price)) I want 3 pieces of item number 567 for 49.00 dollars. age = 36 name = "John" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name)) His name is John. John is 36 years old. myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Ford", model = "Mustang")) I have a Ford, it is a Mustang.

PYTHON TRY...EXCEPT

T RY...EXCEPT try:   f = open("demofile.txt")   try:     f.write("Lorum Ipsum")   except:     print("Something went wrong when writing to the file")   finally:     f.close() except:   print("Something went wrong when opening the file") Something went wrong when writing to the file x = "hello" if not type(x) is int:   raise TypeError("Only integers are allowed") Traceback (most recent call last):   File "/usr/lib/python3.8/idlelib/run.py", line 559, in runcode     exec(code, self.locals)   File "/home/kartik/Downloads/tryCatch.py", line 16, in <module>     raise TypeError("Only integers are allowed") TypeError: Only integers are allowed

PYTHON JSON

J SON import json Some JSON: x = '{ "name":"John", "age":30, "city":"New York"}' Parse x: y = json.loads(x) The result is a Python dictionary: print(y["age"]) 30 A Python object (dict): x = {   "name": "John",   "age": 30,   "city": "New York" } Convert into JSON: y = json.dumps(x) The result is a JSON string: print(y) {"name": "John", "age": 30, "city": "New York"} x = {   "name": "John",   "age": 30,   "married": True,   "divorced": False,   "children": ("Ann","Billy"),   "pets": None,   "cars": [     {"model": "BMW 230", "mpg": 27.5},     {"model": "Ford Edge", "mpg": 24.1}   ] } print(

PYTHON MODULES

M ODULES mymodule.py def greeting(name): print("Hello, " + name) person1 = { "name": "John", "age": 36, "country": "Norway" } Modules.py import platform import mymodule as mx import mymodule from mymodule import person1 x = platform.system() print(x) #Built-in Modules Linux ['_WIN32_CLIENT_RELEASES', '_WIN32_SERVER_RELEASES', '__builtins__', '__cached__', '__copyright__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__version__', '_comparable_version', '_component_re', '_default_architecture', '_follow_symlinks', '_ironpython26_sys_version_parser', '_ironpython_sys_version_parser', '_java_getprop', '_libc_search', '_mac_ver_xml', '_node', '_norm_version', '_platform', '_pl

PYTHON SCOPE

S COPE def myfunc():   x = "Local Scope"   print(x) myfunc() Local Scope def myfunc():   x = "Function Inside Function"   def myinnerfunc():     print(x)   myinnerfunc() myfunc() Function Inside Function x = "Global Scope" def myfunc():   print(x) myfunc() Global Scope print(x) Global Scope x = "Global Scope" def myfunc():   x = "Local Scope"   print(x) myfunc() Local Scope print(x) Global Scope Global Keyword def myfunc():   global x   x = 300 myfunc() print(x) 300 x = 300 def myfunc():   global x   print(x)   x = 200   print(x) myfunc() 300 200 print(x) 200

PYTHON ITERATORS

I TERATORS mytuple = ("apple", "banana", "cherry") myit = iter(mytuple) print(next(myit)) apple print(next(myit)) banana print(next(myit)) cherry print(type(myit)) <class 'tuple_iterator'> The for loop actually creates an iterator object and executes the next() method for each loop. for x in mytuple:   print(x) apple banana cherry mystr = "banana" for x in mystr:   print(x) b a n a n a class MyNumbers:   def __iter__(self):     self.a = 1     return self   def __next__(self):     x = self.a     self.a += 1     return x myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) 1 print(next(myiter)) 2 print(next(myiter)) 3 print(next(myiter)) 4 print(next(myiter)) 5 To prevent the iteration to go on forever, we can use the StopIteration statement. class MyNumbers:   def __iter__(self):     self.a = 1     ret

PYTHON CLASS/OBJECT & INHERITANCE

C LASS/OBJECT & INHERITANCE class Person:   def __init__(self1, name, age):     self1.name = name     self1.age = age   def myfunc(self2):     print("Hello my name is " + self2.name) p1 = Person("Kartik", 36) print(p1.name) Kartik print(p1.age) 36 p1.myfunc() Hello my name is Kartik p1.age = 35 print(p1.age) 35 print(type(p1)) <class '__main__.Person'> print(type(p1.age)) <class 'int'> print(type(type(Person))) <class 'type'> del p1.age del p1 class Person:   pass Python Inheritance class Person:   def __init__(self, fname, lname):     self.firstname = fname     self.lastname = lname   def printname(self):      print(self.firstname, self.lastname) class Student(Person):   pass x = Student("Nagar", "Kartik") x.printname() Nagar Kartik class Person:   def __init__(self, fname, lname)

PYTHON LAMBDA

L AMBDA x = lambda a, b, c : a + b + c print(x(5, 6, 2)) 13 def myfunc(n):   return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(10)) 20 def myfunc(n):   return lambda a : a * n mydoubler = myfunc(2) mytripler = myfunc(3) print(mydoubler(11)) 22 print(mytripler(11)) 33

PYTHON FUNCTION

F UNCTION def my_function():   print("Hello from a function") my_function() Hello from a function def my_function(fname):   print(fname + " Refsnes") my_function("Emil") Emil Refsnes my_function("Tobias") Tobias Refsnes my_function("Linus") Linus Refsnes def my_function(fname, lname):   print(fname + " " + lname) my_function("Emil", "Refsnes") Emil Refsnes def my_function(*kids):    print("\nThe youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") The youngest child is Linus def my_function(child3, child2, child1):   print("\nThe youngest child is " + child1) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus") The youngest child is Emil def my_function(**kid):   print("\nHis last name is " + kid["lname"]) my_functi

PYTHON IF...ELSE, WHILE & FOR LOOPS

I F...ELSE, WHILE & FOR LOOPS If...else a = 200 b = 100 if b > a:   print("b is greater than a") elif a == b:   print("a and b are equal") else:   print("a is greater than b") a is greater than b if a > b: print("a is greater than b") a is greater than b print("A") if a > b else print("B") A a = 200 b = 201 print("A") if a > b else print("=") if a == b else print("B is greater than A") B is greater than A if a > 100:   print("A is above 100")   if b > 300:     print("B is above 300!")   else:     print("B is not above 300!") A is above 100 B is not above 300! if a > b:    pass Having an empty if statement like this, would raise an error without the pass statement While Loops i = 1 while i < 6:   print(i)   if i == 3:    break   i += 1 1 2 3 i = 0 wh

PYTHON DICTIONARIES

D ICTIONARIES thisdict = {   "brand": "Ford",   "electric": False,   "year": 1964,   "colors": ["red", "white", "blue"],   "type": {     "A1" : "21 Lac",     "A2" : "23Lac",     "A3" : "25Lac",   }   } print(thisdict) {'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue'], 'type': {'A1': '21 Lac', 'A2': '23Lac', 'A3': '25Lac'}} print(type(thisdict)) <class 'dict'> print(len(thisdict)) 5 Access,Add,Change Items car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.keys() print(x) before the change dict_keys(['brand', 'model'

PYTHON SETS

S ETS set1 = {"abc", 34, True, 40, "male"} print(set1) {True, 34, 40, 'abc', 'male'} thisset = set(("apple", "banana", "cherry","apple","Apple")) print(thisset) {'apple', 'cherry', 'banana', 'Apple'} print(len(thisset)) 4 print(type(thisset)) <class 'set'> Access Items for x in thisset:   print(x) apple cherry banana Apple print("banana" in thisset) True Add,Remove,Join Set Items thisset.add("orange") print(thisset) {'banana', 'apple', 'orange', 'Apple', 'cherry'} set1.update(thisset) print(set1) {True, 34, 'banana', 40, 'abc', 'apple', 'orange', 'Apple', 'male', 'cherry'} mylist = ["kiwi", "orange"] thisset.update(mylist) print(thisset) {'kiwi', 'banan

PYTHON TUPLES

T UPLES thistuple = ("apple",20, "cherry",True,False,3) Note the double round-brackets print(thistuple) ('apple', 20, 'cherry', True, False, 3) print(type(thistuple)) <class 'tuple'> thistuple = tuple(("apple",20, "cherry",True,False,3.0)) print(thistuple) ('apple', 20, 'cherry', True, False, 3.0) print(type(thistuple)) <class 'tuple'> Access Tuples print(thistuple[1]) 20 print(thistuple[-4]) cherry print(thistuple[-4:]) ('cherry', True, False, 3.0) print(thistuple[1:]) (20, 'cherry', True, False, 3.0) Add and Remove Tuples Values x = ("apple", "banana", "cherry") y = list(x) y[1] = "kiwi" x = tuple(y) print(x) ('apple', 'kiwi', 'cherry') thistuple = ("apple", "banana", "cherry") y = list(thistuple) y.append("orange"

PYTHON LISTS

L ISTS Access Lists Items list1 = ["abc", 34, True, 40, "male"] print(list1) ['abc', 34, True, 40, 'male'] print(list1[-1],list1[0]) male abc print(list1[-3:],list1[3:]) [True, 40, 'male'] [40, 'male'] print(list1[:-3],list1[:3]) ['abc', 34] ['abc', 34, True] print(list1[-4:-1],list1[1:4]) [34, True, 40] [34, True, 40] if 34 in list1:   print("Yes, '34' is in the fruits list") Yes, '34' is in the fruits list Change Lists Items list1[1] = "def" print("List :",list1) List : ['abc', 'def', True, 40, 'male'] list1[1:3] = ["blackcurrant", "watermelon"] print("List :",list1) List : ['abc', 'blackcurrant', 'watermelon', 40, 'male'] list1[0:5] =["watermelon"] print(list1) ['watermelon'] Add Lists Items list1.appe

PYTHON OPERATORS

O PERATORS x = 27 y = 3 Python Assignment Operators print(x + y) 30 print(x - y) 24 print(x * y) 81 print(x / y) 9.0 print(x % y) 0 print(x ** y) 19683 print(x // y) 9 Python Arithmetic Operators x = 5 x <<= 3 print(x) 40 x >>= 2 print(x) 10 x |= 3 print(x) 11 x &= 3 print(x) 3 x **= 3 print(x) 27 x //= 3 print(x) 9 x %= 3 print(x) 0 x /= 3 print(x) 0.0 x *= 3 print(x) 0.0 x -= 3 print(x) -3.0 x += 3 print(x) 0.0 x = 5 print(x) 5 Python Comparison Operators x = 5 y = 3 print(x == y) False print(x != y) True print(x > y) True print(x < y) False print(x >= y) True print(x = y) False Python Logical Operators x = 5 print(x > 3 and x < 10) True print(x < 5 or x < 4) False print(not(x < 5 and x < 10)) True Python Identity Operator x = ["apple", "banana"]

PYTHON DATA TYPE

D ATA TYPE x = 5 y = 10 print(x + y) 15 x = "normal variable" print(x) normal variable def myfunc(): global x x = "Global variable" myfunc() print("After running fun " , x) After running fun Global variable fruits = ("apple", "banana", "cherry", "strawberry", "raspberry") a = (green, *yellow, red) = fruits print(type(a)," = ", a) <class 'tuple'> = ('apple', 'banana', 'cherry', 'strawberry', 'raspberry') print(type(green)," = ", green) <class 'str'> = apple print(type(yellow)," = ", yellow) <class 'list'> = ['banana', 'cherry', 'strawberry'] print(type(red)," = ", red) <class 'str'> = raspberry print(type(fruits)," = ", fruits) <class 'tuple'> = ('apple'