python 함수 (아날로그 산수 게임)

3777 단어 python
이 프로그램은 매번 랜덤으로 두 개의 10 이내의 정수를 생성한 다음에 +-조작을 한 다음에 사용자 입력 결과를 판단하고operator 모듈의dd,sub python Document operator를 사용합니다.
from operator import add,sub
from random import randint,choice
ops={'+':add,'-':sub}
def init():
    op=choice('+-')#          
    nums=[randint(1,10) for x in range(2)]
    # nums.sort(reverse=True)
    #    *,            
    #                    
    ans=ops[op](*nums)
    pr='%d %s %d=' % (nums[0],op,nums[1])
    oops=0;
    while True:
        try:
            if int(input(pr))==ans:
                print('correct')
                break;
            if oops==2:
                print('answrer:
%s %d'
% (pr,ans)) else : print('incorrect... try again') oops+=1 except(KeyboardInterrupt,EOFError,ValueError): print('invalid input... try again') def main(): while True: init() try: opt=input('Again [y/n]?').lower() if opt and opt[0]=='n': break except(KeyboardInterrupt,EOFError): break if __name__=='__main__': main()

다음은 사전이 매개 변수로 함수를 호출하는 간단한 예이다
def test(**a):
    for x in a:
        print(x,':',a[x])
if __name__=='__main__':
    a={'x':1,'y':2,'z':3}
    test(**a)

좋은 웹페이지 즐겨찾기