Python

BASIC:

* Variables : **name ='ada loverace'**
	+ Methods with printing **print(name.title())'**
	+ Concatenating print(" Hello, " + full\_name.title() + " !" )
	+ Tabs, new lines print(" \n" + "This is new line char" + "\t" + "This is tab character"
		- Stripping whitespace right: favourite.rstrip(), left : lstrip, strip
	+ Printing strings: print( **str**(variable))
	+ **inputing**: message = input( "Tell me something" ) , print(message)
	+ **numerical input-**  age = input( "How old are you?" ) print(str(age))
		- **WHILE LOOP**
			* while loop: while current\_number <=5: print(current\_number) current\_number +=1
			* using flag with while loop : active= True , while active: if message == 'quit': active = False
			* break, while True: if x>5: break
			* continue- omit some part of loop while number>10: number +=1 if number % == 2: continue

Data structures:

* **LIST** - **collection of items in a particular order**
	+ basic
		- **bicycles = [ 'trek', 'giant' , 'red', 'specialized']**
		- **accessing** is through index, bicycles[0], bicycles[1], last item - bicycles[-1]
		- we can using elements through index with methods, bicycles[0].title()
		- **replacing elements** bicycles[0]= 'ducati'
		- adding to the end of the list **motorcycles.append('ducati')**
		- **inserting** on 2 place on a list , **motorcycles.insert(2, 'ducati')**
		- **removing** del motorcycles[0]
		- **popping motorcycles.pop() -** by default last item, but we can motorcycles.pop(0) - first element
		- **removing by item** - motorcycles.remove('ducati')
		- **sorting** - cars.sort() , reverse order cars.sort(reverse=True), temporarily sorting sorted(cars)
		- **changing to reverse order** - cars.reverse()
		- **lenght of the list** - len(cars) , printing will be print( "Lenght of the list is: " + str(len(cars))"
	+ **Looping through list** : for magicians in magician: print(magician.title())
	+ **numerical list:** for value in range(1,5): print(value)
	+ **numbers** = list(range(1,6))
	+ **even\_numbers**= list(range(2,11,2) , odd\_numbers=list(range(1,11,2))
	+ **methods**: min(even\_numbers) , max(even\_numbers), sum(odd\_numbers)
	+ **list comprehensions :** squares= [ value \*\*2 for value in range(1,11)]
	+ **slicing the list**: print(players[0:3]) - first three elements, or [:3]
	+ **looping through slice** , for player in players[:3]:
	+ **copying the list** friends\_food= my\_foods[:]
	+ **if condition** , for car in cars: if car =='bmw': , elif:, else:
	+ **numerical if** - if answer !=42:
	+ **checking if value is not in the list** : if user not in banned\_users:
	+ **checking if list is not empty :** if requested\_toppings:
	+ **using multiple lists -** for requested\_topping in requested\_toppings: if requested\_toppings in available\_toppings:
* **TUPLES -** List tat values canoot change , dimensions = (200,50) , print(dimensions[0])
	+ looping through tuple; for dimension in dimensions:
	+ we can only redefine dimensions=(400,1000)
* **DICTIONARIES: key-value**
	+ alien\_0= {'color': 'green', 'points': 5}
	+ **accesing** = print(alien\_0['color'])
	+ **adding new keys with values**: alien\_0['x\_position'] = 0
	+ **removing ke**y - del alien\_0['points']
	+ **looping through keys and values;** for key,value in alien\_0.items():
	+ **looping through only keys in orde**r: for key in sorted(alien\_0.keys()):
	+ **looping through all values for values in** alien\_0.values():
	+ **list of dictionaries:** alien\_0 = { 'color:'green'} , alien\_1= { 'color': 'red'} , aliens=[alien\_0,alien\_1] for alien in aliens:
	+ **a list in dictionary** : pizza = { 'crust': 'thick, 'toppings': ['mushrooms', 'extra chesse'] } , for topping in pizza['toppings']:
	+ **a dictionary in dictionary:**  users = { 'ainstein': { 'fist': albert', 'last': 'einstein'} , 'mcurie': { 'first': 'marie' , 'last': 'curie', } } for username, user\_info in users.items(): print(username)
* **FUNCTION** - **blocks of code that are designed to do one specific job**
	+ **defining function** def greet\_user(parameter): , greet\_user('argument')
	+ **positional argumen**t- def describe\_pet(animal\_type,pet\_name) describe\_pet('harry','hamster')
	+ **key-word argument** describe\_pet(animal\_type='hamster', pet\_name='harry')
	+ **default values** - def describe\_pet(pet,name,animal\_type='dog')
	+ **optional\_argument** - get formatted\_name(first\_name,last\_name,middle\_name=' ')
	+ **preventing a function from modyfying a list** - print\_models(unprinted\_designs[ : ],completed\_models)
	+ **passing an arbitary number of arguments**- def make\_pizza(,size,\*toppings) - creates a tuple, must be placet last in the function definition
	+ **passing a arbitary keyword arguments** - def build\_profile(first,last,\*\*user\_info): profile{} profile['first\_name'] = first profile['last\_name']= last for key,value in user\_info.items(): profile[key] = value -- creates dictionary
	+ **importing modules** from other python program - import pizza
	+ **importing only some function** - from pizza import make\_pizza
	+ **giving a alias** - from pizza import make\_pizza as mp, mp(16,'pepperoni')
	+ **importing all functions** - from pizza import \*

* '***Class'* -** to create objects on class. When you write a class, you define the general behaviour that whole category of object can have.
	+ class Cat:
	   def \_\_init\_\_(self, name, age): ## main function, the self is requried at first place
	          self.name = name
	           self.age = age
	  def sit(self):
	           print(self.name.title() + " is now sitting.")
	  def roll\_over(self):
	           print(self.name.title() + " rolled over!")
	+ **making instance** - my\_cat=Cat('Kocur',6)

​                                     print("My Cat name is " + my\_cat.title() + ".")

                                     print("My cat is + str(my\_cat.age) + " years old")

* **calling the methods -** my\_cat.sit() , my\_cat.roll\_over()
* **default value for attribute -** class Motor():

      def \_\_init\_\_(self, make, model, year):
           """Initialize attributes to describe a car."""
           self.make = make
           self.model = model
           self.year = year
          **self.odometer\_reading = 0**

           """Print a statement showing the car's mileage."""
           print("This motor has " + str(self.odometer\_reading) + " miles on it.")

   my\_new\_motor = Car('Suzuki', 'Rs', 2016)
   print(my\_new\_motor.get\_descriptive\_name())
   my\_new\_motor.read\_odometer()
* **modyfying attribute**

* + ​**directly** - my\_new\_motor.odometer\_reading = 23
	+ **through method** - def update\_odometer(self,mileage): self.odometer= mileage , my\_new\_motor.update\_odometer(23)
* **incrementing attribute through method**-  def inc\_odometer(self,miles): self.odometer\_reading +=miles
* **Inheritance  -**

​class ElectricMotor(Motor):
       """Represent aspects of a car, specific to electric vehicles."""
   def \_\_init\_\_(self, make, model, year):
           """Initialize attributes of the parent class."""
         super().\_\_init\_\_(make, model, year)

 my\_motor= ElectricMotor('tesla', 'model q', 2016)
   print(my\_motor.get\_descriptive\_name())​

* ​**Classes as attributes**

           "
           self.battery\_size = battery\_size

  def describe\_battery(self):
           """Print a statement describing the battery size."""
           print("This motor has a " + str(self.battery\_size) + "-kWh battery.")

​class ElectricMotor(Motor):
       """Represent aspects of a car, specific to electric vehicles."""    def \_\_init\_\_(self, make, model, year):            """Initialize attributes of the parent class."""          super().\_\_init\_\_(make, model, year)

**self.battery= Battery()**
 my\_motor= ElectricMotor('tesla', 'model q', 2016)    print(my\_motor.get\_descriptive\_name()

**my\_motor.battery.describe\_battery()**

* Importing classes **-** from motor import Motor
* ====**Importing entire module -**import car====
* **FILES**
	+ **​reading line by line -**

​filename = 'digits.txt' with open(filename) as file\_object:    for line in file\_object:           print(line)

* **Stores values in the list**

filename = 'pi\_digits.txt'
   with open(filename) as file\_object: ➊     lines = file\_object.readlines()
➋ for line in lines:        print(line.rstrip())

* '***writing to file**  - '*You can open a file inread mode ('r'), write mode ('w'), append mode ('a'), or a mode that allows you to read and write to the file ('r+')

 with open(filename, 'w') as file\_object:
    file\_object.write("I love programming.")

* ====Exception - ====

1. ​try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
2. print("Give me two numbers, and I'll divide them.")
   print("Enter 'q' to quit.")

   while True:
       first\_number = input("\nFirst number: ")
       if first\_number == 'q':
           break
       second\_number = input("Second number: ")
    try:
           answer = int(first\_number) / int(second\_number)
 except ZeroDivisionError:
           print("You can't divide by 0!")
   else:
           print(answer)
3. filename = 'alice.txt'

        contents = f\_obj.read()
except FileNotFoundError:
    msg = "Sorry, the file " + filename + " does not exist."
    print(msg)
4. def count\_words(filename):
       """Count the approximate number of words in a file."""
       try:
           --snip--
       except FileNotFoundError:
          pass
       else:

* **JSON**

* + **​dumpling  -**

​import json

​   numbers = [2, 3, 5, 7, 11, 13]

   filename = 'numbers.json'
   with open(filename, 'w') as f\_obj:
   json.dump(numbers, f\_obj)

* **reading**

import json

filename = 'username.json'

               with open(filename) as f\_obj:

username = json.load(f\_obj)

print("Welcome back, " + username + "!")

* ::              import json

   def get\_stored\_username():
   """Get stored username if available."""
       filename = 'username.json'
               username = json.load(f\_obj)
       except FileNotFoundError:
           return None
       else:
           return username
   def greet\_user():
       """Greet the user by name."""
       username = get\_stored\_username()
      if username:
           print("Welcome back, " + username + "!")
       else:
           username = input("What is your name? ")
           filename = 'username.json'
           with open(filename, 'w') as f\_obj:
               json.dump(username, f\_obj)
               print("We'll remember you when you come back, " + username + "!")

   greet\_user()