Skip to main content

Posts

Showing posts with the label Python Scope

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