The print function literally prints out the content
print('Hello World!')
Data types tell what kind of information a certain variable contains.
Literally Integers -3,-2,-1,0,1,2,3
Decimals are floats.
Integers with a decimal point is also considered as a float 1.00
Literally complex numbers. the i is replaced with a j in python
1+3j
A list of characters is a string. Numbers with quotation marks are also strings.
A data type used with conditions. Can be either true or false.
Variables can be seen as containers of data.
Integers, floats, complex numbers, strings, booleans,functions can be stored in variables
%-formatting and str.format() can used to insert within a string. However using them make code hard to read when longer strings are used.
So a new method of f-String is being used now.
This method is not only more concise but faster
just add a f or F infront of the quotation mark and place brackets in places where you need Variables
>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'
simple arithmetics can be done within the brackets
>>> f"{2 * 37}"
'74'
functions and methods can also be called within the brackets
----------------function----------------
>>> def to_lowercase(input):
... return input.lower()
>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny."
'eric idle is funny.'
-----------------method------------------
>>> f"{name.lower()} is funny."
'eric idle is funny.'
objects created from classes can also be used
multiple lines of strings can be created for better readability
>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
... f"Hi {name}. "
... f"You are a {profession}. "
... f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'
there has to be an f infront of each string.
using a backslash between strings also works.
>>> message = f"Hi {name}. " \
... f"You are a {profession}. " \
... f"You were in {affiliation}."
...
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'
for more info 링크텍스트
combining strings together is called concatenation
name = input()
print("Hello, " + name)
f-string explained above is a type of concating
The if statement is structures thus in python
if expression:
codes to execute
Indentations are used instead of brackets in python
same as Java and C
elif == else if
You can just write out 'and' instead of &&.
The same goes for ||, just write out 'or'
Use nested if statements if mutiple if conditions overlap.
Use # for single lines and '''~~~''' for multilines.
Same thing as functions in java and c.
The stucture in python
def 함수명(parameter):
문장1
문장2
...
문장N
[return 리턴값]
you can just give parameters like you do in java or c
This concept is similar to the f-string concat.
Instead of inputing parameters in order, you can specify the name of the parameter and give it value.
You can use both positional and keyword args together. However you obviously have to have the positional args in the right place. They are called positional arguments for a reason!
You can give the parameters of a funtion default values by using the syntax of keyword args.
if the default parameter comes first there is no way for the computer to read the following non-default value parameter. I guess it could work if the first argument is left blank and the second argument is shown after a comma but that would make code hard to read.
edited:
When python is being compiled the interpreter goes through the code that is passed.
And there is a preset rule that has to be followed. Since there is an order that the parameters have to follow if the order of parameters is off the interpreter throws an error.
The order that has to be followed is :
Positional Parameter->Keyword Parameter->Default Parameter->Keyword-only Parameter
Since positional parameters and keyword parameter looks the same, at the stage of defining, even if keyword parameters could be acknowledged after a default parameter, it throws an error at the point of declaration.
A function is defined at the beginning of runtime. Even before the function is called the interpreter throws an error that the default value parameter is being defined before the non-default value parameter.
code example
def compute(a, b, c, print_args=True, intype=int, *more, operation,
print_result=False, return_type, ignore_exceptions=True, **kwargs):
This arguments saves all the input data into a tuple so it can take in as many arguments as the user inputs.
def my_min(*args):
result = args[0]
for num in args:
if num < result:
result = num
return result
my_min(4, 5, 6, 7, 2)
This arguments saves all the input data into a dictionary so it can take in as many key value pairs as the user inputs
def kwarg_type_test(**kwargs):
print(kwargs)
kwarg_type_test(a="hi")
kwarg_type_test(roses="red", violets="blue")
--result--
{'a': 'hi'}
{'roses': 'red', 'violets': 'blue'}
A list is a data structure that stores a bunch of elemets. These elements can be of different data types.
Indexing is same as java
You can attach a new element to the end of the list using the append method.
list.append(element)
You can attach multiple elements to the end of the list using the + sign. Similar to concating strings
list1 = list1 + list2
ex) color_list = color_list + ["Light Blue", "Pink"]'
You can insert a new element at the index you want using the insert method.
cities.insert(1, "제주특별자치도 제주시")
my_list = [ ]
cities = [
"서울특별시",
"부산광역시",
"인천광역시",
"대구광역시",
"대전광역시",
]
cities[2] = "경기도 성남시"
Used when copying a part of a list between indexes start and stop with a step.
It's similar to the for loop of java.
list_name[start : stop : step]
Get rid of an element at the index.
del twice[3]
Remove using the value
twice.remove("모모")
Tuples are lists that cannot be mutated.
Slicing still works
uses () instead of []
Sets are also like lists but they don't have indexing and cannot contain mutiple elements of the same data.
If the new data input is equal to one of the elements then it replaces it with the new data/ ends up being the same tho.
set1 = {1, 2, 3}
set2 = set([1, 2, 3])
you can turn a list into a set using set()
my_set = {1, 2, 3}
my_set.add(4)
my_set = {1, 2, 3}
my_set.remove(3)
Use the 'in' keyword to see if an element is already contained
my_set = {1, 2, 3}
if 1 in my_set:
print("1 is in the set")
> 1 is in the set
if 4 not in my_set:
print("4 is not in the set")
> 4 is not in the set
Intersections can be found using & or the intersection function
set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}
print(set1 & set2)
> {4, 5, 6}
print(set1.intersection(set2))
> {4, 5, 6}
Unions can be made using the | and union functions
print(set1 | set2)
> {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set1.union(set2))
> {1, 2, 3, 4, 5, 6, 7, 8, 9}
This data structure includes sets of a key value pair
my_dic = { "key1" : "value1", "key2" : "value2"}
Similar to lists but call elements through the key not index.
Keys can be strings and numbers but have to be unique.
If the key value is preexisting the old pair gets replaced.
dictionary_name[new_key] = new_value
It's a for loop same thing as java.
Implemented like below
for element in list:
do_something_with_element
can be used in python too