Python's functions
1. print() -> shows what is in the ()
2. input() -> Make an input box where I can put the value -> return intro str type -> inside of ()
3. len() -> find the length of the data -> inside of ()
4. type() -> find the type of the given data -> inside of ()
5. int(), float(), str() -> turn the data type into another data type -> inside of the ()
6. sum() -> find the sum(total) of the given data -> inside of the () (only on list and tuple)
7. min(), max() -> min -> find the minimum value, max -> find the maximum value -> inside of the ()
8. sorted() -> align all the value(list, tuple etc)
8.1 .sort() -> It will sort the given value itself. cannot be returned by other variables
ex.
result ->
a: [3, 1, 2]
____________________
a: [1, 2, 3]
b: None
only can be used in the 'a' variable(not b)
8.2 sorted -> It will sort the given value and it can be returned by other variables
Ex.
result ->
a: [3, 1, 2]
____________________
a: [3, 1, 2]
b: [1, 2, 3]
can be used by other variables
9. abs() -> find the absolute value in the given data -> inside of the ()
10. round() -> These rounds' values are in the float data.
Ex.
result -> 3.43 (a, 2) -> in 'a' variable. Round to the second decimal place.
Function -> def
frame
def name of function (Parameters1, Parameters2, .....):
codes
Tips!
Parameter -> receiver
Ex.
def Hi(name): -> (name) -> parameter
print(f"{name}. Hi!
Argument -> giver
Hi("kevin") -> ("kevin") -> argument
return -> after completing the code, returns to the location it was called.
Multiple returning data
Ex.
It will return both True and False -> (in tuple type)
BUT
since it returns in tuple type, I can put multiple variables too
So, If I give two variables(a, b) as well as the return data, a will have True, and b will have False data
It's like
Processing return value, normal execution status = function(argument1, argument2, etc..)
I can also set the default data
Ex.
I didn't put any data in hi(). since I put name = 'kevin' -> it means that If I don't give any argument,
'kevin' will be replaced as argument
Remember!
the variable that has the default data must follow after the variable that doesn't have the default data
Ex.
as I can see, since age has no default data, it must come first.
Variable-Length Argument -> takes an indefinite number of arguments.
1. *args
Ex.
*arg -> can take numerous arguments like (1,2,3) -> I don't have to make like num1, num2, num3 etc
-> in tuple type
2. *kwargs
It is almost the same as *args but returns in dictionary type
result -> {'name': 'Kevin', 'age': 40}
And I can use both args and kwargs -> but args must come first
Module -> is a bundle that includes related classes, variables, functions
1. import
Ex.
lets make 2 file
1.1 study
1.2 work
then make a function in study file
then use import in work file
import study -> bring study.py file and make it available to use on work.py file
as -> change the name to m
work = m.study(1,2,3) -> get close to the file (m.) and use the function(study(1,2,3))
result -> 6(1+2+3)
2. from -> loads specific items from the module.
ex.
as here, I can see I don't have to use '.' to bring data
I already brought the study.py file by the 'from' statement
from study import sumNo as s -> will get the sumNo function from the study.py file. So, I can get close to the data more easily.
Tips
* - will get all the modules Ex.(from study import *)
Package -> bundle of the modules
Almost the same as the module
how to get packages
Ex. in my file
mypackage/
__init__.py
module1.py
module2.py
from mypackage import module1
but if I want to get a certain function
from mypackage.module1 import (name of the function)
Frame
mypackage/ -> top package director
__init__.py -> initializes the package(necessary -> the name itself)
module1.py -> first module
module2.py -> second module
__init__.py - initializes the sub-package
submodule.py -> the sub package's inner module
pip -> python's package installation helper
pip list -> shows the list of the downloaded packages
pip install name of package -> download the selected package\
pip install --upgrade name of the package -> upgrade the installed packages
pip uninstall -> uninstall the installed packages
virtual environment-> makes the isolated Python environment -> it can be upgraded itself then prevent the errors that can happen because of the different version.
How to make a virtual environment
1. python -m venv myenv -> make the virtual environment named myenv(the name can be changed)
activating the virtual environment
myenv\\Scripts\\activate -> not //
deactivate the virtual environment
deactivate
how to cope with errors
try:
#codes that can cause the error
except except type:
#codes that will run instead of the error code
Ex.
since 10/0 will cause an error, then '에러' will be shown
finally ->always be executed regardless of whether an exception occurs.
Total frame
try:
#
except except type:
#
finally:
# codes that will always be executed
To see the error type
try:
10/0
except Exception(class) as e :
print (f'모든에러 {e}")
Class Objects: Object Oriented
Class -> It's like a whole frame for the object
1. OOP
Encapsulation-> will lash all the methods and characteristics so that the other codes can't touch it
inheritance -> One object passes its code to another object.
Polymorphism -> methods with the same name can behave differently on different objects.
How to make class
class name of the class:
def __init__(self): -> it should be __init__ for first
self -> the function itself, automatically passes the object on which the current method was called. So, it must be located at the very first of the () ex. (self, input_name). So, I don't have to put the value for self. because I will send the received data to the object.
self.name -> it will get close to the data itself(__init__) and make a name data
Since data received from __init__ is initialized, if data is put into the __init__ function, it is initialized and then stored. From then on, other functions can also retrieve and use the data in __init__.
Magic Method -> a defined method that has a special role
common magic method
1. __init__ -> Responsible for initializing objects
2. __repr__ -> Returns the "official" string representation
Ex.
But I thought It is similar as normal function
But it will show error. because it must be print(name.dog())
__add__ -> adds objects together.
but to use __add__, must use other
Ex.
__add__(self, other)
__eq__ -> find if the two objects are same -> also must use other
__str__ -> mostly used to show specific text on screen
Class method
there is a variable under the class Myclass. -> Class variable = This variable can be used for all of the parts in the class
@classmethod -> This is the class method that represents the class
write it on the function and change the parameters to cls
Static method -> method that is not related to a class or object, but is meaningful in the flow of the class.
Inheritance -> is when a new class inherits and uses the properties and methods of an existing class.
from here, Animal class is not different from other classes. but making new class and putting the old one (Dog(new)(Animal(old)) -> this is what inheritance is.
+
super().__init__(parameter) -> will make the code able to get the mother's code
Dealing with files
opening file -> open('name of file', 'mode')
file modes
1. "r" -> just for reading
2. "w" -> for writing
3. "a" -> adding the data at the end of the data
4. "b" -> binary mod. used to read or write previous files, and used with other mods
closing file -> close() method -> must be closed after opened
or
with statement -> will close the file automatically
ex.
with open()
reading file
read() method
ex.
a = open('x.txt', "r")
a.read()
readline() -> will read lines one by one
if I want to start with the first line,
a.seek(0)
readlines method -> will read all the lines at once
Writing files
write() method
ex.
with open('a.txt', "w")
file.write('쓰인 내용")
But the result will be in number. It means it's the number of successfully changed texts
writeline() method -> will write all the line included in list
Iterator
same as for(actually a object of the for)
used __iter__() method, __next()__ and StopIteration to stop
Ex.
numbers = [1, 2, 3]
iterator = iter(numbers) # create iterator from list
print(next(iterator)) # 1
print(next(iterator)) # 2
print(next(iterator)) # 3
Good night!