Summary of Python 3 Tutorial by Net Ninja (Part 2 of 3)
JL’s Self-teaching Story #7

🌲 This is the second part of my summary of Python 3 Tutorial by Net Ninja on YouTube.
11) Functions
12) Variable Scope
13) Dictionaries
14) Sorting & Sets
15) Classes
16) The Init Function
17) Methods & Attributes
18) Modules & Packages
19) Bar Tab Calculator11) Functions (YouTube)
[lessons > functions.py]
def greet():
print('Hello World')
greet()
greet()
----------------------------------->>> python functions.py
Hello World
Hello World
> We can reuse the function as many times as possible.
[lessons > functions.py]
def greet(name, time):
print(f'Good {time}, {name}. Hope you\'re well.')
greet('Jen', 'morning')
----------------------------------->>> python functions.py
Good morning, Jen. Hope you're well.
> We can enter data when we call a function.
[lessons > functions.py]
def greet(name='Jen', time='morning'):
print(f'Good {time}, {name}. Hope you\'re well.')
greet()
----------------------------------->>> python functions.py
Good morning, Jen. Hope you're well.
> Or, we can assign the data in an argument when we define the function.
[lessons > functions.py]
def area(radius):
return 3.142 * radius**2def vol(area, length):
print(area * length)radius = int(input('enter a radius: '))
length = int(input('enter a length: '))vol(area(radius), length)
----------------------------------->>> python functions.py
enter a radius: <entered '10'>
enter a length: <entered '10'>
3142.0
> We can take a function as an argument.
12) Variable Scope (YouTube)
[lessons > scope.py]
my_name = 'Jen'def print_name():
print('the name inside the function is', my_name)print_name()
print('the name outside the function is', my_name)
----------------------------------->>> python scope.py
the name inside the function is Jen
the name outside the function is Jen
> We defined a variable called “my_name” globally.
[lessons > scope.py]
def print_name():
my_name = 'Jen'
print('the name inside the function is', my_name)print_name()
print('the name outside the function is', my_name)
----------------------------------->>> python scope.py
the name inside the function is Jen
NameError: name 'my_name' is not defined
> We defined a variable called “my_name” locally.
[lessons > scope.py]
my_name = 'Jen'def print_name():
my_name = 'Smith'
print('the name inside the function is', my_name)print_name()
print('the name outside the function is', my_name)
----------------------------------->>> python scope.py
the name inside the function is Smith
the name outside the function is Jen
> We defined a variable called “my_name” globally & overrode the variable locally.
[lessons > scope.py]
my_name = 'Jen'def print_name():
global my_name
my_name = 'Smith'
print('the name inside the function is', my_name)print_name()
print('the name outside the function is', my_name)
----------------------------------->>> python scope.py
the name inside the function is Smith
the name outside the function is Smith
> We defined a variable called “my_name” globally & overrode the variable locally. Also, I added “global my_name” to make the locally overridden variable globally.
13) Dictionaries (YouTube)
>>> python
>>> colors = {'red':'apple', 'yellow':'banana'}
>>> colors['red']
'apple'
>>> 'blue' in colors
False
>>> 'red' in colors
True>>> colors.keys()
dict_keys(['red', 'yellow'])
>>> list(colors.keys())
['red', 'yellow']>>> colors.values()
dict_values(['apple', 'banana'])
>>> vals = list(dict_values())
['apple', 'banana']
>>> vals.count('banana')
1
>>> vals.count('kiwi')
0>>> colors['brown'] = 'kiwi'
>>> colors
{'red':'apple', 'yellow':'banana', 'brown':'kiwi'}>>> person = dict(name='Jen', age=25, nationality='Korean')
>>> person
{'name':'Jen', 'age':25, 'nationality':'Korean'}
Now, we’ll work on exercises in a text editor. (I’m using Visual Studio Code.)
[lessons > dictionaries.py]
def intro(dictionary):
for key, val in dictionary.items():
print(f'I\'m {key} and I like {val}.')colors = {}while True:
name = input('enter a name: ')
color = input('enter a color: ')
colors[name] = color another = input('add another? (y/n): ')
if another == 'y':
continue
else:
breakintro(colors)
- .items(): “When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the
items()method (Official Website)”. - “while True” creates an infinite loop. But, we can break out of the loop when user types “n” as a response to the “add another? (y/n): ” question. Until then, keep assigning key-value pairs that the user enter to the “cities” object.
14) Sorting & Sets (YouTube)
>>> python
>>> nums = [3,4,1,4,5,4,5,9]
>>> sorted(nums)
[1, 3, 4, 4, 4, 5, 5, 9]
>>> set(nums)
{1, 3, 4, 5, 9}>>> names = ['amy','smith','keith','Jen','Amy','Jane','amy']
>>> sorted(names)
['Amy', 'Jane', 'Jen', 'amy', 'amy', 'keith', 'smith']
>>> set(names)
{'amy', 'Jane', 'Amy', 'Jen', 'keith', 'smith'}>>> cities = {'jen':'Seoul', 'smith':'Tokyo', 'kim':'Seoul'}
>>> sorted(cities.values())
('Tokyo', 'Seoul', 'Seoul')
>>> set(cities.values())
{'Tokyo', 'Seoul'}
> sorted()
- Doesn’t get rid of duplicates.
- Preserve an order (Capital letters always come first).
- Produce results with round brackets
> set()
- Get rid of duplicates.
- Doesn’t preserve an order.
- Produce results with curly brackets
[lessons > dictionaries.py]
def count(dictionary):
user_colors = list(dictionary.values())
for user_color in user_colors:
num = user_colors.count(user_color)
print(f'There are {num} users who like {user_color}.')colors = {}while True:
name = input('enter a name: ')
color = input('enter a color: ')
colors[name] = coloranother = input('add another? (y/n): ')
if another == 'y':
continue
else:
breakcount(colors)
----------------------------------->>> python dictionaries.py
>>> <entered data>
There are 2 users who like red.
There are 3 users who like blue.
There are 2 users who like red.
There are 3 users who like blue.
There are 3 users who like blue.
> To avoid duplicated statements, replace for user_color in user_colors with for user_color in set(user_colors).
>>> python dictionaries.py
>>> <entered data>
There are 2 users who like red.
There are 3 users who like blue.15) Classes (YouTube)
>>> python
>>> name = 'jen'
>>> age = 25
>>> nums = [1,2,3,4]
>>> type(name)
<class 'str'>
>>> type(age)
<class 'int'>
>>> type(nums)
<class 'list'>
>>> name.upper()
JEN“Class is a blueprint of how an object should look and behave (Net Ninja)”
[lessons > classes.py]
class Planet:
def __init__(self):
self.name = 'Hoth'
self.radius = 200000
self.gravity = 5.5
self.system = 'Hoth System' def orbit(self):
return f'{self.name} is orbiting in the {self.system}.'hoth = Planet()
print(f'Name is: {hoth.name}')
print(f'Radius is: {hoth.radius}')
print(f'The gravity is: {hoth.gravity}')
print(hoth.orbit())
----------------------------------->>> python classes.py
Name is: Hoth
Radius is: 200000
The gravity is: 5.5
Hoth is orbiting in the Hoth System.
> We can attach a class to an instance (e.g., hoth = Planet())
> We can also attach a method to a class (e.g., def orbit(self):)
16) The Init Function (YouTube)
[lessons > classes.py]
class Planet:
def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = system def orbit(self):
return f'{self.name} is orbiting in the {self.system}.'hoth = Planet('Hoth', 200000, 5.5, 'Hoth System')
print(f'Name is: {hoth.name}')
print(f'Radius is: {hoth.radius}')
print(f'The gravity is: {hoth.gravity}')
print(hoth.orbit())naboo = Planet('Naboo', 300000, 8, 'Naboo System')
print(f'Name is: {naboo.name}')
print(f'Radius is: {naboo.radius}')
print(f'The gravity is: {naboo.gravity}')
print(naboo.orbit())
----------------------------------->>> python classes.py
Name is: Hoth
Radius is: 200000
The gravity is: 5.5
Hoth is orbiting in the Hoth System.
Name is: Naboo
Radius is: 300000
The gravity is: 8
Naboo is orbiting in the Naboo System.
> By passing “name”, “radius”, “gravity”, and “system” as arguments in the init function, we can reuse the init function in new instances of the Planet class.
17) Methods & Attributes (YouTube)
[lessons > classes.py]
class Planet:
shape = 'round' def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = systemhoth = Planet('Hoth', 200000, 5.5, 'Hoth System')print(Planet.shape)
print(hoth.shape)
print(Planet.name)
----------------------------------->>> python classes.py
round
round
AttributeError: type object 'Planet' has no attribute 'name'
> shape = 'round' is a class-level attribute. That’s why it can be accessed by all of the following: Planet.shape, hoth.shape, and naboo.shape.
> On the other hand, self.name, self.radius, self.gravity, and self.system are instance-level attributes. That’s why it can’t be accessed by Planet.name.
[lessons > classes.py]
class Planet:
shape = 'round' def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = system def orbit(self):
return f'{self.name} is orbiting in the {self.system}.' @classmethod
def commons(cls):
return f'All planets are {cls.shape} because of gravity.'hoth = Planet('Hoth', 200000, 5.5, 'Hoth System')print(Planet.commons())
print(hoth.commons())
print(Planet.orbit)
----------------------------------->>> python classes.py
All planets are round because of gravity.
All planets are round because of gravity.
TypeError: orbit() missing 1 required positional argument: 'self'
> To create a class-level method, we need to include @classmethod decorator.
> Because orbit(self) is an instance-level method, this method can’t be accessed by Planet.orbit.
[lessons > classes.py]
class Planet:
shape = 'round'def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = system@staticmethod
def spin(speed = '2000 miles per hour'):
return f'The planet spins and spins at {speed}.'hoth = Planet('Hoth', 200000, 5.5, 'Hoth System')print(Planet.spin())
print(Planet.spin('a very high speed'))
print(hoth.spin('a very high speed'))
----------------------------------->>> python classes.py
The planet spins and spins at 2000 miles per hour.
The planet spins and spins at a very high speed.
The planet spins and spins at a very high speed.
> @staticmethod is a class-level method as well. But, it doesn’t take anything in except for the parameter we pass in.
18) Modules & Packages (YouTube)
A module is a file containing Python definitions and statements. Definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode) (official website)
[lessons > space > __init__.py]
-----------------------------------[lessons > space > planet.py]
class Planet:
shape = 'round'def __init__(self, name, radius, gravity, system):
self.name = name
self.radius = radius
self.gravity = gravity
self.system = systemdef orbit(self):
return f'{self.name} is orbiting in the {self.system}.'@classmethod
def commons(cls):
return f'All planets are {cls.shape} because of gravity.'@staticmethod
def spin(speed = '2000 miles per hour'):
return f'The planet spins and spins at {speed}.'
-----------------------------------[lessons > space > calc.py]
def planet_mass(gravity, radius):
mass = (gravity*radius**2) / (6.67*10**-11)
return massdef planet_vol(radius):
vol = (4*3.142*radius**2) / 3
return vol
-----------------------------------[lessons > classes.py]
from space.planet import Planet
from space.calc import planet_mass, planet_volnaboo = Planet('Naboo', 300000, 8, 'Naboo System')naboo_mass = planet_mass(naboo.gravity, naboo.radius)
naboo_vol = planet_vol(naboo.radius)print(f'{naboo.name} has a mass of {naboo_mass} and a volume of {naboo_vol}.')
----------------------------------->>> python classes.py
Naboo has a mass of 1.0794602698650675e+22 and a volume of 377040000000.0.
- Having “__init__.py” file in “space” folder tells Python that the folder is a package, a collection of modules.
- Instead of saving info of Planet class in classes.py, saved the info in planet.py within the package.
- We can import data from the package and use it.
19) Bar Tab Calculator (YouTube)
[projects > bar_tab.py]
class Tab:
menu = {
'soft_drink': 2,
'chicken': 10,
'dessert': 6
} def __init__(self):
self.total = 0
self.items = []
def add(self, item):
self.items.append(item)
self.total += self.menu[item] def print_bill(self, tax, service):
tax = (tax/100) * self.total
service = (service/100) * self.total
total = self.total + tax + service
for item in self.items:
print(f'{item} ${self.menu[item]}') print(f'Total: ${total:.2f}')
-----------------------------------(nn_python3) Hyejungs-MacBook-Air:projects HyejungLim$ python
>>> from bar_tab import Tab
>>> table1 = Tab()
>>> table1
<bar_tab.Tab object at 0x103df6518>
>>> table1.add('soft_drink')
>>> table1.add('chicken')
>>> table1.add('dessert')
>>> table1.print_bill(10, 10)
soft_drink $2
chicken $10
dessert $6
Total $21.60
If we change {item} to {item:20} & Total: to {"Total:":20}, we can set {item} & {"Total:"} to be 20 characters long. So, the output would be the following:
soft_drink $2
chicken $10
dessert $6
Total $21.60Thanks for reading! 💕 If you like this blog post, please clap👏
