<jupyter_start><jupyter_text>Beginner's Python Cheat SheetThis is a good link on Github I (<NAME> @hmok) am practicing and sharing it on Google Colabhttps://ehmatthes.github.io/pcc/cheatsheets/README.htmlhttp://nostarchpress.com/pythoncrashcourseI have seen others have done similar things but not maybe all in one notebook.https://github.com/sujee81/Python-Cheat-SheetCheck these 28 Jupyter Notebook Tips, Tricks, and Shortcuts:https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/Enjoy learning! Variables and StringsVariables are used to store values. A string is a series ofcharacters, surrounded by single or double quotes Hello World<jupyter_code>print('Hello World!')
print("Hello World!") # both are correct<jupyter_output><empty_output><jupyter_text>Hello world with a variable<jupyter_code>msg = "Hello world!"
print(msg)<jupyter_output><empty_output><jupyter_text>Concatenation (combining strings)<jupyter_code>first_name = 'albert'
last_name = 'einstein'
full_name = first_name + ' ' + last_name
print(full_name)<jupyter_output><empty_output><jupyter_text>ListsA list stores a series of items in a particular order. Youaccess items using an index, or within a loop.<jupyter_code># Make a list
bikes = ['trek', 'redline', 'giant']

# Get the first item in a list
first_bike = bikes[0]

# Get the last item in a list
last_bike = bikes[-1]

# Looping through a list
for bike in bikes:
    print(bike)
    
# Adding items to a list
bikes = []
bikes.append('trek')
bikes.append('redline')
bikes.append('giant')

# Making numerical lists
squares = []
for x in range(1,11):
    squares.append(x**2)
squares

# List cont.
#  List comprehensions
squares = [x**2 for x in range(1,11)]

#slicing a list
finishers = ['sam', 'bob', 'ada', 'bea']
first_two = finishers[0:2] #or first_two = finishers[:2] 

#  Copying a list
copy_of_bikes = bikes.copy() #or copy_of_bikes = bikes[:]

# Wanna learn more about *args and **kwargs see this below:
# https://www.geeksforgeeks.org/args-kwargs-python/<jupyter_output><empty_output><jupyter_text>TuplesTuples are similar to lists, but the items in a tuple cannot be modified<jupyter_code># making a tuple
dimensions = (1920, 1080)
squares = [x**2 for x in range(10)]
squares<jupyter_output><empty_output><jupyter_text>If statements If statements are used to test for particular conditions andrespond appropriately.<jupyter_code># Conditional tests
x == 42 # equals
x != 42 #not equal 
x > 42 #greater than 
x >= 42 #or equal to
x < 42 #less than 
x <= 42 #or equal to
x
# Conditional test with lists
'trek' in bikes
'surly' not in bikes

# Assigning boolean values
game_active = True
can_edit = False

# A simple if test
age=24
if age>=18:
    print('You can vote')

#     If-elif-else statements
ticket_price = 20
if age < 4:
 ticket_price = 0
elif age < 18:
 ticket_price = 10
else:
 ticket_price = 15<jupyter_output><empty_output><jupyter_text>Dictionaries Dictionaries store connections between pieces ofinformation. Each item in a dictionary is a key-value pair.<jupyter_code># A Simple dictionary (key, value paires) or items={key: value, ...}
alien = {'color': 'green', 'points': 5}

# Access a value
print("The alien's color is" + alien['color'])

# Addeing a new key-vale pair

alien['x_positon'] = 0
alien
# Loopoing through all key-value pairs

for key in alien:
    print(key)
  
fav_numbers = {'eric': 17, 'ever': 4}
for name, number in fav_numbers.items():
    print(name + ' loves ' + str(number))
    
#   Looping through all keys
for name in fav_numbers.keys():
    print(name + ' loves a number')
    
#   Looping through all values
for number in fav_numbers.values():
    print(str(number) + ' is a favorite')<jupyter_output>color
points
x_positon<jupyter_text>User inputYour programs can prompt the user for input. All input isstored as a string.<jupyter_code># Prompting for value
name = input('what is your name?')
print('Hello, ' + name + '!')

# Prompting for for numerical input
age = input('How old are you?')
age = int(age)

pi = input('what is  the value of pi?')
pi = float(pi)
print(pi)<jupyter_output><empty_output><jupyter_text>While loopsA while loop repeats a block of code as long as a certaincondition is true.<jupyter_code># A simple while loop
current_value = 1
while current_value <= 5:
    print(current_value)
    current_value +=1

  # Letting the user choose when to quit
msg = ''
while msg !='quit':
    msg = input('what is your message?')
    print(msg)<jupyter_output><empty_output><jupyter_text>FunctionsFunctions are named blocks of code, designed to do onespecific job. Information passed to a function is called anargument, and information received by a function is called aparameter<jupyter_code>#  A simplefunction
def greet_user():
    """Display a simple greeting"""
    print('Hello!')

greet_user()
greet_user.__doc__ # the comment above between """doc"""


# passing an argument
def greet_user(username):
    """Display a personlized greeting greeting"""
    print("Hello, " + username + "!")
    
greet_user('Jesse')

# Default values for parameters
def make_pizza(topping='bacon'):
    """Make a single-topping pizza."""
    print("Have a " + topping + " pizza!")
    
make_pizza()
make_pizza('pepperroni')

# Returning a value
def add_numbers(x,y):
    """Add two numbers and return the sum"""
    return x + y
  
sum = add_numbers(3,4)
print(sum)<jupyter_output>Have a bacon pizza!
Have a pepperroni pizza!
7<jupyter_text>ClassesA class defines the behavior of an object and the kind ofinformation an object can store. The information in a classis stored in attributes, and functions that belong to a classare called methods. A child class inherits the attributes andmethods from its parent class.<jupyter_code># Creating a dog class
class Dog():
  """Represent a dog"""
  
  def __init__(self, name):
      """Initialize dog object"""
      self.name = name
      
  def sit(self):
      """Simulate sitting"""
      print(self.name + " is sitting.")
      
#how to use Dog(name) e.g. Dog('Peso')
my_dog = Dog('Peso')    

print(my_dog.name + " is a great dog!")
my_dog.sit()

# Inheritance

class SARDog(Dog):
    """represent a search dog."""
  
    def __init__(self, name):
        """Initialize the sardog"""
        super().__init__(name)
        
    def search(self):
        """Simulate searching."""
        print(self.name + " is searching")
        
my_dog = SARDog('Willie')

print(my_dog.name + "is a search dog.")
my_dog.sit()
my_dog.search()<jupyter_output>Willieis a search dog.
Willie is sitting.
Willie is searching<jupyter_text>Infinite SkillsIf you had inifite programing skills, what would you build?As you're learning to program, it's helpful to thinkabout the real-world projects you'd like to create. It'sa good habit to keep an "ideas" notebook that youcan refer to whenever you want to start a new project.If you haven't done so already, take a few minutesand describe three projects you'd like to create.  Working with filesYour programs can read from files and write to files. Filesare opened in read mode ('r') by default, but can also beopened in write mode ('w') and append mode ('a').<jupyter_code># Create a file txt file
fh = open('demo.txt','w')
for i in range(10):
    fh.write("this is the line no %d\n" % i)

fh.close()

# Reading a file and storing its lines

filename = 'demo.txt' #'sidedhartha.txt'

with open(filename) as file_object:
    lines = file_object.readlines()
    
for line in lines:
   print(line)
    
    
# Writing to a file
filename = 'journal.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programing.")
    
#Appending to a file
filename = 'journal.txt'
with open(filename, 'a') as file_object:
    file_object.write("\nI love making games")<jupyter_output><empty_output><jupyter_text>ExceptionsExceptions help you respond appropriately to errors thatare likely to occur. You place code that might cause anerror in the try block. Code that should run in response toan error goes in the except block. Code that should run onlyif the try block was successful goes in the else block.<jupyter_code>#Catching an exception
prompt = "How many tickets do you need? "
num_tickets = input(prompt)

try:
    num_tickets = int(num_tickets)
except ValueError:
    print("Please try again.")
else: 
    print("Your tickers are printing.")<jupyter_output><empty_output><jupyter_text>Zen of PythonSimple is better than complexIf you have a choice between a simple and a complexsolution, and both work, use the simple solution. Yourcode will be easier to maintain, and it will be easierfor you and others to build on that code later on.  what are lists?A list stores a series of items in a particular order.Lists allow you to store sets of information in oneplace, whether you have just a few items or millionsof items. Lists are one of Python's most powerfulfeatures readily accessible to new programmers, andthey tie together many important concepts inprogramming.Defining a listUse square brackets to define a list, and use commas toseparate individual items in the list. Use plural names forlists, to make your code easier to read.<jupyter_code>#making a list
users = ['val','bob','mia','ron','ned']<jupyter_output><empty_output><jupyter_text>Accessing elementsIndividual elements in a list are accessed according to theirposition, called the index. The index of the first element is0, the index of the second element is 1, and so forth.Negative indices refer to items at the end of the list. To geta particular element, write the name of the list and then theindex of the element in square brackets.<jupyter_code>#Getting gthe first element
first_element = users[0]
#Getting gthe second element
first_element = users[1]
#Getting gthe last element
first_element = users[-1]<jupyter_output><empty_output><jupyter_text>Modifying individual itemsOnce you have defined a list, you can change individual elements in the list (but not in tuple). you do this by referring to the index of the item you want to modify.<jupyter_code># Changing an element
users[0] = 'valerie'
users[-2] = 'ronald'<jupyter_output><empty_output><jupyter_text>Adding elementsYou can add elements to the endof a list, or you can insert them wherever you like in a list.<jupyter_code># Adding an element to the end of the list
users.append('Amy')

# Starting with an empty list (rememebr ctrl+? will do # haha good shortcut)

users = []
users.append('val')
users.append('bob')
users.append('mia')
users
# Inserting elements at a particualr position
users.insert(0, 'joe')
users.insert(3, 'bea')<jupyter_output><empty_output><jupyter_text>Removing elementsYou can remove elements by their position in a list. or by the value of the item. If you remove an item by its value, Python removes only the first item that has that value.<jupyter_code># Deleting an element by its position
del users[-1]
users.remove('bea') #users.remove('mia') will show ValueError<jupyter_output><empty_output><jupyter_text>Poping elementsIf you want towork with an element that you are removing from the list, you can 'pop' the elemetn. If you think of the list as a stack of items, pop() takes an item off the top of the stack. by default pop() returns the last element in the list, but you can also pop elements from any position in the list.<jupyter_code>#pop the last item from a list

most_recent_user = users.pop()
print(most_recent_user)

# pop the first item in a list
first_user = users.pop(0)
print(first_user)<jupyter_output><empty_output><jupyter_text>List LengthThe len() function returns the number of iterms in a list<jupyter_code># Find the length of a list
num_users = len(users)
print("We have " + str(num_users) + " users." )<jupyter_output><empty_output><jupyter_text>Sorting a listThe sort() method changes the order of a list permanently.The sorted() function returns a copy of the list, leaving theoriginal list unchanged. You can sort the items in a list inalphabetical order, or reverse alphabetical order. You canalso reverse the original order of the list. Keep in mind thatlowercase and uppercase letters may affect the sort order.<jupyter_code>#  Sorting a list permanetly
users.sort()
users.append('AHA')

# Sorting a list permanetly in reverse alphabetical order
users.sort(reverse=True)

# Sorting a list tempporarily

print(sorted(users))
print(sorted(users, reverse=True))

# Reversing the order of a list
users.reverse()<jupyter_output><empty_output><jupyter_text>Looping through a listLists can contain millions of items, so Python provides anefficient way to loop through all the items in a list. Whenyou set up a loop, Python pulls each item from the list oneat a time and stores it in a temporary variable, which youprovide a name for. This name should be the singularversion of the list name. The indented block of code makes up the body of theloop, where you can work with each individual item. Anylines that are not indented run after the loop is completed<jupyter_code>#  Printing all items in a list

for user in users:
    print(user)
    
# Printing a message for each item, and a seprate message afterwards

for user in users:
    print("Welcome, " + user + "!")
    
print("Welcome, we are glad to see you all")<jupyter_output><empty_output><jupyter_text>The range() functionYou can use the range() function to work with a set of numbers efficiently. The range() function starts at 0 by default, and stops one number below the number passed to it. You can use the list() function to efficiently generate a large list of numbers<jupyter_code>#  Printing the numbers 0 to 1000
for number in range(1001):
    print(number)
    
# Printing the number 1 to 1000
for number in range(1,1001):
    print(number)
    
# Making a list of numebrs from 1 to a millon
numbers = list(range(1,10000001))
len(numbers)<jupyter_output><empty_output><jupyter_text>Simple StatisticsThere are a number of simple statistics you can run on a list containing numerical data.<jupyter_code>#  finding the minimum value in a list

ages = [93, 99, 66, 17, 85, 1, 35, 82, 2, 77] 
youngetst  = min(ages)

# Finding the maximum value
oldest = max(ages)

# Finding the sum of all value
total_years = sum(ages)<jupyter_output><empty_output><jupyter_text>Slicing a listYou can work with any set of elements from a list. A portion of a list is called a slice. To slice a list start with the index of the first item you want, then add a colon and the index after the last item you want. Leave off the first index to start at the beginning of the list, and leave off the last index to slice through the end of the list.<jupyter_code>#  Getting the first three items
finishers = ['kai','abe','ada','gus','zoe']
first_three = finishers[:3]

#  Getting the middle three items
middle_three = finishers[1:4]

# Getting the last three items
last_three = finishers[-3:]<jupyter_output><empty_output><jupyter_text>Copying a listTo copy a list make a slice that starts at the first item and ends at the last item. If you try to copy a list without using this approach, whatever you do to the copied list will affect the original list as well<jupyter_code># Making a copy of a list
finishers = ['kai','abe','ada','gus','zoe']
copy_of_finishers = finishers.copy() #or copy_of_finishers = finishers[:]<jupyter_output><empty_output><jupyter_text>List comprehenstions You can use a loop to generate a list based on a range of numbers or on another list. This is a common operation, so Python offers a more efficient way to do it. List comprehensions may look complicated at first; if so, use the for loop approach until you're ready to start using comprehensions.     To write a comprehension, define an expression for the values you want to store in the list. Then write a for loop to generate input values needed to make the list.<jupyter_code>#  Using a loop to generate a list of square numbers
squares = []
for x in range(1,11):
    square = x**2
    squares.append(square)
    
squares
class Car():
    """A simple attempt to model a car"""
    
    def __init__(self, make, model, year):
        """Initialize car attributes."""
        self.make = make
        self.model = model
        self.year = year
        
 # Fuel capacity and level in gallons.         
        self.fuel_capacity = 15        
        self.fuel_level = 0
    
    def fill_tank(self):
      """Fill gas tank to capacity."""
      self.fuel_level = self.fuel_capacity
      print("Fuel tank is full.")
        
    def drive(self):
        """Simulate driving"""
        print("The car is moving")
        
    # Writing a method to update an attribute's value 
    def update_fuel_level(self, new_level):
      """Update the fuel level."""
      if new_level <= self.fuel_capacity:
        self.fuel_level = new_level     
      else:
        print("The tank can't hold that much!")   
        
#       Writing a method to increment an attribute's value
      def add_fuel(self, amount):
          """Add fuel to the tank."""
          if (self.fuel_level + amount <= self.fuel_capacity):
            self.fuel_level += amount 
            print("Added fuel.")    
          else:         
            print("The tank won't hold that much.")
      
        
my_car = Car('mazda', 'toyo', 2019)
my_car.fuel_capacity = 20

my_car.fuel_capacity


# Creating an object from a class 

my_car = Car('audi','a4', 2016)

# Accessing attribute values
print(my_car.make)
print(my_car.model)
print(my_car.year)

# Calling Methods
my_car.fill_tank()
my_car.drive()

# Creating multiple objects
my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)<jupyter_output>audi
a4
2016
Fuel tank is full.
The car is moving<jupyter_text>Modifying attributesYou can modify an attribute's value directly, or you can write methods that manage updating values more carefully<jupyter_code>#  Modifying an attribute directly

my_new_car = Car('audi', 'a4', 2016) 
my_new_car.fuel_level = 5



my_new_car.update_fuel_level(new_level=10)
my_new_car.fuel_level
def greet_users(names):
    """Print a simple greeting to everyone."""
    for name in names:
      msg = "Hello, " + name + "!"         
      print(msg) 
 
usernames = ['hannah', 'ty', 'margot'] 
greet_users(usernames)<jupyter_output><empty_output><jupyter_text>Namaing ConventionsIn Python class names are written in CamelCase and object names are written in lowercase with underscores. Modules that contain classes should still be named in lowercase with underscores.   Class inhertitanceIf the class you're writing is a specialized version of another class, you can use inheritance. When one class inherits from another, it automatically takes on all the attributes and methods of the parent class. The child class is free to introduce new attributes and methods, and override attributes and methods of the parent class.     To inherit from another class include the name of the parent class in parentheses when defining the new class.<jupyter_code># The __init__() method for a child class 

class ElectricCar(Car):
  """A simple model of an electric car.""" 
  def __init__(self, make, model, year):
    """Initialize an electric car."""
    super().__init__(make, model, year) 
    # Attributes specific to electric cars. 
      # Battery capacity in kWh.
    self.battery_size = 70     
      # Charge level in %.
      
    self.charge_level = 0 
    
    
ElectricCar.drive('ooo')

# Adding new methods to the child class
class ElectricCar(Car):
    """--snip---"""
    def charge(self):
      """Fully charge the vehicle"""
      self.charge_level = 100
      print("The vehicle is fully charged")

#       Using child methods and parent method

my_ecar = ElectricCar('tesla', 'model s', 2016)
my_ecar.charge()
my_ecar.drive()<jupyter_output><empty_output><jupyter_text>Finding your workflowThere are many ways to model real world objects and situations in code, and sometimes that variety can feel overwhelming. Pick an approach and try it – if your first attempt doesn't work, try a different approach.  Class inheritance (cont.)<jupyter_code># Overriding parent methods
class ElectricCar(Car):
    """snip"""
    def fill_tank(self):
      """Display an error message."""
      print("This car has no fuel tank!")
      
my_ecar = ElectricCar('tesla', 'model s', 2016)
my_ecar.fill_tank()<jupyter_output><empty_output><jupyter_text>Instances as attributesA class can have objects as attributes. This allows classes to work together to model complex situations.<jupyter_code># A Battery class

class Battery():
  """ A battery for an electric car."""
 
  def __ini__(self, size=70):
      """Initialize battery atributes."""
      #Capacity in kwh, charge level in %.
      self.size = size
      self.charge_level = 0
      
      
  def get_range(self):
      """Return the battery's range."""
      if self.size == 70:
        return 240
      elif self.size == 85:
        return 270

#       Using an instance as an attribute
class ElectricCar(Car):
  """snip"""
  
  def __ini__(self, make, model, year):
    """Initialize an electric car."""
    super().__ini__(make, model, year)
    
#     Atribute specific to electric cars.
    self.battery = Battery()
  
  def charge(self):
    """Fully charge the vehicle."""
    self.battery.cahrge_level = 100
    print("the vehicle is fully charged.")
    
    
my_ecar = ElectricCar('tesla', 'model x', 2016)  
my_ecar.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()<jupyter_output><empty_output><jupyter_text>Passing informaton to a functionInformation that's passed to a function is called an argument; information that's received by a function is called a parameter. Arguments are included in parentheses after the function's name, and parameters are listed in parentheses in the function's definition.<jupyter_code>#  Passing a single argument
def greet_user(username):
 """Display a simple greeting."""
 print("Hello, " + username + "!")

greet_user('jesse')
greet_user('diana')
greet_user('brandon')<jupyter_output>Hello, jesse!
Hello, diana!
Hello, brandon!<jupyter_text>Positional and Keyword argumentsThe two main kinds of arguments are positional andkeyword arguments. When you use positional argumentsPython matches the first argument in the function call withthe first parameter in the function definition, and so forth. With keyword arguments, you specify which parametereach argument should be assigned to in the function call.When you use keyword arguments, the order of thearguments doesn't matter.<jupyter_code># Using positional arguments
def describe_pet(animal, name):
 """Display information about a pet."""
 print("\nI have a " + animal + ".")
 print("Its name is " + name + ".")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

# Using keyword arguments
def describe_pet(animal, name):
 """Display information about a pet."""
 print("\nI have a " + animal + ".")
 print("Its name is " + name + ".")
describe_pet(animal='hamster', name='harry')
describe_pet(name='willie', animal='dog')<jupyter_output>I have a hamster.
Its name is harry.

I have a dog.
Its name is willie.<jupyter_text>Default ValuesYou can provide a default value for a parameter. Whenfunction calls omit this argument the default value will beused. Parameters with default values must be listed afterparameters without default values in the function's definitionso positional arguments can still work correctly<jupyter_code># Using a default value
def describe_pet(name, animal='dog'):
 """Display information about a pet."""
 print("\nI have a " + animal + ".")
 print("Its name is " + name + ".")
describe_pet('harry', 'hamster')
describe_pet('willie')

# Using None to make an argument optional
def describe_pet(animal, name=None):
  """Display information about a pet."""
  print("\nI have a " + animal + ".")
  if name:
    print("Its name is " + name + ".")

describe_pet('hamster', 'harry')
describe_pet('snake')<jupyter_output>I have a hamster.
Its name is harry.<jupyter_text>Return ValuesA function can return a value or a set of values. When afunction returns a value, the calling line must provide avariable in which to store the return value. A function stopsrunning when it reaches a return statement.<jupyter_code># Returning a single value
def get_full_name(first, last):
 """Return a neatly formatted full name."""
 full_name = first + ' ' + last
 return full_name.title(), full_name # str.title() make the first letter Capital

musician = get_full_name('jimi', 'hendrix')
print(musician)

# Returning a dictionary
def build_person(first, last):
 """Return a dictionary of information
 about a person.
 """
 person = {'first': first.title(), 'last': last}
 return person

# usage Example
musician = build_person('jimi', 'hendrix')
print(musician)


# Returning a dictionary with optional values
def build_person(first, last, age=None):
  """Return a dictionary of information about a person."""
  person = {'first': first, 'last': last}
  if age:
    person['age'] = age
   
  return person
  
musician = build_person('jimi', 'hendrix', 27)
print(musician)
musician = build_person('janis', 'joplin')
print(musician)
# musician[]<jupyter_output>{'first': 'jimi', 'last': 'hendrix', 'age': 27}
{'first': 'janis', 'last': 'joplin'}<jupyter_text>Visualization FunctionsTry running some of these examples on [PythonTutor](http://pythontutor.com/)This is  cool website to learn and visualize your code and get or give help. Let's try it...  Passing a list to a functionYou can pass a list as an argument to a function, and thefunction can work with the values in the list. Any changesthe function makes to the list will affect the original list. Youcan prevent a function from modifying a list by passing acopy of the list as an argument.<jupyter_code># Passing a list as an argument
def greet_users(names):
  """Print a simple greeting to everyone."""
  for name in names:
    msg = "Hello, " + name + "!"
    print(msg)
  
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

def greet_users(names):
  """pring a simpel greeting to all"""
  for name in names:
    print('Hello ' + name + "!")
    
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)<jupyter_output>Hello hannah!
Hello ty!
Hello margot!<jupyter_text>Allowing a function to modify a listThe following example sends a list of models to a function forprinting. The original list is emptied, and the second list is filled.<jupyter_code>def print_models(unprinted, printed):
  """3d print a set of models."""
  while unprinted:
    current_model = unprinted.pop()
    print("Printing " + current_model)
    printed.append(current_model)
    
# Store some unprinted designs,
# and print each of them.
unprinted = ['phone case', 'pendant', 'ring']
printed = []
print_models(unprinted, printed)
print("\nUnprinted:", unprinted)
print("Printed:", printed)<jupyter_output>Printing ring
Printing pendant
Printing phone case

Unprinted: []
Printed: ['ring', 'pendant', 'phone case']<jupyter_text>Preventing a function from modifying a listThe following example is the same as the previous one, except theoriginal list is unchanged after calling print_models().<jupyter_code>def print_models(unprinted, printed):
  """3d print a set of models."""
  while unprinted:
    current_model = unprinted.pop()
    print("Printing " + current_model)
    printed.append(current_model)
      
# Store some unprinted designs,
# and print each of them.
original = ['phone case', 'pendant', 'ring']
printed = []
print_models(original[:], printed)
print("\nOriginal:", original)
print("Printed:", printed)<jupyter_output><empty_output><jupyter_text>Passing a number of argumentsSometimes you won't know how many arguments afunction will need to accept. Python allows you to collect anarbitrary number of arguments into one parameter usingThe ''*'' operator. A parameter that accepts an arbitrary number ofarguments must come last in the function definition. The ** operator allows a parameter to collect an arbitrarynumber of keyword arguments<jupyter_code># Collecting an arbitrary number of arguments
def make_pizza(size, *toppings):
  """Make a pizza."""
  print("\nMaking a " + size + " pizza.")
  print("Toppings:")
  for topping in toppings:
    print("- " + topping)
    
# Make three pizzas with different toppings.
make_pizza('small', 'pepperoni')
make_pizza('large', 'bacon bits', 'pineapple')
make_pizza('medium', 'mushrooms', 'peppers',
 'onions', 'extra cheese')
# Collecting an arbitrary number of keyword arguments
def build_profile(first, last, **user_info):
  """Build a user's profile dictionary."""
  # Build a dict with the required keys.
  profile = {'first': first, 'last': last}
  # Add any other keys and values.
  for key, value in user_info.items():
    profile[key] = value
    return profile
  
# Create two users with different kinds
# of information.
user_0 = build_profile('albert', 'einstein',
 location='princeton')
user_1 = build_profile('marie', 'curie',
 location='paris', field='chemistry')
print(user_0)
print(user_1)<jupyter_output>{'first': 'albert', 'last': 'einstein', 'location': 'princeton'}
{'first': 'marie', 'last': 'curie', 'location': 'paris'}<jupyter_text>What is the best way to structur a functionAs you can see there are many ways to write and call afunction. When you're starting out, aim for something thatsimply works. As you gain experience you'll develop anunderstanding of the more subtle advantages of differentstructures such as positional and keyword arguments, andthe various approaches to importing functions. For now ifyour functions do what you need them to, you're doing well.  Module You can store your functions in a separate file called amodule, and then import the functions you need into the filecontaining your main program. This allows for cleanerprogram files. (Make sure your module is stored in thesame directory as your main program.)<jupyter_code># Storing a function in a module
#  File: pizza.py, one needs to create pizza.py from the following otherwise this piece would not work.
#  Simply open a blank txt editor like Notepad++ and copy the function below and save it as pizza.py
# then upload it here if you use google colab. 

# Also, the pizza.py needs to be in the same directory this code is being run.

# Storing a function in a module
# File: pizza.py
def make_pizza(size, *toppings):
  """Make a pizza."""
  print("\nMaking a " + size + " pizza.")
  print("Toppings:")
  for topping in toppings:
    print("- " + topping)
    
# Importing an entire module
# File: making_pizzas.py
# Every function in the module is available in the program file.
import pizza # this maynot work if we dont ahve this file pizza.py
pizza.make_pizza('medium', 'pepperoni')
pizza.make_pizza('small', 'bacon', 'pineapple')

# Importing a specific function
# Only the imported functions are available in the program file.
from pizza import make_pizza
make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')

# Giving a module an alias
import pizza as p
p.make_pizza('medium', 'pepperoni')
p.make_pizza('small', 'bacon', 'pineapple')

# Giving a function an alias
from pizza import make_pizza as mp
mp('medium', 'pepperoni')
mp('small', 'bacon', 'pineapple')


# Importing all functions from a module

# Don't do this, but recognize it when you see it in others' code. It
# can result in naming conflicts, which can cause errors.
from pizza import *
make_pizza('medium', 'pepperoni')
make_pizza('small', 'bacon', 'pineapple')<jupyter_output>Making a medium pizza.
Toppings:
- pepperoni

Making a small pizza.
Toppings:
- bacon
- pineapple

Making a medium pizza.
Toppings:
- pepperoni

Making a small pizza.
Toppings:
- bacon
- pineapple

Making a medium pizza.
Toppings:
- pepperoni

Making a small pizza.
Toppings:
- bacon
- pineapple

Making a medium pizza.
Toppings:
- pepperoni

Making a small pizza.
Toppings:
- bacon
- pineapple

Making a medium pizza.
Toppings:
- pepperoni

Making a small pizza.
Toppings:
- bacon
- pineapple<jupyter_text>Cheat Sheet - ClassesWhat are classes?Classes are the foundation of object-orientedprogramming. Classes represent real-world thingsyou want to model in your programs: for exampledogs, cars, and robots. You use a class to makeobjects, which are specific instances of dogs, cars,and robots. A class defines the general behavior thata whole category of objects can have, and theinformation that can be associated with those objects. Classes can inherit from each other – you canwrite a class that extends the functionality of anexisting class. This allows you to code efficiently for awide variety of situations. Creating and using classesConsider how we might model a car. What informationwould we associate with a car, and what behavior would ithave? The information is stored in variables calledattributes, and the behavior is represented by functions.Functions that are part of a class are called methods.<jupyter_code># The Car class
class Car():
  """A simple attempt to model a car."""
  def __init__(self, make, model, year):
    """Initialize car attributes."""
    self.make = make
    self.model = model
    self.year = year
    
 # Fuel capacity and level in gallons.
    self.fuel_capacity = 15
    self.fuel_level = 0
  
  def fill_tank(self):
    """Fill gas tank to capacity."""
    self.fuel_level = self.fuel_capacity
    print("Fuel tank is full.")

  def drive(self):
    """Simulate driving."""
    print("The car is moving.")
    

# Creating an object from a class
my_car = Car('audi', 'a4', 2016)
# Accessing attribute values
print(my_car.make)
print(my_car.model)
print(my_car.year)

# Calling methods

my_car.fill_tank()
my_car.drive()

# Creating multiple objects
my_car = Car('audi', 'a4', 2016)
my_old_car = Car('subaru', 'outback', 2013)
my_truck = Car('toyota', 'tacoma', 2010)<jupyter_output>audi
a4
2016
Fuel tank is full.
The car is moving.<jupyter_text>Modifying attributesYou can modify an attribute's value directly, or you canwrite methods that manage updating values more carefully.<jupyter_code># Modifying an attribute directly

my_new_car = Car('audi', 'a4', 2016)
my_new_car.fuel_level = 5

# Writing a method to update an attribute's value
def update_fuel_level(self, new_level): 
  """Update the fuel level."""
  if new_level <= self.fuel_capacity:
    self.fuel_level = new_level
  else:
      print("The tank can't hold that much!")

# Writing a method to increment an attribute's value
def add_fuel(self, amount):
  """Add fuel to the tank."""
  if (self.fuel_level + amount <= self.fuel_capacity):
    self.fuel_level += amount
    print("Added fuel.")
  else:
      print("The tank won't hold that much.")<jupyter_output><empty_output><jupyter_text>Naming ConventionIn Python class names are written in CamelCase and objectnames are written in lowercase with underscores. Modulesthat contain classes should still be named in lowercase withunderscores.  Class InheritanceIf the class you're writing is a specialized version of anotherclass, you can use inheritance. When one class inheritsfrom another, it automatically takes on all the attributes andmethods of the parent class. The child class is free tointroduce new attributes and methods, and overrideattributes and methods of the parent class. To inherit from another class include the name of theparent class in parentheses when defining the new class.<jupyter_code># The __init__() method for a child class
class ElectricCar(Car):
  """A simple model of an electric car."""
  def __init__(self, make, model, year):
    """Initialize an electric car."""
    super().__init__(make, model, year)
    # Attributes specific to electric cars.
    # Battery capacity in kWh.
    self.battery_size = 70
    # Charge level in %.
    self.charge_level = 0
    
    Adding new methods to the child class
class ElectricCar(Car):
 --snip--
 def charge(self):
 """Fully charge the vehicle."""
 self.charge_level = 100
 print("The vehicle is fully charged.")
Using child methods and parent methods
my_ecar = ElectricCar('tesla', 'model s', 2016)
my_ecar.charge()
my_ecar.drive()<jupyter_output><empty_output><jupyter_text>Finding your workflowThere are many ways to model real world objects andsituations in code, and sometimes that variety can feeloverwhelming. Pick an approach and try it – if your firstattempt doesn't work, try a different approach.<jupyter_code># Overriding parent methods
class ElectricCar(Car):
  '''--snip--'''
  def fill_tank(self):
    """Display an error message."""
    print("This car has no fuel tank!")
    
    
my_car = ElectricCar('asd','Tesla', 2099)
my_car.fill_tank()<jupyter_output>This car has no fuel tank!<jupyter_text>instances as inheritanceA class can have objects as attributes. This allows classesto work together to model complex situations.<jupyter_code># A Battery class
class Battery():
  """A battery for an electric car."""
  def __init__(self, size=70):
    """Initialize battery attributes."""
    # Capacity in kWh, charge level in %.
    self.size = size
    self.charge_level = 0
  
  def get_range(self):
    """Return the battery's range."""
    if self.size == 70:
      return 240
    elif self.size == 85:
      return 270

# Using an instance as an attribute
class ElectricCar(Car):
#  --snip--
    def __init__(self, make, model, year):
      """Initialize an electric car."""
      super().__init__(make, model, year)
      # Attribute specific to electric cars.
      self.battery = Battery()
    def charge(self):
      """Fully charge the vehicle."""
      self.battery.charge_level = 100
      print("The vehicle is fully charged.")
      
x =ElectricCar('324','234',40)
x.charge()

# Using the instance
my_ecar = ElectricCar('tesla', 'model x', 2016)
my_ecar.charge()
print(my_ecar.battery.get_range())
my_ecar.drive()<jupyter_output>The vehicle is fully charged.
240
The car is moving.<jupyter_text>Importing classesClass files can get long as you add detailed information and functionality. To help keep your program files uncluttered, you can store your classes in modules and import the classes you need into your main program Storing classesin a file car.py<jupyter_code>"""Represent gas and electric cars.""" 
 
class Car():     
  """A simple attempt to model a car."""  
  #--snip— 
 
class Battery():     
  """A battery for an electric car."""
  #--snip-- 
 
class ElectricCar(Car):     
  """A simple model of an electric car."""  
  #--snip--
  
  
  
# Need to create my_cars.py including all the classes and import them here so these below may not work
# They are to help show the pathway
# Importing individual classes from a module my_cars.py 
from car import Car, ElectricCar 
 
my_beetle = Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank() my_beetle.drive() 
 
my_tesla = ElectricCar('tesla', 'model s', 2016)
my_tesla.charge() my_tesla.drive() 

#Importing an entire module 
import car 
 
my_beetle = car.Car('volkswagen', 'beetle', 2016)
my_beetle.fill_tank() my_beetle.drive() 
 
my_tesla = car.ElectricCar('tesla', 'model s', 2016)
my_tesla.charge() 
my_tesla.drive()

# Importing all classes from a module (Don’t do this, but recognize it when you see it.) 
from car import *  
my_beetle = Car('volkswagen', 'beetle', 2016) 
 
# Classes in Python 2.7 I doubt this has changed for v3+ check anyway.
  
# Classes should inherit from object 
class ClassName(object): 

#The Car class in Python 2.7 
class Car(object): 
  
# Child class __init__() method is different 
class ChildClassName(ParentClass):     
  def __init__(self):         
    super(ClassName, self).__init__() 
    
    
# The ElectricCar class in Python 2.7 
class ElectricCar(Car):     
  def __init__(self, make, model, year):
    super(ElectricCar, self).__init__(make, model, year)<jupyter_output><empty_output><jupyter_text>Storing objects in a listA list can hold as many items as you want, so you can make a large number of objects from a class and store them in a list.     Here's an example showing how to make a fleet of rental cars, and make sure all the cars are ready to drive.<jupyter_code># A fleet of rental cars
from car import Car, ElectricCar 
 
# Make lists to hold a fleet of cars. 
gas_fleet = [] electric_fleet = [] 
 
# Make 500 gas cars and 250 electric cars. 
for _ in range(500):     
  car = Car('ford', 'focus', 2016) 
  gas_fleet.append(car) for _ in range(250):
    ecar = ElectricCar('nissan', 'leaf', 2016)  
    electric_fleet.append(ecar) 
 
# Fill the gas cars, and charge electric cars. 
for car in gas_fleet:   
  car.fill_tank() for ecar in electric_fleet:
    ecar.charge() 
 
print("Gas cars:", len(gas_fleet)) print("Electric cars:", len(electric_fleet))<jupyter_output><empty_output><jupyter_text>Beginner's Python Cheat Sheet - Files and ExceptionsWhat are files? What are exceptions?Your programs can read information in from files, and they can write data to files. Reading from files allows you to work with a wide variety of information; writing to files allows users to pick up where they left off the next time they run your program. You can write text to files, and you can store Python structures such as lists in data files.  Exceptions are special objects that help your programs respond to errors in appropriate ways. For example if your program tries to open a file that doesn’t exist, you can use exceptions to display an informative error message instead of having the program crash.   Reading from a fileTo read from a file your program needs to open the file and then read the contents of the file. You can read the entire contents of the file at once, or read the file line by line. The with statement makes sure the file is closed properly when the program has finished accessing the file.<jupyter_code># e.g. get this file form github or anywhere from internet using !wget
!wget https://github.com/ehmatthes/pcc/blob/master/chapter_10/siddhartha.txt
  
# or 

import urllib.request
print('Beginning file download with urllib2...')
url = 'https://github.com/ehmatthes/pcc/blob/master/chapter_10/siddhartha.txt'  
urllib.request.urlretrieve(url, './siddhartha.txt') 

filename = 'siddhartha.txt'

with open(filename) as f_obj:
    contents = f_obj.read()
    
print(contents)<jupyter_output>Beginning file download with urllib2...<jupyter_text>Reading line by line Each line that's read from the file has a newline character at the end of the line, and the print function adds its own newline character.The rstrip() method gets rid of the the extra blank lines this would result in whenprinting to the terminal.<jupyter_code>filename = 'siddhartha.txt'

with open(filename) as f_obj:
  for line in f_obj:
    print(line.rstrip())
    
    
# Storing the lines in a list 
filename = 'siddhartha.txt' 
 
with open(filename) as f_obj:
  lines = f_obj.readlines() 
  for line in lines:    
    print(line.rstrip())<jupyter_output><empty_output><jupyter_text>Writing to a file Passing the 'w' argument to open() tells Python you want to write to the file. Be careful; this will erase the contents of the file if it already exists. Passing the 'a' argument tells Python you want to append to the end of an existing file.<jupyter_code># Writing to an empty file 
filename = 'programming.txt' 
 
with open(filename, 'w') as f: 
  f.write("I love programming!") 
  
#   Writing multiple lines to an empty file 
filename = 'programming.txt' 
 
with open(filename, 'w') as f:   
  f.write("I love programming!\n")
  f.write("I love creating new games.\n")
  
#   Appending to a file 
filename = 'programming.txt' 
 
with open(filename, 'a') as f: 
  f.write("I also love working with data.\n")   
  f.write("I love making apps as well.\n")<jupyter_output><empty_output><jupyter_text>File PathsWhen Python runs the open() function, it looks for the file in the same directory where the program that's being excuted is stored. You can open a file from a subfolder using a relative path. You can also use an absolute path to open any file on your system.<jupyter_code># Opening a file from a subfolder
# note: if you use Google Colab you need to create or upload these files there is a
# Upload botton on the left hand side under Files
f_path = "text_files/alice.txt" 
 
with open(f_path) as f_obj:    
  lines = f_obj.readlines() 
 
for line in lines:     
  print(line.rstrip())
  
  
# Opening a file using an absolute path 
f_path = "/home/ehmatthes/books/alice.txt" 
 
with open(f_path) as f_obj:     
  lines = f_obj.readlines() 
  
#   Opening a file on Windows Windows will sometimes interpret forward slashes incorrectly. 
#   If you run into this, use backslashes in your file paths. 
f_path = "C:\Users\ehmatthes\books\alice.txt" 
 
with open(f_path) as f_obj:     
  lines = f_obj.readlines()<jupyter_output><empty_output><jupyter_text>The try-except blockWhen you think an error may occur, you can write a tryexcept block to handle the exception that might be raised. The try block tells Python to try running some code, and the except block tells Python what to do if the code results in a particular kind of error.<jupyter_code># Handling the ZeroDivisionError exception 
try:     
  print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!") 
    
# Handling the FileNotFoundError exception 
f_name = 'siddhartha.txt' 
 
try:    
  with open(f_name) as f_obj:  
    lines = f_obj.readlines() 
except FileNotFoundError:   
  msg = "Can't find file {0}.".format(f_name)
  print(msg)<jupyter_output><empty_output><jupyter_text>Knowing which exception to handleIt can be hard to know what kind of exception to handle when writing code. Try writing your code without a try block, and make it generate an error. The traceback will tell you what kind of exception your program needs to handle.> The else blockThe try block should only contain code that may cause an error. Any code that depends on the try block running successfully should be placed in the else block.<jupyter_code>import matplotlib.pyplot as plt
x_values = [0, 1, 2, 3, 4, 5]
squares = [0, 1, 4, 9, 16, 25]
plt.plot(x_values, squares)
plt.show()
import matplotlib.pyplot as plt
x_values = list(range(1000))
squares = [x**2 for x in x_values]
plt.scatter(x_values, squares, s=10)
plt.title("Square Numbers", fontsize=24)
plt.xlabel("Value", fontsize=18)
plt.ylabel("Square of Value", fontsize=18)
plt.tick_params(axis='both', which='major',
 labelsize=14)
plt.axis([0, 1100, 0, 1100000])
plt.show()
import matplotlib.pyplot as plt
x_values = list(range(1000))
squares = [x**2 for x in x_values]
plt.scatter(x_values, squares, c=squares,
 cmap=plt.cm.Blues, edgecolor='none',
 s=10)

plt.scatter(x_values[0], squares[0], c='green',
 edgecolor='none', s=100)
plt.scatter(x_values[-1], squares[-1], c='red',
 edgecolor='none', s=100)
plt.title("Square Numbers", fontsize=24)

# Removing axes
# You can customize or remove axes entirely. Here’s how to access
# each axis, and hide it.
plt.axes().get_xaxis().set_visible(False)
plt.axes().get_yaxis().set_visible(False)
# Setting a custom figure size
# You can make your plot as big or small as you want. Before
# plotting your data, add the following code. The dpi argument is
# optional; if you don’t know your system’s resolution you can omit
# the argument and adjust the figsize argument accordingly.
plt.figure(dpi=128, figsize=(10, 6))
# Saving a plot
# The matplotlib viewer has an interactive save button, but you can
# also save your visualizations programmatically. To do so, replace plt.show()  with plt.savefig(). 
# The bbox_inches='tight'
# argument trims extra whitespace from the plot.
plt.savefig('squares.png', bbox_inches='tight')
f= open("guru99.py","w+")


# Writing to a file
filename = 'journal.py'
with open(filename, 'w') as file_object:
    file_object.write("I love programing.")<jupyter_output><empty_output><jupyter_text><jupyter_code>!pip install pygal
import pygal
x_values = list(range(11))
squares = [x**2 for x in x_values]
cubes = [x**3 for x in x_values]

chart = pygal.Line()
# chart.force-uri_protocl ='http'
chart.title = "Squared and Cubes"
chart.x_labels = x_values

chart.add('Squaures', squares)
chart.add('Cubes', cubes)
chart.render_to_file('squares_cubes.svg')

chart = pygal.Line(file=True, zero=0)<jupyter_output><empty_output><jupyter_text><jupyter_code>filename = 'programming.txt' 
 
with open(filename, 'w') as f:
    f.write("I love programming!")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09472030429569603, 'fraction_numerical': 0.008785711332534005, 'mean_word_length': 4.397188441370077, 'pattern_counts': {'":': 0, '<': 215, '<?xml version=': 0, '>': 210, 'https://': 6, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '55', 'dir': 'jupyter-structured-clean-dedup', 'id': '304282', 'license': 'Apache-2.0', 'n_tokens_mistral': 15205, 'n_tokens_neox': 14332, 'n_words': 5816, 'path': 'week-0/beginnersPythonCheatSheet.ipynb', 'repo_name': 'yonseimath/data-science-2021', 'size': '48388'}