Wecode day2

Michael Minchang Kim·2020년 4월 21일
0

wecode

목록 보기
6/22

1. Print

The print function literally prints out the content

print('Hello World!')

2. Data Types

Data types tell what kind of information a certain variable contains.

a. Integer

Literally Integers -3,-2,-1,0,1,2,3

b. Float

Decimals are floats.
Integers with a decimal point is also considered as a float 1.00

c. Complex Numbers

Literally complex numbers. the i is replaced with a j in python
1+3j

d. String

A list of characters is a string. Numbers with quotation marks are also strings.

e. Boolean

A data type used with conditions. Can be either true or false.

3. Variables

Variables can be seen as containers of data.
Integers, floats, complex numbers, strings, booleans,functions can be stored in variables

4. f-Strings

%-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

a. simple syntax

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.'

b. arbitrary expressions

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

c. multiline

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 링크텍스트

5. Concatenating Text Strings

combining strings together is called concatenation

name = input()
print("Hello, " + name)

f-string explained above is a type of concating

6. If Statement

The if statement is structures thus in python

if expression:
    codes to execute 

a. Indents

Indentations are used instead of brackets in python

Comparisons

same as Java and C

elif/else

elif == else if

AND/OR

You can just write out 'and' instead of &&.
The same goes for ||, just write out 'or'

nested if statements

Use nested if statements if mutiple if conditions overlap.

Comments

Use # for single lines and '''~~~''' for multilines.

Functions

Same thing as functions in java and c.
The stucture in python

def 함수명(parameter):
    문장1
    문장2
    ...
    문장N
    [return 리턴값]

Function Parameters

you can just give parameters like you do in java or c

Keyword Arguments

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.

mixing positional args with keyword args

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!

Paramter Default Value

You can give the parameters of a funtion default values by using the syntax of keyword args.

Why can't default value parameters come before non-default value parameters?

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.

Function Arguments

code example

def compute(a, b, c, print_args=True, intype=int,  *more, operation, 
print_result=False, return_type, ignore_exceptions=True, **kwargs):

Variable Length Positional Arguments

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)

Variable Length Keyword Arguments

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'}

Lists

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

Append

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"]'

insert

You can insert a new element at the index you want using the insert method.

cities.insert(1, "제주특별자치도 제주시")

empty lists

my_list = [ ]

Updating Elements

cities = [
    "서울특별시",
    "부산광역시",
    "인천광역시",
    "대구광역시",
    "대전광역시",
]
cities[2] = "경기도 성남시"

list slicing

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]

deleting elements from a list

Get rid of an element at the index.

del twice[3]

remove

Remove using the value

twice.remove("모모")

Tuples

Tuples are lists that cannot be mutated.
Slicing still works
uses () instead of []

Sets

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()

adding new elements to a set

my_set = {1, 2, 3}
my_set.add(4)

removing elements from a set

my_set = {1, 2, 3}
my_set.remove(3)

looking up elements within a set

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 and unions

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}

Dictionary

This data structure includes sets of a key value pair

my_dic = { "key1" : "value1", "key2" : "value2"}

reading elements of a dictionary

Similar to lists but call elements through the key not index.
Keys can be strings and numbers but have to be unique.

adding new elements to a dictionary

If the key value is preexisting the old pair gets replaced.

dictionary_name[new_key] = new_value

For Loops

It's a for loop same thing as java.
Implemented like below

for element in list:
    do_something_with_element

break/continue

can be used in python too

profile
Soon to be the world's Best programmer ;)

0개의 댓글