'파이썬'에 해당되는 글 12건

  1. 2019.08.23 파이썬 딕셔너리(dictionary)
  2. 2019.08.22 파이썬 세트(set)
  3. 2019.08.21 파이썬 튜플(tuple)
  4. 2019.08.20 파이썬 리스트(list)
  5. 2019.08.20 파이썬 문자열(String)
  6. 2019.08.20 파이썬 continue 문
  7. 2019.08.19 파이썬 break문
  8. 2019.08.19 파이썬 while 반복문
posted by 쁘로그래머 2019. 8. 23. 10:10

딕셔너리(dictionary)는 파이썬에서 키-값 쌍을 구현하는 데 사용됩니다. 

딕셔너리(dictionary)는 파이썬의 데이터 유형으로 특정 키에 대해 특정 값이 존재하는 실제 데이터 배열을 시뮬레이션 할 수 있습니다.


딕셔너리(dictionary)는 키-불변 파이썬 객체, 즉 숫자, 문자열 또는 튜플 인 반면 값은 임의의 파이썬 객체가 될 수있는 키-값 쌍의 모음이라고 말할 수 있습니다.


# 딕셔너리(dictionary) 생성하기

작은 괄호 ()로 묶고 콜론 (:)으로 구분 된 여러 키-값 쌍을 사용하여 dictionary를 작성할 수 있습니다. 

키-값 쌍의 콜렉션은 중괄호 ({})로 묶습니다.


dictionary를 정의하는 구문은 다음과 같습니다.

Dict = {"Name": "Ayush","Age": 22}  


# 딕셔너리(dictionary) 생성 및 출력

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  

print(type(Employee))  

print("printing Employee data .... ")  

print(Employee)  


# 결과

<class 'dict'>

printing Employee data .... 

{'Age': 29, 'salary': 25000, 'Name': 'John', 'Company': 'GOOGLE'}


# 딕셔너리(dictionary) 값에 액세스

인덱싱을 사용하여 목록 및 튜플에서 데이터에 액세스하는 방법에 대해 설명했습니다.

그러나 dictionary에서 키가 고유하므로 키를 사용하여 dictionary에서 값에 액세스 할 수 있습니다.

dictionary 값은 다음과 같은 방식으로 액세스 할 수 있습니다.


# 예시

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  

print(type(Employee))  

print("printing Employee data .... ")  

print("Name : %s" %Employee["Name"])  

print("Age : %d" %Employee["Age"])  

print("Salary : %d" %Employee["salary"])  

print("Company : %s" %Employee["Company"])  


# 결과

<class 'dict'>

printing Employee data .... 

Name : John

Age : 29

Salary : 25000

Company : GOOGLE


dictionary는 변경 가능한 데이터 유형이며 특정 키를 사용하여 값을 업데이트 할 수 있습니다.

# 예시

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}  

print(type(Employee))  

print("printing Employee data .... ")  

print(Employee)  

print("Enter the details of the new employee....");  

Employee["Name"] = input("Name: ");  

Employee["Age"] = int(input("Age: "));  

Employee["salary"] = int(input("Salary: "));  

Employee["Company"] = input("Company:");  

print("printing the new data");  

print(Employee)  


# 결과

<class 'dict'>

printing Employee data .... 

{'Name': 'John', 'salary': 25000, 'Company': 'GOOGLE', 'Age': 29}

Enter the details of the new employee....

Name: David

Age: 19

Salary: 8900

Company:JTP

printing the new data

{'Name': 'David', 'salary': 8900, 'Company': 'JTP', 'Age': 19}

'파이썬' 카테고리의 다른 글

파이썬 세트(set)  (0) 2019.08.22
파이썬 튜플(tuple)  (0) 2019.08.21
파이썬 리스트(list)  (0) 2019.08.20
파이썬 문자열(String)  (0) 2019.08.20
파이썬 continue 문  (0) 2019.08.20
posted by 쁘로그래머 2019. 8. 22. 13:33

파이썬 set는 중괄호로 묶인 다양한 항목의 정렬되지 않은 컬렉션으로 정의 할 수 있습니다. 

set의 요소는 복제 할 수 없습니다. 

파이썬 set의 요소는 변경 불가능해야합니다.


파이썬의 다른 컬렉션과 달리 set의 요소에 연결된 인덱스가 없습니다. 

즉 인덱스에 의해 set의 요소에 직접 액세스 할 수 없습니다. 

그러나 모두 함께 인쇄하거나 set를 반복하여 요소 목록을 가져올 수 있습니다.


# set 생성하기

괄호로 쉼표로 구분 된 항목을 묶어 set를 작성할 수 있습니다. 

파이썬은 또한 전달 된 시퀀스에 의해 set를 생성하는데 사용될 수있는 set 메소드를 제공합니다.


# set 생성 - 중괄호 사용

Days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}  

print(Days)  

print(type(Days))  

print("looping through the set elements ... ")  

for i in Days:  

    print(i)  


# 결과

{'Friday', 'Tuesday', 'Monday', 'Saturday', 'Thursday', 'Sunday', 'Wednesday'}

<class 'set'>

looping through the set elements ... 

Friday

Tuesday

Monday

Saturday

Thursday

Sunday

Wednesday


# set 생성 - set() 메서드 사용

Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"])  

print(Days)  

print(type(Days))  

print("looping through the set elements ... ")  

for i in Days:  

    print(i) 


# 결과

{'Friday', 'Wednesday', 'Thursday', 'Saturday', 'Monday', 'Tuesday', 'Sunday'}

<class 'set'>

looping through the set elements ... 

Friday

Wednesday

Thursday

Saturday

Monday

Tuesday

Sunday


# set에 아이템 추가

Python은 특정 항목을 set에 추가하는 데 사용할 수있는 add () 메소드를 제공합니다. 


# 예시

Months = set(["January","February", "March", "April", "May", "June"])  

print("\nprinting the original set ... ")  

print(Months)  

print("\nAdding other months to the set...");  

Months.add("July");  

Months.add("August");  

print("\nPrinting the modified set...");  

print(Months)  

print("\nlooping through the set elements ... ")  

for i in Months:  

    print(i)  


# 결과

printing the original set ... 

{'February', 'May', 'April', 'March', 'June', 'January'}


Adding other months to the set...


Printing the modified set...

{'February', 'July', 'May', 'April', 'March', 'August', 'June', 'January'}


looping through the set elements ... 

February

July

May

April

March

August

June

January 

'파이썬' 카테고리의 다른 글

파이썬 딕셔너리(dictionary)  (0) 2019.08.23
파이썬 튜플(tuple)  (0) 2019.08.21
파이썬 리스트(list)  (0) 2019.08.20
파이썬 문자열(String)  (0) 2019.08.20
파이썬 continue 문  (0) 2019.08.20
posted by 쁘로그래머 2019. 8. 21. 09:23

Python Tuple은 불변 파이썬 객체의 시퀀스를 저장하는 데 사용됩니다. 

튜플은 목록에 저장된 항목의 값을 변경할 수있는 반면 튜플은 변경할 수 없고 

튜플에 저장된 항목의 값을 변경할 수 없기 때문에 목록과 유사합니다.


작은 괄호로 묶인 쉼표로 구분 된 값의 모음으로 튜플을 작성할 수 있습니다. 


튜플은 다음과 같이 정의 할 수 있습니다.

T1 = (101, "Ayush", 22)  

T2 = ("Apple", "Banana", "Orange")  


# tuple 예시

tuple1 = (10, 20, 30, 40, 50, 60)  

print(tuple1)  

count = 0  

for i in tuple1:  

    print("tuple1[%d] = %d"%(count, i));  


# 결과

(10, 20, 30, 40, 50, 60)

tuple1[0] = 10

tuple1[0] = 20

tuple1[0] = 30

tuple1[0] = 40

tuple1[0] = 50

tuple1[0] = 60


# tuple 내장 함수

cmp(tuple1, tuple2) 두 튜플을 비교하고 tuple1이 tuple2보다 크면 true를, 그렇지 않으면 false를 반환합니다.

len(tuple) 튜플의 길이를 계산합니다.

max(tuple) 튜플의 최대 요소를 반환합니다.

min(tuple) 튜플의 최소 요소를 반환합니다.

tuple(seq) 지정된 시퀀스를 튜플로 변환합니다.


# 중첩 list 및 tuple

tuple 내부에 list를 저장하거나 list 안에 tuple을 임의의 레벨까지 저장할 수 있습니다.


# tuple내에 list를 저장하는 방법

Employees = [(101, "Ayush", 22), (102, "john", 29), (103, "james", 45), (104, "Ben", 34)]  

print("----Printing list----");   

for i in Employees:  

    print(i)  

Employees[0] = (110, "David",22)  

print();  

print("----Printing list after modification----");  

for i in Employees:   

    print(i)  


# 결과

----Printing list----

(101, 'Ayush', 22)

(102, 'john', 29)

(103, 'james', 45)

(104, 'Ben', 34)


----Printing list after modification----


(110, 'David', 22)

(102, 'john', 29)

(103, 'james', 45)

(104, 'Ben', 34)

'파이썬' 카테고리의 다른 글

파이썬 딕셔너리(dictionary)  (0) 2019.08.23
파이썬 세트(set)  (0) 2019.08.22
파이썬 리스트(list)  (0) 2019.08.20
파이썬 문자열(String)  (0) 2019.08.20
파이썬 continue 문  (0) 2019.08.20
posted by 쁘로그래머 2019. 8. 20. 12:31

파이썬의 list는 다양한 유형의 데이터 시퀀스를 저장하기 위해 구현됩니다. 

그러나 파이썬에는 시퀀스를 저장할 수있는 6 가지 데이터 형식이 포함되어 있지만 가장 일반적이고 안정적인 형식은 list입니다.


list는 값 모음 또는 다른 유형의 항목으로 정의 될 수 있습니다. 

list의 항목은 쉼표 (,)로 구분되고 대괄호 []로 묶습니다.


list는 다음과 같이 정의 할 수 있습니다.

L1 = ["John", 102, "USA"]  

L2 = [1, 2, 3, 4, 5, 6]  

L3 = [1, "Ryan"]  


# list 예시

emp = ["John", 102, "USA"]   

Dep1 = ["CS",10];  

Dep2 = ["IT",11];  

HOD_CS = [10,"Mr. Holding"]  

HOD_IT = [11, "Mr. Bewon"]  

print("printing employee data...");  

print("Name : %s, ID: %d, Country: %s"%(emp[0],emp[1],emp[2]))  

print("printing departments...");  

print("Department 1:\nName: %s, ID: %d\nDepartment 2:\nName: %s, ID: %s"%(Dep1[0],Dep2[1],Dep2[0],Dep2[1]));  

print("HOD Details ....");  

print("CS HOD Name: %s, Id: %d"%(HOD_CS[1],HOD_CS[0]));  

print("IT HOD Name: %s, Id: %d"%(HOD_IT[1],HOD_IT[0]));  

print(type(emp),type(Dep1),type(Dep2),type(HOD_CS),type(HOD_IT));   


# 결과

printing employee data...

Name : John, ID: 102, Country: USA

printing departments...

Department 1:

Name: CS, ID: 11

Department 2:

Name: IT, ID: 11

HOD Details ....

CS HOD Name: Mr. Holding, Id: 10

IT HOD Name: Mr. Bewon, Id: 11

<class 'list'> <class 'list'> <class 'list'> <class 'list'> <class 'list'>


# list에 요소 추가

파이썬은 list에 요소를 추가 할 수있는 append () 함수를 제공합니다. 

그러나 append () 메서드는 목록 끝에 만 값을 추가 할 수 있습니다.


# list 예시

l =[];  

n = int(input("Enter the number of elements in the list")); #Number of elements will be entered by the user  

for i in range(0,n): # for loop to take the input  

    l.append(input("Enter the item?")); # The input is taken from the user and added to the list as the item  

print("printing the list items....");   

for i in l: # traversal loop to print the list items  

    print(i, end = "  "); 


# list 결과

Enter the number of elements in the list 5

Enter the item?1

Enter the item?2

Enter the item?3

Enter the item?4

Enter the item?5

printing the list items....

1  2  3  4  5 


# list 요소 제거

List = [0,1,2,3,4]   

print("printing original list: ");  

for i in List:  

    print(i,end=" ")  

List.remove(0)  

print("\nprinting the list after the removal of first element...")  

for i in List:  

    print(i,end=" ")  


# 결과

printing original list: 

0 1 2 3 4 

printing the list after the removal of first element...

1 2 3 4 

'파이썬' 카테고리의 다른 글

파이썬 세트(set)  (0) 2019.08.22
파이썬 튜플(tuple)  (0) 2019.08.21
파이썬 문자열(String)  (0) 2019.08.20
파이썬 continue 문  (0) 2019.08.20
파이썬 break문  (0) 2019.08.19
posted by 쁘로그래머 2019. 8. 20. 11:39

파이썬에서는 따옴표 안에 문자 또는 문자 시퀀스를 묶어 문자열을 만들 수 있습니다. 

파이썬은 작은 따옴표, 큰 따옴표 또는 삼중 따옴표를 사용하여 문자열을 만들 수 있습니다.


파이썬에서 다음 예제를 고려하여 문자열을 만듭니다.

str = "Hi Python !"  


변수 str의 유형을 확인하면 type()을 사용하면 됩니다.

print(type(str))


# 문자열 재할당

문자열의 내용을 업데이트하는 것은 새 문자열에 할당하는 것만 큼 쉽습니다. 

문자열 객체는 항목 할당을 지원하지 않습니다. 


즉, 문자열은 내용을 부분적으로 바꿀 수 없으므로 새 문자열로만 바꿀 수 있습니다. 

파이썬에서는 문자열을 변경할 수 없습니다.


# 문자열 예시

str = "HELLO"  

str[0] = "h"  

print(str)  


# 결과

Traceback (most recent call last):

  File "12.py", line 2, in <module>

    str[0] = "h";

TypeError: 'str' object does not support item assignment


# 문자열 연산자

+: 연산자의 양쪽에 주어진 문자열을 결합하는 데 사용되는 연결 연산자라고합니다.

*: 반복 연산자라고합니다. 동일한 문자열의 여러 사본을 연결합니다.

[]: 슬라이스 연산자라고합니다. 특정 문자열의 하위 문자열에 액세스하는 데 사용됩니다.

[:]: 범위 슬라이스 연산자라고합니다. 지정된 범위에서 문자에 액세스하는 데 사용됩니다.

in: 멤버쉽 운영자라고합니다. 지정된 문자열에 특정 하위 문자열이 있으면 반환합니다.

not in: 멤버쉽 연산자이기도하고 in을 정확하게 반대로 수행합니다. 지정된 문자열에 특정 하위 문자열이 없으면 true를 반환합니다.

r/R: 원시 문자열을 지정하는 데 사용됩니다. 원시 문자열은 "C : // python"과 같은 이스케이프 문자의 실제 의미를 인쇄해야하는 경우에 사용됩니다. 문자열을 원시 문자열로 정의하려면 문자 r 또는 R 뒤에 문자열이옵니다.

%: 문자열 형식을 수행하는 데 사용됩니다. % d 또는 % f와 같은 C 프로그래밍에서 사용되는 형식 지정자를 사용하여 값을 파이썬으로 매핑합니다. 파이썬에서 포맷팅이 어떻게 이루어지는 지 논의 할 것입니다.


# 문자열 연산자 예시

str = "Hello"   

str1 = " world"  

print(str*3) # prints HelloHelloHello  

print(str+str1)# prints Hello world   

print(str[4]) # prints o              

print(str[2:4]); # prints ll                  

print('w' in str) # prints false as w is not present in str  

print('wo' not in str1) # prints false as wo is present in str1.   

print(r'C://python37') # prints C://python37 as it is written  

print("The string str : %s"%(str)) # prints The string str : Hello   


# 결과

HelloHelloHello

Hello world

o

ll

False

False

C://python37

The string str : Hello

'파이썬' 카테고리의 다른 글

파이썬 튜플(tuple)  (0) 2019.08.21
파이썬 리스트(list)  (0) 2019.08.20
파이썬 continue 문  (0) 2019.08.20
파이썬 break문  (0) 2019.08.19
파이썬 while 반복문  (0) 2019.08.19
posted by 쁘로그래머 2019. 8. 20. 10:23

파이썬에서 continue 문은 프로그램 제어를 루프 시작 부분으로 가져 오는 데 사용됩니다. 

continue 문은 루프 내의 나머지 코드 줄을 건너 뛰고 다음 반복으로 시작합니다. 

주로 루프 내부의 특정 조건에 사용되므로 특정 조건에 대한 특정 코드를 건너 뛸 수 있습니다.


Python continue 문의 구문은 다음과 같습니다.

#loop statements  

continue;  

#the code to be skipped   


# continue문 예시1

i = 0;  

while i!=10:  

    print("%d"%i);  

    continue;  

    i=i+1;  


# 결과

infinite loop


# continue문 예시2

i=1; #initializing a local variable  

#starting a loop from 1 to 10  

for i in range(1,11):  

    if i==5:  

        continue;  

    print("%d"%i);  


# 결과

1

2

3

4

6

7

8

9

10


# pass 구문

구문이 구문적으로 필요하지만 그 대신 실행 가능한 명령문을 사용하고 싶지 않은 경우에 사용됩니다.

Pass는 코드가 어딘가에 작성되지만 프로그램 파일에는 아직 작성되지 않은 경우에도 사용됩니다.


# pass 구문 예시

list = [1,2,3,4,5]  

flag = 0  

for i in list:  

    print("Current element:",i,end=" ");  

    if i==3:  

        pass;  

        print("\nWe are inside pass block\n");  

        flag = 1;  

    if flag==1:  

        print("\nCame out of pass\n");  

        flag=0;  


# 결과

Current element: 1 Current element: 2 Current element: 3 

We are inside pass block



Came out of pass


Current element: 4 Current element: 5 



'파이썬' 카테고리의 다른 글

파이썬 리스트(list)  (0) 2019.08.20
파이썬 문자열(String)  (0) 2019.08.20
파이썬 break문  (0) 2019.08.19
파이썬 while 반복문  (0) 2019.08.19
파이썬 반복문  (0) 2019.08.19
posted by 쁘로그래머 2019. 8. 19. 11:58

break는 파이썬에서 키워드로 프로그램 제어를 루프 밖으로 가져 오는 데 사용됩니다. 

break 문은 루프를 하나씩 끊습니다. 

즉 중첩 루프의 경우 내부 루프를 먼저 끊고 외부 루프로 진행합니다. 


break는 프로그램의 현재 실행을 중단하는 데 사용되고 제어는 루프 다음 ​​줄로 넘어갑니다.

주어진 조건에서 루프를 끊어야하는 경우에 일반적으로 break가 사용됩니다.


break 구문은 다음과 같습니다.

#loop statements  

break;   


# break문 예시1

list =[1,2,3,4]  

count = 1;  

for i in list:  

    if i == 4:  

        print("item matched")  

        count = count + 1;  

        break  

print("found at",count,"location");  


# 결과

item matched

found at 2 location


# break문 예시2

str = "python"  

for i in str:  

    if i == 'o':  

        break  

    print(i); 


# 결과

p

y

t

h

'파이썬' 카테고리의 다른 글

파이썬 문자열(String)  (0) 2019.08.20
파이썬 continue 문  (0) 2019.08.20
파이썬 while 반복문  (0) 2019.08.19
파이썬 반복문  (0) 2019.08.19
파이썬 조건문(if else)  (0) 2019.08.18
posted by 쁘로그래머 2019. 8. 19. 10:39

일반적으로 while 루프를 사용하면 주어진 조건이 true 인 한 코드의 일부를 실행할 수 있습니다.

반복되는 if 문으로 볼 수 있습니다. 

while 루프는 반복 횟수를 미리 알 수없는 경우에 주로 사용됩니다.


# while 구문

while expression:  

    statements  


# while문 예시

i=1;  

while i<=10:  

    print(i);  

    i=i+1;  


# 결과

1

2

3

4

5

6

7

8

9

10


# 무한 while loop

while 루프에 주어진 조건이 절대 false가되지 않으면 

while 루프는 종료되지 않고 무한 while 루프가됩니다.


while 루프에서 0이 아닌 값은 항상 참 조건을 나타내고 

0은 항상 거짓 조건을 나타냅니다. 


이러한 유형의 접근 방식은 프로그램이 방해없이 

루프에서 지속적으로 실행되도록하려는 경우에 유용합니다.


# 무한 while loop 예시

var = 1  

while var != 2:  

    i = int(input("Enter the number?"))  

    print ("Entered value is %d"%(i))  


# 결과

Enter the number?102

Entered value is 102

Enter the number?102

Entered value is 102

Enter the number?103

Entered value is 103

Enter the number?103

(infinite loop)

'파이썬' 카테고리의 다른 글

파이썬 continue 문  (0) 2019.08.20
파이썬 break문  (0) 2019.08.19
파이썬 반복문  (0) 2019.08.19
파이썬 조건문(if else)  (0) 2019.08.18
파이썬 주석  (0) 2019.08.18