-1

我几乎完成了我为帮助我学习日语课而制作的这个程序。我需要做的就是弄清楚如何跟踪我做对或做错的次数,然后打印结果。我的程序有点大,但这就是我所拥有的:(还没有按照我想要的方式工作)

RIGHT = 0
WRONG = 0

import random

def main():    
    study_more = 'y'

    while study_more == 'y':
        start()

        score()

        study_more = input('Do you want to study more? (y for yes): ')

def start():
    answer2 = int(input('Enter the chapter you would like to study (1-6): '))
    answer3 = int(input('Japanese to English? (1) or English to Japanese (2): '))
    print()

    if answer2 == 1 and answer3 == 1:
        ch1_japanese_to_english()
    elif answer2 == 1 and answer3 == 2:
        ch1_english_to_japanese()
    elif answer2 == 2 and answer3 == 1:
        ch2_japanese_to_english()
    elif answer2 == 2 and answer3 == 2:
        ch2_english_to_japanese()
    elif answer2 == 3 and answer3 == 1:
        ch3_japanese_to_english()
    elif answer2 == 3 and answer3 == 2:
        ch3_english_to_japanese()
    elif answer2 == 4 and answer3 == 1:
        ch4_japanese_to_english()
    elif answer2 == 4 and answer3 == 2:
        ch4_english_to_japanese()
    elif answer2 == 5 and answer3 == 1:
        ch5_japanese_to_english()
    elif answer2 == 5 and answer3 == 2:
        ch5_english_to_japanese()
    elif answer2 == 6 and answer3 == 1:
        ch6_japanese_to_english()
    elif answer2 == 6 and answer3 == 2:
        ch6_english_to_japanese()
    else:
        print("You've entered invalid responses.")

def score():

    ch1_japanese_to_english()
    ch1_english_to_japanese()    
    ch2_japanese_to_english()
    ch2_english_to_japanese()
    ch3_japanese_to_english()
    ch3_english_to_japanese()
    ch4_japanese_to_english()
    ch4_english_to_japanese()
    ch5_japanese_to_english()
    ch5_english_to_japanese()
    ch6_japanese_to_english()
    ch6_english_to_japanese()

    print('The number you got right: ', RIGHT)
    print('The number you go wrong: ', WRONG)

def ch1_japanese_to_english():
    dictionary = {'ano' : 'um', 'ima': 'now', 'eego' : 'english', 'hai' : 'yes', 'gakusei' : 'student', '...go' : 'language', 'kookoo' : 'high school', 'gogo' : 'pm', 'gozen' : 'am', '...sai' : 'years old', '...san' : 'mr/ms', '...ji' : "o'clock", '...jin' : 'people', 'senkoo' : 'major', 'sensei' : 'teacher', 'soo desu' : "that's right", 'daigaku' : 'college', 'denwa' : 'telephone', 'tomodachi' : 'friend', 'namae' : 'name', 'nani' : 'what', 'nihon' : 'japan', '...nensei' : 'year student', 'han' : 'half', 'bangoo' : 'number', 'ryuugakusei' : 'international student', 'watashi' : 'I', 'amerika' : 'america', 'igirisu' : 'britain', 'oosutoraria' : 'australia', 'kankoku' : 'korea', 'suweeden' : 'sweeden', 'chuugoku' : 'china', 'kagaku': 'science', 'ajia kenkyuu' : 'asian studies', 'keizai' : 'economics', 'kokusaikankei' : 'international relations', 'konpyuutaa' : 'computer', 'jinruigaku' : 'anthropology', 'seeji' : 'politics', 'bijinesu' : 'business', 'bungaku' : 'literature', 'rekishi' : 'history', 'shigoto' : 'occupation', 'isha' : 'doctor', 'kaishain' : 'office worker', 'kookoosei' : 'high school student', 'shufu' : 'house wife', 'daigakuinsei' : 'graduate student', 'bengoshi' : 'lawyer', 'okaasan' : 'mother', 'otoosan' : 'father', 'oneesan' : 'older sister', 'oniisan' : 'older brother', 'imooto' : 'younger sister', 'otooto': 'younger brother'}
    words = list(dictionary.items())
    random.shuffle(words)

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG

def ch1_english_to_japanese():
    dictionary = {'um' : 'ano', 'now' : 'ima', 'english' : 'eego', 'yes' : 'hai', 'student' : 'gakusei', 'language' : 'go', 'high school' : 'kookoo', 'pm': 'gogo', 'am' : 'gozen', 'years old': 'sai', 'mr/ms' : 'san', "o'clock" : 'ji', 'people' : 'go', 'major' : 'senkoo', 'teacher' : 'sensei', "that's right" : 'soo desu', 'college' : 'daigaku', 'telephone' : 'denwa', 'friend' : 'tomodachi', 'name' : 'namae', 'what' : 'nani', 'japan' : 'nihon', 'year student' : 'nensei', 'half' : 'han', 'number' : 'bangoo', 'international student' : 'ryuugakusei', 'I' : 'watashi', 'america' : 'amerika', 'britain' : 'igirisu' , 'australia' : 'oosutoraria', 'korea' : 'kankoku', 'sweeden' : 'suweeden', 'china' : 'chuugoku', 'science' : 'kagaku', 'asian studies' : 'ajia kenkyuu', 'economics' : 'keizai', 'international relations' : 'kokusaikankei', 'computer' : 'konpyuutaa', 'anthropology' : 'jinruigaku', 'politics' : 'seeji', 'business' : 'bijinesu', 'literature' : 'bungaku', 'history' : 'rekishi', 'occupation' : 'shigoto', 'doctor' : 'isha', 'office worker' : 'kaishain', 'high school student' : 'kookoosei', 'house wife' : 'shufu', 'graduate student' : 'daigakuinsei', 'lawyer' : 'bengoshi', 'mother' : 'okaasan', 'father' : 'otoosan', 'older sister' : 'oneesan', 'older brother' : 'oniisan', 'younger sister' : 'imooto', 'younger brother' : 'otooto'}
    words = list(dictionary.items())
    random.shuffle(words)   

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG        

def ch2_japanese_to_english():
    dictionary = {'kore' : 'this one', 'sore' : 'that one', 'are' : 'that one over there', 'dore' : 'which one', 'kono' : 'this', 'sono' : 'that', 'ano' : 'that over there', 'dono' : 'which', 'koko' : 'here', 'soko' : 'there', 'asoko' : 'over there', 'doko' : 'where', 'dare' : 'who', 'oishii' : 'delicious', 'sakana' : 'fish', 'tonkatsu' : 'pork cutlet', 'niku' : 'meat', 'menyuu' : 'menu', 'yasai' : 'vegetable', 'enpitsu' : 'pencil', 'kasa' : 'umbrella', 'kaban' : 'bag', 'kutsu' : 'shoes', 'saifu' : 'wallet', 'jiinzu' : 'jeans', 'jisho' : 'dictionary', 'jitensha' : 'bicycle', 'shinbun' : 'newspaper', 'tiishatsu' : 't-shirt', 'tokei' : 'clock', 'nooto' : 'notebook', 'pen' : 'pen', 'booshi' : 'hat', 'hon' : 'book', 'kissaten' : 'cafe', 'ginkoo' : 'bank', 'toire' : 'restroom', 'toshokan' : 'library', 'yuubinkyoku' : 'post office', 'ikura' : 'how much', 'en' : 'yen', 'takai' : 'expensive', 'irasshaimase' : 'welcome', 'onegaishimasu': 'please', 'kudasai' : 'please give me', 'jaa' : 'then', 'doozo' : 'here it is', 'doomo' : 'thank you'}
    words = list(dictionary.items())
    random.shuffle(words)   

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG        

def ch2_english_to_japanese():
    dictionary = {'this one' : 'kore', 'that one' : 'sore', 'that one over there' : 'are', 'which one' : 'dore', 'this' : 'kono', 'that' : 'sono', 'that over there' : 'ano', 'which' : 'dono', 'here' : 'koko', 'there' : 'soko', 'over there' : 'asoko', 'where' : 'doko', 'who' : 'dare', 'delicious' : 'oishii', 'fish' : 'sakana', 'pork cutlet' : 'tonkatsu', 'meat' : 'niku', 'menu' : 'menyuu', 'vegetable' : 'yasai', 'pencil' : 'enpitsu', 'umbrella' : 'kasa', 'bag' : 'kaban', 'shoes' : 'kutsu', 'wallet' : 'saifu', 'jeans' : 'jiinzu', 'dictionary' : 'jisho', 'bicycle' : 'jitensha', 'newspaper' : 'shinbun', 't-shirt' : 'tiishatsu', 'clock' : 'tokei', 'notebook' : 'nooto', 'pen' : 'pen', 'hat' : 'booshi', 'book' : 'hon', 'cafe' : 'kissaten', 'bank' : 'ginkoo', 'restroom' : 'toire', 'library' : 'toshokan', 'post office' : 'yuubinkyoku', 'how much' : 'ikura', 'yen' : 'en', 'expensive' : 'takai', 'welcome' : 'irasshaimase', 'please' : 'onegaishimasu', 'please give me' : 'kudasai', 'then' : 'jaa', 'here it is' : 'doozo', 'thank you' : 'doomo'}
    words = list(dictionary.items())
    random.shuffle(words)  

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG        

def ch3_japanese_to_english():
    dictionary = {'eiga' : 'movie','ongaku' : 'music','zasshi' : 'magazine','supootsu' : 'sports','deeto' : 'date','tenisu' : 'tenis','terebi' : 'tv','aisukuriimu' : 'ice cream','asagohan' : 'breakfast','osake' : 'alchohol','ocha' : 'green tea','koohii' : 'coffee','bangohan' : 'dinner','hanbaagaa' : 'hamburger','hirugohan' : 'lunch','mizu' : 'water','ie' : 'home','uchi' : 'my place','gakkoo' : 'school','asa' : 'morning','ashite' : 'tommorow','itsu' : 'when','kyoo' : 'today','goro' : 'at about','konban' : 'tonight','shuumatsu' : 'weekend','doyoobi' : 'saturday','nichiyoobi' : 'sunday','mainichi' : 'everyday','maiban' : 'every night','iku' : 'to go','kaeru' : 'to return','kiku' : 'to listen','nomu' : 'to drink','hanasu' : 'to speak','yomu' : 'to read','okiru' : 'to get up','taberu' : 'to eat','neru' : 'to sleep','miru' : 'to see','kuru' : 'to come','suru' : 'to do','benkyoosuru' : 'to study','ii' : 'good','hayai' : 'early','amari' : 'not much','zenzen' : 'not at all','taitei' : 'usually','chotto' : 'a little','tokidoki' : 'sometimes','yoku' : 'often','soo desu ne' : "that's right",'demo' : 'but','doo desu ka' : 'how about'}
    words = list(dictionary.items())
    random.shuffle(words)   

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG        

def ch3_english_to_japanese():
    dictionary = {'movie' : 'eiga','music' : 'ongaku','magazine' : 'zasshi','sports' : 'supootsu','date' : 'deeto','tenis' : 'tenisu','tv' : 'terebi','ice cream' : 'aisukuriimu','breakfast' : 'asagohan','alchohol' : 'osake','green tea' : 'ocha','coffee' : 'koohii','dinner' : 'bangohan','hamburger' : 'hanbaagaa','lunch' : 'hirugohan','water' : 'mizu','home' : 'ie','my place' : 'uchi','school' : 'gakkoo','morning' : 'asa','tommorow' : 'ashite','when' : 'itsu','today' : 'kyoo','at about' : 'goro','tonight' : 'konban','weekend' : 'shuumatsu','saturday' : 'doyoobi','sunday' : 'nichiyoobi','everyday' : 'mainichi','every night' : 'maiban','to go' : 'iku','to return' : 'kaeru','to listen' : 'kiku','to drink' : 'nomu','to speak' : 'hanasu','to read' : 'yomu','to get up' : 'okiru','to eat' : 'taberu','to sleep' : 'neru','to see' : 'miru','to come' : 'kuru','to do' : 'suru','to study' : 'benkyoosuru','good' : 'ii','early' : 'hayai','not much' : 'amari','not at all' : 'zenzen','usually' : 'taitei','a little' : 'chotto','sometimes' : 'tokidoki','often' : 'yoku',"that's right" : 'soo desu ne','demo' : 'but','doo desu ka' : 'how about'}
    words = list(dictionary.items())
    random.shuffle(words)  

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print() 
        return RIGHT
        return WRONG        

def ch4_japanese_to_english():
    dictionary = {'arubaito' : 'part time job','kaimono' : 'shopping','kurasu' : 'class','anata' : 'you','isu' : 'chair','inu' : 'dog','amiyage' : 'souvenir','kodomo' : 'child','gohan' : 'meal','shashin' : 'picture','tsukue' : 'desk','tegami' : 'letter','neko' : 'cat','paso' : 'bread','hito' : 'person','meeru' : 'e-mail','otera' : 'temple','kooen' : 'park','suupaa' : 'supermarket','depaato' : 'department store','basutei' : 'bus stop','byooin' : 'hospital','hoteru' : 'hotel','honya' : 'bookstore','machi' : 'city','resutoran' : 'restaurant','kinoo' : 'yesterday','jikan' : 'hours','ichijikan' : 'one hour','senshuu' : 'last week','toki' : 'when','getsuyoobi' : 'monday','kayoobi' : 'tuesday','suiyoobi' : 'wednesday','mokuyoobi' : 'thursday','kinyoobi' : 'friday','au' : 'to meet','aru' : 'there is','kau' : 'to buy','kaku' : 'to write','toru' : 'to take','matsu' : 'to wait','wakaru' : 'to understand','iru' : 'is in','gurai' : 'about','gomennasai' : "I'm sorry",'dakara' : 'so','takusan' : 'many','to' : 'together with','dooshite' : 'why','hitoride' : 'alone','migi' : 'right','hidari' : 'left','mae' : 'front', 'ushiro' : 'back', 'naka' : 'inside', 'ue' : 'on', 'shita' : 'under', 'chikaku' : 'near', 'tonari' : 'next', 'aida' : 'between'}
    words = list(dictionary.items())
    random.shuffle(words)  

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()  
        return RIGHT
        return WRONG        

def ch4_english_to_japanese():
    dictionary = {'part time job' : 'arubaito','shopping' : 'kaimono','class' : 'kurasu','you' : 'anata','chair' : 'isu','dog' : 'inu','souvenir' : 'omiyage','child' : 'kodomo','meal' : 'gohan','picture' : 'shashin','desk' : 'tsukue','letter' : 'tegami','cat' : 'neko','bread' : 'paso','person' : 'hito','e-mail' : 'meeru','temple' : 'otera','park' : 'kooen','supermarket' : 'suupaa','department store' : 'depaato','bus stop' : 'basutei','hospital' : 'byooin','hotel' : 'hoteru','bookstore' : 'honya','city' : 'machi','restaurant' : 'resutoran','yesterday' : 'kinoo','hours' : 'jikan','one hour' : 'ichijikan','last week' : 'senshuu','when' : 'toki','monday' : 'getsuyoobi','tuesday' : 'kayoobi','wednesday' : 'suiyoobi','thursday' : 'mokuyoobi','friday' : 'kinyoobi','to meet' : 'au','there is' : 'aru','to buy' : 'kau','to write' : 'kaku','to take' : 'toru','to wait' : 'matsu','to understand' : 'wakaru','is in' : 'iru','about' : 'gurai',"I'm sorry" : 'gomennasai','so' : 'dakara','many' : 'takusan','together with' : 'to','why' : 'dooshite','alone' : 'hitoride','right' : 'migi','left' : 'hidari','front' : 'mae', 'back' : 'ushiro', 'inside' : 'naka', 'on' : 'ue', 'under' : 'shita', 'near' : 'chikaku', 'next' : 'tonari', 'between' : 'aida'}
    words = list(dictionary.items())
    random.shuffle(words)  

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG        

def ch5_japanese_to_english():
    dictionary = {'umi' : 'sea','kitte' : 'postal stamps','kippu' : 'ticket','saafuin' : 'surfing','shukudai' : 'homework','tabemono' : 'food','tanjoobi' : 'birthday','tesuto' : 'test','tenki' : 'weather','nomimono' : 'drink','hagaki' : 'post card','basu' : 'bus','hikooki' : 'airplane','heya' : 'room','boku' : 'I','yasumi' : 'holiday','ruogoo' : 'travel','atarashii' : 'new','atsui' : 'hot','isogashii' : 'busy','ookii' : 'large','omoshiroi' : 'interesting','kakkoii' : 'good looking','kowai' : 'frightening','samui' : 'cold','tanoshii' : 'fun','chiisai' : 'small','tsumaranai' : 'boring','furui' : 'old','muzukashii' : 'difficult','yasashii' : 'easy','yasui' : 'cheap','kirai' : 'to dislike','kirei' : 'beautiful','genki' : 'healthy','shizuka' : 'quiet','suki' : 'to like','daikirai' : 'to hate','daisuki' : 'to love','nigiyaka' : 'lively','hima' : 'not busy','oyogu' : 'to swim','kiku' : 'to ask','noru' : 'to ride','yaru' : 'to do','dekakeru' : 'to go out','isshoni' : 'together','sugoku' : 'extreamly','sorekara' : 'and then','daijoobu' : "it's okay",'totemo' : 'very','donna' : 'what kind of'}
    words = list(dictionary.items())
    random.shuffle(words)  

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()  
        return RIGHT
        return WRONG        

def ch5_english_to_japanese():
    dictionary = {'sea' : 'umi','postal stamps' : 'kitte','ticket' : 'kippu','surfing' : 'saafuin','homework' : 'shukudai','food' : 'tabemono','birthday' : 'tanjoobi','test' : 'tesuto','weather' : 'tenki','drink' : 'nomimono','post card' : 'hagaki','bus' : 'basu','airplane' : 'hikooki','room' : 'heya','I' : 'boku','holiday' : 'yasumi','travel' : 'ryogoo','new' : 'atarashii','hot' : 'atsui','busy' : 'isogashii','large' : 'ookii','interesting' : 'omoshiroi','good looking' : 'kakkoii','frightening' : 'kowai','cold' : 'samui','fun' : 'tanoshii','small' : 'chiisai','boring' : 'tsumaranai','old' : 'furui','difficult' : 'muzukashii','easy' : 'yasashii','chaep' : 'yasui','to dislike' : 'kirai','beautiful' : 'kirei','healthy' : 'genki','quiet' : 'shizuka','to like' : 'suki','to hate' : 'dakirai','to love' : 'daisuki','lively' : 'nigiyaka','not busy' : 'hima','to swim' : 'oyogu','to ask' : 'kiku','to ride' : 'noru','to do' : 'yaru','to go out' : 'dekakeru','together' : 'isshoni','extreamly' : 'sugoku','and then' : 'sorekara',"it's okay" : 'daijoobu','very' : 'totemo','what kind of' : 'donna'}
    words = list(dictionary.items())
    random.shuffle(words)   

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print() 
        return RIGHT
        return WRONG        

def ch6_japanese_to_english():
    dictionary = {'okane' : 'money','ofuro' : 'bath','kanji' : 'kanji','kyookasho' : 'textbook','konshuu' : 'this weeek','shiidii' : 'cd','shiminbyooin' : 'municipal hospital','shiyawaa' : 'shower','tsugi' : 'next','denki' : 'electricity','densha' : 'train','nimotsu' : 'baggage','pasokon' : 'personal computer','peeji' : 'page','mado' : 'window','yoru' : 'night','raishuu' : 'next week','rainen' : 'next year','taihen' : 'tough','asobu' : 'to play','isogu' : 'to hurry','ofuronihairu' : 'to take a bath','kaesu' : 'to return','kesu' : 'to turn off','shinu' : 'to die','suwaru' : 'to sit down','tatsu' : 'to stand up','tabaiwosuu' : 'to smoke','tsukau' : 'to use','tetsudau' : 'to help','hairu' : 'to enter','motsu' : 'to carry','yasumu' : 'to be absent','akeru' : 'to open','oshieru' : 'to teach','oriru' : 'to get off','kariru' : 'to borrow','shinuru' : 'to close','shiyawaawoabiru' : 'to take a shower','to turn on' : 'tsukeru','to make a phone call' : 'denwawokakeru','wasureru' : 'to forget','tsuretekuru' : 'to bring a person','mottekuru' : 'to bringa  thing','atode' : 'later on','osoku' : 'do something late','kara' : 'because','kekkoo desu' : 'that would be fine','sugu' : 'right away','honto desu ka' : 'really?','yukkuri' : 'slowly'}
    words = list(dictionary.items())
    random.shuffle(words)   

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print() 
        return RIGHT
        return WRONG        

def ch6_english_to_japanese():
    dictionary = {'money' : 'okane','bath' : 'ofuro','kanji' : 'kanji','textbook' : 'kyookasho','this week' : 'konshuu','cd' : 'shiidii','municipal hospital' : 'shiminbyooin','shower' : 'shiyawaa','next' : 'tsugi','electricity' : 'denki','train' : 'densha','baggage' : 'nimotsu','personal computer' : 'pasokon','page' : 'peeji','window' : 'mado','night' : 'yoru','next week' : 'raishuu','next year' : 'rainen','tough' : 'taihen','to play' : 'asobu','to hurry' : 'isogu','to take a bath' : 'ofuronihairu','to return' : 'kaesu','to turn off' : 'kesu','to die' : 'shinu','to sit down' : 'suwaru','to stand up' : 'tatsu','to smoke' : 'tabaiwosuu','to use' : 'tsukau','to help' : 'tetsudau','to enter' : 'hairu','to carry' : 'motsu','to be absent' : 'yasumu','to open' : 'akeru','to teach' : 'oshieru','to get off' : 'oriru','to borrow' : 'kariru','to close' : 'shinuru','to take a shower' : 'shiyawaawoabiru','to turn on' : 'tsukeru','to make a phone call' : 'denwawokakeru','to forget' : 'wasureru','to bring a person' : 'tsuretekuru','to bring a thing' : 'mottekuru','later on' : 'atode','do something late' : 'osoku','because' : 'kara','that would be fine' : 'kekkoo desu','right away' : 'sugu','really?' : 'hontoo desu ka','slowly' : 'yukkuri'}
    words = list(dictionary.items())
    random.shuffle(words)   

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            RIGHT += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            WRONG += 1

        print()
        return RIGHT
        return WRONG        

main()
4

4 回答 4

3

I know this isn't really what you asked, so apologies if this is an actual assignment, in which case this likely won't be helpful. As others have mentioned, there is a lot of duplication in your code. The things that stand out are: the essentially identical functions that handle the actual quizzing and (to a smaller degree) the number of if statements involved in interpreting the response. The general idea of the code below is to condense all of that down into one Quiz function, and store all of the quiz words in a different module. Regarding the chapter words, since the chapter dictionaries are actually identical, just reversed, you can use:

words = {v: k for k, v in words.items()}

to 'reverse' it in the case you want to go from English -> Japanese. Then, once you are done, the scores can just be printed. This could be further optimized, but hopefully this will get you started:

import random
import quiz_vocab

CHAPTER_WORDS = {
    1: quiz_vocab.chapter_1,
    2: quiz_vocab.chapter_2
    }


def main():
    study_more = 'y'
    right = 0
    wrong = 0

    while study_more == 'y':
      chapter = int(input('Enter the chapter you would like to study (1-6): '))
      direction = int(input('Japanese to English? (1) or English to Japanese (2): '))

      # Do additional handling here to make sure they pick the right stuff
      if chapter not in CHAPTER_WORDS or direction not in (1, 2):
        print("You've entered invalid responses.")
        continue
      print()

      # Return the results of quiz into their respective variables
      # and increment the overall totals
      num_right, num_wrong = quiz(chapter, direction)
      total_right += num_right
      total_wrong += num_wrong

      # Cycle again
      study_more = input('Do you want to study more? (y for yes): ')

    # Print the final total
    print('Right: {0}\nWrong: {1}'.format(total_right, total_wrong))


def quiz(chapter, direction):
    right, wrong = 0, 0

    # Get the words corresponding to the input
    words = CHAPTER_WORDS[chapter]

    # If we decide to go English -> Japanese, reverse the dictionary
    if direction == 2:
      words = {v: k for k, v in words.items()}

    # This is all the same as yours...
    words = list(words.items())
    random.shuffle(words)

    for word, translation in words:
        print()
        print(word)
        answer = input('Enter the translation: ')

        if answer == translation:
            print('Correct!')
            right += 1
        else:
            print('Incorrect.')
            print('The correct answer is: %s.' % translation)
            wrong += 1

    # Return the right/wrong counts
    return right, wrong

main()

And the quiz_vocab module looks like:

chapter_1 = {'ano' : 'um', 'ima': 'now', 'eego' : 'english'} # continues...
于 2012-12-13T03:27:40.110 回答
2

在我看来,您希望用户选择要运行的测试(在 中start()),但随后您又从 中运行所有测试score()

如果您要跟踪全局变量中正确/错误答案的数量(不应该这样做,但这是一个不同的问题),那么该score()函数应该只打印全局变量的值。

顺便说一句,测试函数不需要返回变量的值,因为您直接修改全局变量。无论如何,双重返回语句没有意义。该函数在第一条语句上返回,永远不会到达第二条。

于 2012-12-13T03:59:14.260 回答
1

One mistake I see straight away is that the variables RIGHT and WRONG are referenced before assignment within your 'chapter' functions. Each function must include global RIGHT, WRONG

Moreover to make your program considerably smaller you can employ the following within start function:

answer1 = raw_input('Enter the chapter you would like to study (1-6): ')
answer2 = input('Japanese to English? (1) or English to Japanese (2): ')

if answer1 in range(1,7) and answer2 in [1,2]:
    functionName = 'ch{}_{}()'.format(answer1, ['japanese_to_english', 'english_tojapanese'][answer2-1])
    eval(functionName)

That would replace all the if elif clauses


One more improvement I can suggest is that rather than having a function for each chapter you can have a list of all the dictionaries(since they are the only things different in each 'chapter' function)of all the functions in serial order. Then have just one function which accepts answer1 and answer2 as arguements and accordingly selects the required dictionary. For example:

j_to_e = [ # all the japanese to english dictionaries in order as a list]
e_to_j = [ # all the english to japanese dictionaries in order as a list]
all_dicts = [j_to_e, e_to_j]

def chapter(chapterNumber, j_to_e):
    global RIGHT, WRONG
    curDict = all_dicts[j_to_e-1][chapterNumber-1] # '-1' to compensate 0 based lists
    words = list(curDict.items())
    random.shuffle(words)

    for word, translation in words:
        # all the function code 
        ...
        print()
        return RIGHT, WRONG  # RIGHT and WRONG should be returned on the same line otherwise 'return WRONG' won't be executed

The above improvements would make your code significantly concise. Hope this helps.

于 2012-12-13T03:30:12.553 回答
0

There are a number of problems with this code.

  1. Redundant code: As @Joran points out, there's an enormous amount of code duplication. Functions should be generalizable. Each function asks for user input, then checks if it matches the dictionary's stored value. The only thing that changes is the dictionary. Why not make one "quizzing" function, and pass in the dictionary?
  2. Global variables: Very bad. I'll leave it to you to research why, but your functions should not be modifying a global right/wrong count.
  3. Verbose code: An enormous if/else block is a sign of un-Pythonic code. Consider following the advice given in your previous question.

Combining all this, your generalized quizzing function should look something like this:

def quiz(word_dict):
    """ Quiz the user on a word dictionary, returning right/wrong count. """
    right = wrong = 0  # Initialize local count
    words = list(word_dict.items())
    random.shuffle(words)

    for word, translation in words:
        print(word)
        answer = input('Enter the translation: ')
        # (...)
    return (right, wrong)

A quizzing session should consist of prompting the user for the chapter, selecting the appropriate dictionary, then calling the quizzing function.

于 2012-12-13T03:28:28.533 回答