기본 

def print_table(number):
    times = range(1,number+1)
    for i in times:
        print("\t"+str(i),end="")       # \t를 해줘야 저렇게 간격이 띄워진다. 
    print()                                     # 줄바꿈해줘야 함. 
    
    for i in times:
        print(i, end="")
        for j in times:
            print("\t"+str(i*j),end="")
        print()  
           
print_table(9)

 

응용한 버젼


def print_table(number):
    times = range(1,number+1)

    for i in times:
        print("\t"+str(i),end="")
    print()

    for i in times:
        print(i,end="")
        for j in times:
            if i==j:
                print("\t"+"-",end="")
            elif i<j:
                print("\t"+"+",end="")
            elif i%2==0 and j%2==0:
                print("\t"+"*",end="")
            else:
                print("\t"+str(i+j),end="")
        print()

print_table(9)

'Python' 카테고리의 다른 글

or 연산자 사용할 때 주의점.  (0) 2019.04.15
파이썬에서 dir과 help함수 이용하기  (0) 2019.04.12
random 모듈 관련 함수  (0) 2019.04.11
중첩 for문  (0) 2019.04.06
자료형 주의  (0) 2019.03.31
Posted by sozero
,

계산기를 사용할때 중간에 멈추기 위해 q 또는 Q를 사용하여 중단하기 위해 or 연산자를 사용.

 

 

while True :
    num1 = int(input("첫번째 수 입력 :"))
    num2 = int(input("두번째 수 입력 :"))
    oper = input("연산자 입력 :")

    if oper == "q" or oper == "Q":
# 반드시 or를 쓸땐 Var == value1 or Var == value2

# Var == value1 or value2   로하면 오류메세지도 안나고 오류가 남. 조심할 것. 
        break
    elif oper == "+" :
        print("%d + %d = %d" %(num1, num2, num1 + num2 ))
    elif oper == "-" :
        print("%d - %d = %d" %(num1, num2, num1 - num2 ))
    elif oper == "*" :
        print("%d * %d = %d" %(num1, num2, num1 * num2 ))
    elif oper == "/" :
        print("%d / %d = %d" %(num1, num2, num1 / num2 ))
    

'Python' 카테고리의 다른 글

파이썬으로 테이블 그리기  (0) 2019.04.30
파이썬에서 dir과 help함수 이용하기  (0) 2019.04.12
random 모듈 관련 함수  (0) 2019.04.11
중첩 for문  (0) 2019.04.06
자료형 주의  (0) 2019.03.31
Posted by sozero
,

급하게 어떤 함수나 모듈에 대한 정보를 python 내에서 알아보는 법. 

바로 dir과 help 함수를 이용해보는 것. 

 

dir(클래스) 를 입력할 경우 해당 클래스에 내장되어있는 함수들의 이름 리스트를 알아낼 수 있다. 

help(클래스)나 help(함수)를 할 경우 해당 클래스나 함수의 정보를 얻을 수 있지만 불필요한 정보까지 얻을 수 있다. 

필요한 정보만 골라내기 위해서 

help(클래스.함수)를 통해 빠르게 정보를 알아내자. 

=> help(random.randrange)

 

 

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> help(list.append)
Help on method_descriptor:

append(self, object, /)
    Append object to the end of the list.

>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_BuiltinMethodType', '_MethodType', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_inst', '_itertools', '_log', '_os', '_pi', '_random', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> help(random.randrange)
Help on method randrange in module random:

randrange(start, stop=None, step=1, _int=<class 'int'>) method of random.Random instance
    Choose a random item from range(start, stop[, step]).
    
    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.

>>> help(random.randint)
Help on method randint in module random:

randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.

>>> help(dir)
Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings
    
    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

'Python' 카테고리의 다른 글

파이썬으로 테이블 그리기  (0) 2019.04.30
or 연산자 사용할 때 주의점.  (0) 2019.04.15
random 모듈 관련 함수  (0) 2019.04.11
중첩 for문  (0) 2019.04.06
자료형 주의  (0) 2019.03.31
Posted by sozero
,

random 모듈 관련 함수

Python 2019. 4. 11. 13:50

먼저 import random 을 선언.

 

1) random( )

0~1사이의 랜덤 실수를 리턴한다. 

>>> random.random()
0.961592837296599
>>> random.random()
0.7294672568371695

 

 

2) uniform( )

2개의 숫자 사이의 랜덤 실수를 리턴한다 

 

>>> random.uniform(1,10)
4.708655700075207
>>> random.uniform(1,10)
8.72419066105807

 

3) randint( ) 

2개의 숫자 사이의 랜덤 정수를 리턴 (2번째 인자로 넘어온 정수도 범위에 포함한다.)

 

>>> random.randint(1,10)
3
>>> random.randint(1,2)
2
>>> random.randint(1,2)
1

 

4)randrange( )

range(start, stop, step) 모양.  start는 포함되나 stop의 수는 포함되지 않는다. 

 

>>> random.randrange(1, 10, 3)
1
>>> random.randrange(1, 10, 3)
4
>>> random.randrange(1, 10, 3)
7
>>> random.randrange(1, 10, 3)
4

 

 

5) choice( )

랜덤하게 하나의 원소를 선택한다. 

 

>>> random.choice('abcdefghijklmn')
'f'
>>> random.choice('abcdefghijklmn')
'd'
>>> random.choice('abcdefghijklmn')
'l'

 

6) sample( )

random.sample(range(a,b),c)

=>a이상 b미만의 c개값을 리스트 형식으로 반환한다. (중복 없다)

시퀀스 자료형을 인자로 전달받아 임의의 값(난수)을 필요한 개수만큼 리스트로 반환.

특정 영역의 숫자를 중복없이 리턴하기 때문에 로또 번호 생성에 사용 가능

 

>>> random.sample([1,2,3,4,5],3)
[1, 4, 2]
>>> random.sample([1,2,3,4,5],3)
[5, 1, 4]
>>> random.sample([1,2,3,4,5],3)
[1, 2, 4]
>>> random.sample([1,2,3,4,5],3)
[4, 5, 3]

 

    

 

7) shuffle( ) 

원소의 순서를 랜덤하게 바꾼다. 

 

>>> items = [1,2,3,4,5,6,7]
>>> random.shuffle(items)
>>> items
[6, 5, 2, 3, 4, 7, 1]
>>> items
[6, 5, 2, 3, 4, 7, 1]

 

 

 

 

출처

http://www.daleseo.com/python-random/

 

[파이썬] random 모듈 사용법

파이썬의 random 모듈은 랜덤 숫자를 생성 뿐만 아니라 다양한 랜덤 관련 함수를 제공합니다. 모듈 임포트우선 random 모듈을 사용하려면 임포트해야 합니다. 1import random random() 함수0부터 1사이의 랜덤 실수를 리턴합니다. 12>>> random.random() # Random float x, 0.0

www.daleseo.com

https://withcoding.com/88

 

파이썬 random 모듈, 함수 사용법 정리 (파이썬 랜덤 모듈, 난수 생성)

파이썬(Python)에서 난수를 만들기 위해서는 random 모듈을 사용해야 합니다. 이 랜덤 모듈에서 가장 많이 사용되는 함수(메소드)를 정리해봅니다. 파이썬 랜덤 모듈 random, randint, randrange 함수 import ran..

withcoding.com

 

'Python' 카테고리의 다른 글

or 연산자 사용할 때 주의점.  (0) 2019.04.15
파이썬에서 dir과 help함수 이용하기  (0) 2019.04.12
중첩 for문  (0) 2019.04.06
자료형 주의  (0) 2019.03.31
if문에서 or를 사용할 때 주의할 점  (0) 2019.03.31
Posted by sozero
,

중첩 for문

Python 2019. 4. 6. 01:44

이해가지 않을때 도움 된 사이트 

 

https://dojang.io/mod/page/view.php?id=2259

'Python' 카테고리의 다른 글

or 연산자 사용할 때 주의점.  (0) 2019.04.15
파이썬에서 dir과 help함수 이용하기  (0) 2019.04.12
random 모듈 관련 함수  (0) 2019.04.11
자료형 주의  (0) 2019.03.31
if문에서 or를 사용할 때 주의할 점  (0) 2019.03.31
Posted by sozero
,

자료형 주의

Python 2019. 3. 31. 22:49

# 사용자에게서 주민등록번호 앞자리 6자리를 받아 생일을 출력하고자 한 코드 

# mm = user_age[2:4]에서 한자리수의 월을 출력할때 앞에 0이 붙는 것을 어떻게 없앨 수 없어 에러가 계속해서 생겨남.

# 이는 변수의 value를 int화한 후 다시 str화하면 원활하게 작동함.

 

def makeBirthdayString(user_age):
    yyyy = "19"+ user_age[:2]
    mm = str(int(user_age[2:4]))
    dd = str(int(user_age[4:]))
    return "당신의 생일은"+" "+ yyyy + "년"+" " + mm + "월"+" " + dd + "일 입니다"


age = input("주민등록번호 앞자리 6자리를 입력해 주세요 :")
print(makeBirthdayString(age))

 

 

 

여기서도 할인율을 적용하기 위해 값에 소수점이 나오는 것을 방지하기 위해 int를 넣어줘야 한다.

그렇지 않으면 TypeError : can't multiply sequence by non-int of type 'float'

가 나올 것임. 

 

'Python' 카테고리의 다른 글

or 연산자 사용할 때 주의점.  (0) 2019.04.15
파이썬에서 dir과 help함수 이용하기  (0) 2019.04.12
random 모듈 관련 함수  (0) 2019.04.11
중첩 for문  (0) 2019.04.06
if문에서 or를 사용할 때 주의할 점  (0) 2019.03.31
Posted by sozero
,

 # 사용자에게 주민등록번호를 입력받아 남성인지 여성인지 분류하기

# 어디서 오류가 났는지 확인하고자 파이썬 셸-인터프리터식으로 코드를 분석하고자 함.

 

# 결과값이 여성으로 나와야하는데 남성으로 나와 곤란하였음.

 

# 8번째 코드 

if gender == '1' or '3' :     이 문제였음.

이를 if gender == '1' or gender == '3'

 

으로 고칠 경우 원활한 작동이 이뤄짐. 

'Python' 카테고리의 다른 글

or 연산자 사용할 때 주의점.  (0) 2019.04.15
파이썬에서 dir과 help함수 이용하기  (0) 2019.04.12
random 모듈 관련 함수  (0) 2019.04.11
중첩 for문  (0) 2019.04.06
자료형 주의  (0) 2019.03.31
Posted by sozero
,