출력

 

줄을 바꾸지 않고 출력한다.

Console.Write("Hello");

개행 문자로 출력한다.

Console.WriteLine("output");

 

C#의 주석은 자바처럼 슬래쉬 두 개이다.

// 이것은 주석입니다
/* 이것은
 * 여러 줄
 * 주석입니다
 * 출력되지 않습니다
 */

 

Console.WriteLine("\tHEY, Hello!"); // 탭
Console.WriteLine("HEY, Hell\bo!"); // 백스페이스
Console.WriteLine("HEY, \nHello!"); // 개행

 

키를 입력하기 전까지 대기

Console.ReadKey();

 

 

Visual Studio(Visual Studio Code와 다른 프로그램이다. 지금까지 같은건줄) 에서 솔루션 내에 프로젝트를 여러 개 생성했을 때,해당 프로젝트만 실행하는 방법

솔루션 우클릭 > 속성 > 공용 속성 > 시작 프로젝트 > 현재 선택 영역

솔루션 우클릭 > 속성
공용 속성 > 시작 프로젝트 > 현재 선택 영역

 

 

※ 쓸모 없는 없지만 알아두면 좋은(?) 정보

실행이 끝나면 삡 소리가 난다.

Console.Beep();

 

'C# > C#' 카테고리의 다른 글

06. 산술 연산자(Arithmetic Operator)  (0) 2023.08.21
05. 입력(Input)  (0) 2023.08.18
04. 형변환(Type Casting)  (0) 2023.08.17
03. 상수(Constants)  (0) 2023.08.16
02. 변수(Variables)  (0) 2023.08.15
예외(Exceptions)

프로그램에서 에러가 발생할 가능성을 방지하여 안정적으로 처리하기 위해 예외를 작성한다.

fruit = ['apple', 'banana', 'strawberry']

try:
    fruit[3]
except:
    print("인덱스를 참조할 수 없습니다.")
# else:
#     print("정상 수행")
finally:
    print("명령 수행")

try에는 예외가 발생 가능성이 있는 코드를 작성하고 except는 에러 상황을 만났을 때, 우회하여 어떤 처리를 해야하는지 설정한다. else는 정상적으로 코드를 수행했을 때 작동하며, finally는 에러가 발생하든 정상적으로 실행되든 작동한다.

 

 

파일 읽기/쓰기

파일 경로를 설정 할 때에는 절대경로와 상대경로가 있다.

절대경로는 컴퓨터의 전체 경로를 말하며(보통 C:\Users\...로 시작한다.) 특수한 경우를 제외하면 일반적으로 작업할 때에는 컴퓨터에 종속되지 않는 상대경로를 쓴다.

f = open('literature\poem.txt', 'r', encoding='UTF-8')

print(f.read()) # 전체
print(f.readline()) # 한 줄
print(f.readlines()) # 전체 줄

f.close()

파일을 읽은 후에는 파일이 유실되지 않도록 close( ) 함수로 닫아주어야한다.

 

with문은 close( ) 함수를 사용하지 않아도 파일을 읽고 자동으로 닫는다.

with open('literature\poem.txt', 'r', encoding='UTF-8') as f:
    print(f.read())

 

쓰기는 a와 w 두 가지 방법이 있다.

f = open('literature\poem.txt', 'a', encoding='UTF-8')
f = open('literature\poem2.txt', 'w', encoding='UTF-8')

f.write("새로운 글이 작성되었습니다.")

f.close()

a는 기존의 내용에 새로 추가하는 것이고, w는 기존의 내용에서 새로운 내용으로 대체하는 것이다. w 모드를 사용할 때에는 기존의 내용이 유실되므로 주의하자.

 

 

'Back-End > Python' 카테고리의 다른 글

객체지향  (0) 2023.08.09
회원가입 프로그램 실습 - 파이썬(Python) 편  (0) 2023.08.08
함수  (0) 2023.08.07
자료구조 - 리스트 / 튜플 / 딕셔너리  (0) 2023.07.27
조건문과 반복문  (0) 2023.07.20

>>본문<<

 

오늘의 단어

mobile / prepare / surface/ encounter / contain

 

 

mobile

1. 이동하는, 이동식의

2. 움직임이 자유로운, 기동성 있는

3. 모빌

 

예문

This small mobile robot eventually landed on Mars seven months later.

이 작은 이동식 로봇은 7개월 뒤 화성에 착륙했다.

 

It's important to keep the joint mobile while it heals.

회복되는 동안 관절을 움직이는 것이 중요하다.

 

 

surface

1. 표면[표층], 지면, 수면

2. 수면으로 올라오다

3. 나타나다[드러나다], 표면화되다

 

예문

We've now climbed up on top of this fan and are exploring the sedimentary rocks on the top surface of the fan.

우리는 이제 이 팬의 위로 올라가서 팬 표면의 퇴적암을 탐사할 것이다.

 

The submarine surfaced a few miles off the coast.

잠수함은 해안에서 몇 마일 떨어진 수면 위에 올라왔다.

 

A rumour has surfaced that the company is about to go out of business.

그 회사가 회사원들을 내보내는 중이라는 소문이 돌았다.

 

 

turn out

1. 모습을 드러내다[나타나다]

2. 되다[되어 가다], 판명나다

3. 바깥쪽으로 향하다

 

예문

As it turned out, these were igneous rocks, which was a surprise to us, but a really pleasant surprise because igneous rocks contain different kinds of information that we're interested in for return sample science.

이 화성암이 모습을 드러내며 우리를 놀라게 했고 다양한 정보를 가지고 있는 화성암이 반환 샘플 과학에 관심이 있는 우리에게 즐거운 놀라움을 가져다 주었다.

 

As events turned out, we were right to have decided to leave early.

일이 이렇게 되자, 우리가 일찍 떠난다는 결정을 한 것이 옳았다.

 

The truth turned out to be stranger than we had expected.

우리의 예상보다 밖의 사실이 판명났다.

 

 

encounter

1. 맞닥뜨리다[부딪히다]
2. 접하다[마주치다]
3. 만남[접촉/조우]
4. 시합

 

예문

What are some of the different types of rock that Perseverance has encountered since it landed two years ago?

Perseverance가 착륙한지 2년 동안 어떤 다양한 종류의 돌을 접했습니까?

 

This meeting will be the first encounter between the party leaders since the election.

이 회의는 선거 이후 지도자 간의 첫 만남이 될 것이다.

 

 

contain

1.  …이 들어[함유되어] 있다, 포함하다
2. 억누르다[참다]
3. 방지하다[억제하다]

 

예문

I lost a file containing a lot of important documents.

많은 중요한 문서가 포함된 파일을 잃어버렸다.

 

She could no longer contain her anger and started yelling at him.

그녀는 더이상 화를 참지 못하고 그에게 소리를 지르기 시작했다.

 

Farms in the area have been closed off in an attempt to contain the disease.

이 지역의 농장은 질병을 방지하기 위해 폐쇄했다.

 

 

클래스(Classes)

클래스의 이름은 함수나 변수의 이름과는 다르게 첫글자를 대문자로 시작한다.

self는 __init__ 생성자 함수를 만들 때 필요한 첫 번째 파라미터이다. self를 넣지 않으면 예기치 못한 오류를 발생시킬 수 있다.

# 클래스 (Classes)

class Student:

    def __init__(self, name, major, is_graduated):
        self.name = name
        self.major = major
        self.is_graduated = is_graduated

    def study(self):
        print(f'{self.name} 학생은 공부 중입니다.')

# 인스턴스

student_1 = Student('김사람', 'ㅇㅇ과', False)

student_1_name = student_1.name
print(student_1_name)

student_1.study()

인스턴스화 된 student_1을 바로 print로 출력하면 지정된 주소값이 나온다. 저장된 값을 불러오기 위해서는 변수를 만들어 넣어주어야한다.study 함수에는 이미 출력 함수가 들어있기 때문에 따로 print에 넣어주지 않아도 출력된다.

 

정보를 수정하는 방법에 대해 알아보자.

class Student:

    def __init__(self, name, major):
        self.name = name
        self.major = major
        self.is_graduated = False

    def study(self):
        print(f'{self.name} 학생은 공부 중입니다.')

# 인스턴스

student_1 = Student('김사람', 'ㅇㅇ과')

student_1.major = 'ㅁㅁ과'
print(student_1.major)

위처럼 직접적으로 정보를 수정할 수 있다. 그러나 이 방법은 보안 부분에서 좋지 않은 방법이다.

 

함수를 구성하여 인스턴스의 속성을 바꾸는 것이 바람직하다.

class Student:

    def __init__(self, name, major):
        self.name = name
        self.major = major
        self.is_graduated = False

    def study(self):
        print(f'{self.name} 학생은 공부 중입니다.')

    def edit_major(self, new_major):
        student_1.major = new_major
        print(f'{student_1.major}로 전공이 변경되었습니다.')

# 인스턴스

student_1 = Student('김사람', 'ㅁㅁ과')

student_1.edit_major('ㅁㅁ과')
print(student_1.major)

 

 

상속(Inheritance)

기존에 사용하던 클래스의 공통적인 속성을 가져와 사용할 수 있다.

class Student:

    def __init__(self, name, major):
        self.name = name
        self.major = major
        self.is_graduated = False

    def study(self):
        print(f'{self.name} 학생은 공부 중입니다.')

# 인스턴스

student_1 = Student('김사람', 'ㅇㅇ과')

student_1.major = 'ㅁㅁ과'
print(student_1.major)

# 상속
class ForeignStudent(Student):

    def __init__(self, name, major, country):
        super().__init__(name, major)
        self.country = country

foreign_stud_1 = ForeignStudent('박사람', '도예학과', '미국')
print(foreign_stud_1.name)
print(foreign_stud_1.major)
print(foreign_stud_1.country)
print(foreign_stud_1.is_graduated)

 

부모 클래스에서 정의된 함수를 자식 클래스에서 덮어 쓰는 것을 오버라이딩이라고 한다.

class Student:

    def __init__(self, name, major):
        self.name = name
        self.major = major
        self.is_graduated = False

    def study(self):
        print(f'{self.name} 학생은 공부 중입니다.')

# 인스턴스

student_1 = Student('김사람', 'ㅇㅇ과')

student_1.major = 'ㅁㅁ과'
print(student_1.major)

# 상속
class ForeignStudent(Student):

    def __init__(self, name, major, country):
        super().__init__(name, major)
        self.country = country
        
    # 오버라이딩
    def study(self):
        print(f'{self.name} is studing now.')

foreign_stud_1 = ForeignStudent('박사람', '도예학과', '미국')

foreign_stud_1.study()

 

만든 클래스를 모듈에서 함수를 불러왔던 것처럼 활용할 수 있다.

# from classes import Student, ForeignStudent
from classes import * # 모든 함수

stud_1 = Student('김사람', 'ㅁㅁ과')
foreign_stud_1 = ForeignStudent('박사람', '도예학과', '미국')

stud_1.study()
foreign_stud_1.study()

 

 

'Back-End > Python' 카테고리의 다른 글

예외 처리와 파일 다루기  (0) 2023.08.10
회원가입 프로그램 실습 - 파이썬(Python) 편  (0) 2023.08.08
함수  (0) 2023.08.07
자료구조 - 리스트 / 튜플 / 딕셔너리  (0) 2023.07.27
조건문과 반복문  (0) 2023.07.20

+ Recent posts