5
\$\begingroup\$

I am self taught in python. I love to play the lottery and play with numbers. I put this program together as a hobby to learn python and build something that people can use.

I used and reused code throughout the program, so some variables in different methods are the same, but still accomplish the goal.

Eventually I would like to build a GUI around this program, but I am not that far advanced yet. I was hoping to get some pointers and advice to improve the design.

__author__ = 'Daniel Ynacay'
import csv
import random
import urllib2
import time
from itertools import groupby


def main():
    # update all files for the program
    update_all_files()
    main_menu()


''' control function so that every time the main() is called the program wont download all
    the files again '''


def run_once(f):

    def wrapper(*args, **kwargs):
        if not wrapper.has_run:
            wrapper.has_run = True
            return f(*args, **kwargs)
    wrapper.has_run = False
    return wrapper


@run_once
def update_all_files():

    # this function downloads the cvs files needed for the program. 30 & 180 day numbers list.

    pb_30 = 'http://www.wvlottery.com/assets/diw/downloads/powerball-numbers-30.csv'
    mm_30 = 'http://www.wvlottery.com/assets/diw/downloads/megamillions-numbers-30.csv'
    hl_30 = 'http://www.wvlottery.com/assets/diw/downloads/hotlotto-numbers-30.csv'
    c25_30 = 'http://www.wvlottery.com/assets/diw/downloads/cash25-numbers-30.csv'
    d3_30 = 'http://www.wvlottery.com/assets/diw/downloads/daily3-numbers-30.csv'
    d4_30 = 'http://www.wvlottery.com/assets/diw/downloads/daily4-numbers-30.csv'

    pb6 = 'http://www.wvlottery.com/assets/diw/downloads/powerball-numbers-180.csv'
    mm6 = 'http://www.wvlottery.com/assets/diw/downloads/megamillions-numbers-180.csv'
    hl6 = 'http://www.wvlottery.com/assets/diw/downloads/hotlotto-numbers-180.csv'
    c26_6 = 'http://www.wvlottery.com/assets/diw/downloads/cash25-numbers-180.csv'
    d3 = 'http://www.wvlottery.com/assets/diw/downloads/daily3-numbers-180.csv'
    d4 = 'http://www.wvlottery.com/assets/diw/downloads/daily4-numbers-180.csv'
    with open('powerball-numbers-180.csv', 'wb') as a:
        a.write(urllib2.urlopen(pb6).read())
        a.close()
    with open('megamillions-numbers-180.csv', 'wb') as b:
        b.write(urllib2.urlopen(mm6).read())
        b.close()
    with open('hotlotto-numbers-180.csv', 'wb') as c:
        c.write(urllib2.urlopen(hl6).read())
        c.close()
    with open('cash25-numbers-180.csv', 'wb') as e:
        e.write(urllib2.urlopen(c26_6).read())
        e.close()
    with open('daily3-numbers-180.csv', 'wb') as f:
        f.write(urllib2.urlopen(d3).read())
        f.close()
    with open('daily4-numbers-180.csv', 'wb') as g:
        g.write(urllib2.urlopen(d4).read())
        g.close()

    with open('powerball-numbers-30.csv', 'wb') as a:
        a.write(urllib2.urlopen(pb_30).read())
        a.close()
    with open('megamillions-numbers-30.csv', 'wb') as b:
        b.write(urllib2.urlopen(mm_30).read())
        b.close()
    with open('hotlotto-numbers-30.csv', 'wb') as c:
        c.write(urllib2.urlopen(hl_30).read())
        c.close()
    with open('cash25-numbers-30.csv', 'wb') as e:
        e.write(urllib2.urlopen(c25_30).read())
        e.close()
    with open('daily3-numbers-30.csv', 'wb') as f:
        f.write(urllib2.urlopen(d3_30).read())
        f.close()
    with open('daily4-numbers-30.csv', 'wb') as g:
        g.write(urllib2.urlopen(d4_30).read())
        g.close()
    print ('All files updated!')
    main_menu()


def main_menu():
    # creates the menu
    print ('Welcome to WV Lottery Tool.')
    print ('Please choose from the following menu items')
    print ("")
    print ("Main Menu:               Type")
    print ("----------------------------")
    print ("Powerball Tool ---------- 1")
    print ("Mega Millions Tool ------ 2")
    print ("Hot Lotto Tool ---------- 3")
    print ("Cash 25 Tool  ----------- 4")
    print ("Daily Pick3 Tool -------- 5")
    print ("Daily Pick4 Tool -------- 6")
    print ("----------------------------")
    # Get user input here
    choice = raw_input('Please select your tool:')
    # --------check to see if the user entered the correct data.----------
    try:
        choice = int(choice)
    except ValueError:
        print("Please type a number from the menu above!")
        main()

    if choice <= 0 or choice >= 7:
        print ("Please choose a number from the above menu")
        main()
    # --------------continue with program-----------------------

    if choice == 1:
        powerball_tool()
    if choice == 2:
        megamillions_tool()
    if choice == 3:
        hotlotto_tool()
    if choice == 4:
        cash25_tool()
    if choice == 5:
        daily3_tool()
    if choice == 6:
        daily4_tool()


# ==================powerball_tool()==================== #


def powerball_tool():
    print('\n'*5)
    # #=====GRAB JACKPOT STRING CODE======Grabs the estimated Jackpot update
    response = urllib2.urlopen('http://www.wvlottery.com/draw-games/powerball/')
    html = response.readlines()
    jackpot = html[427]
    jackpot = jackpot.strip()  # strips whitespace from both sides
    jackpot1 = str(jackpot)[27:-7]  # This cuts the <span></span> tags.
    # #===EMD GRAB JACKPOT STRING CODE==== 'jackpot1' variable is used=====
    # ----------------------------------------------------------------
    # BUILD MENU
    print ('Welcome to the Powerball Tool!')
    print '   ', jackpot1
    print ("Tool:                   Type")
    print ("----------------------------")
    print ("Easy Pick Tool ---------- 1")
    print ("Get Winning Numbers ----- 2")
    print ("See Month of PB Numbers-- 3")
    print ("6 Month Averages PB sets- 4")
    print ("Back to Main Menu ------- 5")
    print ("----------------------------")
    print ("\n" * 1)
    val = raw_input("Please select an option:")
    try:
        val = int(val)
    except ValueError:
        print("Please type a number from the menu above!")
        powerball_tool()

    if val <= 0 or val >= 6:
        print ("Please choose a number from the above menu")
        powerball_tool()
    if val == 1:
        quick_pb_pick()
    if val == 2:
        check_pb_numbers()
        powerball_tool()
    if val == 3:
        pbfm()
        time.sleep(.3)
        powerball_tool()
    if val == 4:
        get_all_avgs()
    if val == 5:
        main()


def pb_easy_pick():
    ball1 = random_number_gen()
    ball2 = random_number_gen()
    ball3 = random_number_gen()
    ball4 = random_number_gen()
    ball5 = random_number_gen()
    pball = random.randint(1, 26)

    white_set = [ball1, ball2, ball3, ball4, ball5]
    white_sorted_set = sorted(white_set)
    turn2str = str(white_sorted_set)[1:-1]
    turnpb2str = str(pball)
    addpbtext = ', PB'
    finaloutput = turn2str + ' ' + addpbtext + ' ' + turnpb2str
    # print white_sorted_set
    # print len(white_sorted_set)
    code = [len(list(group)) for key, group in groupby(white_sorted_set)]

    if len(code) == 5:
        print finaloutput
    elif len(code) <= 4:
        pb_easy_pick()


def random_number_gen():
    ball = random.randint(1, 69)
    return ball


def quick_pb_pick():
    howmany = raw_input('How many Powerball sets? (max of 5:)')
# #--------check to see if the user entered the correct data.----------
    try:
        howmany = int(howmany)
    except ValueError:
        print("Please choose a number between 1 - 5 !")
        quick_pb_pick()

    if howmany <= 0 or howmany >= 6:
        print ("Please choose a number between 1 - 5 !")

    if howmany == 1:
        print ''
        print ''
        pb_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 2:
        print ''
        print ''
        for i in range(2):
            pb_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 3:
        print ''
        print ''
        for i in range(3):
            pb_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 4:
        print ''
        print ''
        for i in range(4):
            pb_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 5:
        print ''
        print ''
        for i in range(5):
            pb_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    powerball_tool()
# #===================BEGIN FUCNTION check_pb_numbers()=================#


def check_pb_numbers():
    with open("powerball-numbers-180.csv") as f1:
        csv_f = csv.reader(f1)
        for i, row in enumerate(csv_f):
            print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
            if i >= 1:
                raw_input('press enter to continue')
                break


# #===================END FUCNTION check_pb_numbers()=================#

def pbfm():
    f = open("powerball-numbers-30.csv")
    csv_f = csv.reader(f)
    for row in csv_f:
        print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
    raw_input('press enter to continue')

# #===========================GET ALL AVERAGAES FOR NUMBERS OVER 6 MONTHS=======start
# This function is calls 6 functions that send back the average for a 6 month period for each ball in the powerball.


def get_all_avgs():
    print avg1ball(), ',', avg2ball(), ',', avg3ball(), ',', avg4ball(), ',', avg5ball(), ', PB', avgpball()
    time.sleep(.2)
    raw_input('press enter to continue')
    powerball_tool()


def avg1ball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column1 = 1
        datatype = float
        data1 = (datatype(row[column1]) for row in incsv)
        least_value = sum(data1)/file_len('powerball-numbers-180.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg2ball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column2 = 2
        datatype = float
        data1 = (datatype(row[column2]) for row in incsv)
        least_value = sum(data1)/file_len('powerball-numbers-180.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg3ball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column3 = 3
        datatype = float
        data1 = (datatype(row[column3]) for row in incsv)
        least_value = sum(data1)/file_len('powerball-numbers-180.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg4ball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column4 = 4
        datatype = float
        data1 = (datatype(row[column4]) for row in incsv)
        least_value = sum(data1)/file_len('powerball-numbers-180.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg5ball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column5 = 5
        datatype = float
        data1 = (datatype(row[column5]) for row in incsv)
        least_value = sum(data1)/file_len('powerball-numbers-180.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avgpball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        powerballs = 6
        datatype = float
        data1 = (datatype(row[powerballs]) for row in incsv)
        least_value = sum(data1)/file_len('powerball-numbers-180.csv') - 1
        least_value = round(least_value, 1)

    return least_value
# #---------------------------- BEGIN MEGA MILLIONS CODE-------------------------------#


def megamillions_tool():
    print('\n' * 5)
    # #=====GRAB JACKPOT STRING CODE======Grabs the estimated Jackpot update
    response = urllib2.urlopen('http://www.wvlottery.com/draw-games/mega-millions/')
    html = response.readlines()
    jackpot = html[426]
    jackpot = jackpot.strip()  # strips whitespace from both sides
    jackpot1 = str(jackpot)[27:-7]  # This cuts the <span></span> tags.
    # #===EMD GRAB JACKPOT STRING CODE==== 'jackpot1' variable is used=====
    # ----------------------------------------------------------------
    # BUILD MENU
    print ('Welcome to the Mega Millions Tool!')
    print '   ', jackpot1
    print ("Tool:                   Type")
    print ("----------------------------")
    print ("Easy Pick Tool ---------- 1")
    print ("Get Winning Numbers ----- 2")
    print ("See Month of MM Numbers-- 3")
    print ("6 Month Averages MM sets- 4")
    print ("Back to Main Menu ------- 5")
    print ("----------------------------")
    print ("\n" * 1)
    val = raw_input("Please select an option:")
    try:
        val = int(val)
    except ValueError:
        print("Please type a number from the menu above!")
        megamillions_tool()

    if val <= 0 or val >= 7:
        print ("Please choose a number from the above menu")
        megamillions_tool()
    if val == 1:
        quick_mm_pick()
    if val == 2:
        check_mm_numbers()
        megamillions_tool()
    if val == 3:
        mmfm()
        time.sleep(.3)
        megamillions_tool()
    if val == 4:
        get_allmm_avgs()
    if val == 5:
        main()


def mm_easy_pick():
    ball1 = randommm_number_gen()
    ball2 = randommm_number_gen()
    ball3 = randommm_number_gen()
    ball4 = randommm_number_gen()
    ball5 = randommm_number_gen()
    pball = random.randint(1, 15)

    white_set = [ball1, ball2, ball3, ball4, ball5]
    white_sorted_set = sorted(white_set)
    turn2str = str(white_sorted_set)[1:-1]
    turnpb2str = str(pball)
    addpbtext = ', MB'
    finaloutput = turn2str + ' ' + addpbtext + ' ' + turnpb2str
    # print white_sorted_set
    # print len(white_sorted_set)
    code = [len(list(group)) for key, group in groupby(white_sorted_set)]

    if len(code) == 5:
        print finaloutput
    elif len(code) <= 4:
        mm_easy_pick()


def randommm_number_gen():
    ball = random.randint(1, 75)
    return ball


def quick_mm_pick():
    howmany = raw_input('How many Mega Millions sets? (max of 5:)')
    # #--------check to see if the user entered the correct data.----------
    try:
        howmany = int(howmany)
    except ValueError:
        print("Please choose a number between 1 - 5 !")
        quick_mm_pick()

    if howmany <= 0 or howmany >= 6:
        print ("Please choose a number between 1 - 5 !")

    if howmany == 1:
        print ''
        print ''
        mm_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')

    if howmany == 2:
        print ''
        print ''
        for i in range(2):
            mm_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 3:
        print ''
        print ''
        for i in range(3):
            mm_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 4:
        print ''
        print ''
        for i in range(4):
            mm_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 5:
        print ''
        print ''
        for i in range(5):
            mm_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    megamillions_tool()


# #===================BEGIN FUCNTION check_pb_numbers()=================#


def check_mm_numbers():
    with open("megamillions-numbers-180.csv") as f1:
        csv_f = csv.reader(f1)
        for i, row in enumerate(csv_f):
            print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
            if i >= 1:
                raw_input('press enter to continue')
                break


# #===================END FUCNTION check_pb_numbers()=================#

def mmfm():
    f = open("megamillions-numbers-30.csv")
    csv_f = csv.reader(f)
    for row in csv_f:
        print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
    raw_input('press enter to continue')
''' #===========================GET ALL AVERAGAES FOR NUMBERS OVER 6
      MONTHS=======start'''


'''# This function is calls 6 functions that send back the average for a
6 month period for each ball in the powerball.'''


def get_allmm_avgs():
    print avg1mball(), ',', avg2mball(), ',', avg3mball(), ',', avg4mball(), ',', avg5mball(), ', MB', avgmmball()
    time.sleep(.2)
    raw_input('press enter to continue')
    megamillions_tool()


def avg1mball():
    with open('powerball-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column1 = 1
        datatype = float
        data1 = (datatype(row[column1]) for row in incsv)
        least_value = sum(data1) / file_len('megamillions-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg2mball():
    with open('megamillions-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column2 = 2
        datatype = float
        data1 = (datatype(row[column2]) for row in incsv)
        least_value = sum(data1) / file_len('megamillions-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg3mball():
    with open('megamillions-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column3 = 3
        datatype = float
        data1 = (datatype(row[column3]) for row in incsv)
        least_value = sum(data1) / file_len('megamillions-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg4mball():
    with open('megamillions-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column4 = 4
        datatype = float
        data1 = (datatype(row[column4]) for row in incsv)
        least_value = sum(data1) / file_len('megamillions-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg5mball():
    with open('megamillions-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column5 = 5
        datatype = float
        data1 = (datatype(row[column5]) for row in incsv)
        least_value = sum(data1) / file_len('megamillions-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avgmmball():
    with open('megamillions-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        powerballs = 6
        datatype = float
        data1 = (datatype(row[powerballs]) for row in incsv)
        least_value = sum(data1) / file_len('megamillions-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


# #======================================End get all averages============================#

# #---------------------------- END -  MEGA MILLIONS CODE-------------------------------#


def hotlotto_tool():
    print('\n' * 5)
    # #=====GRAB JACKPOT STRING CODE======Grabs the estimated Jackpot update
    # http://www.wvlottery.com/assets/diw/downloads/hotlotto-numbers-180.csv
    response = urllib2.urlopen('http://www.wvlottery.com/draw-games/hot-lotto/')
    html = response.readlines()
    jackpot = html[426]
    jackpot = jackpot.strip()  # strips whitespace from both sides
    jackpot1 = str(jackpot)[27:-7]  # This cuts the <span></span> tags.
    # #===EMD GRAB JACKPOT STRING CODE==== 'jackpot1' variable is used=====
    # ----------------------------------------------------------------
    # BUILD MENU
    print ('Welcome to the Hot Lotto Tool!')
    print '   ', jackpot1
    print ("Tool:                   Type")
    print ("----------------------------")
    print ("Easy Pick Tool ---------- 1")
    print ("Get Winning Numbers ----- 2")
    print ("See Month of HL Numbers-- 3")
    print ("6 Month Averages HL sets- 4")
    print ("Back to Main Menu ------- 5")
    print ("----------------------------")
    print ("\n" * 1)
    val = raw_input("Please select an option:")
    try:
        val = int(val)
    except ValueError:
        print("Please type a number from the menu above!")
        hotlotto_tool()

    if val <= 0 or val >= 7:
        print ("Please choose a number from the above menu")
        hotlotto_tool()
    if val == 1:
        quick_hl_pick()
    if val == 2:
        check_hl_numbers()
        hotlotto_tool()
    if val == 3:
        hlfm()
        time.sleep(.3)
        hotlotto_tool()
    if val == 4:
        get_allhl_avgs()
    if val == 5:
        main()


def hl_easy_pick():
    ball1 = randomhl_number_gen()
    ball2 = randomhl_number_gen()
    ball3 = randomhl_number_gen()
    ball4 = randomhl_number_gen()
    ball5 = randomhl_number_gen()
    pball = random.randint(1, 19)

    white_set = [ball1, ball2, ball3, ball4, ball5]
    white_sorted_set = sorted(white_set)
    turn2str = str(white_sorted_set)[1:-1]
    turnpb2str = str(pball)
    addpbtext = ', HB'
    finaloutput = turn2str + ' ' + addpbtext + ' ' + turnpb2str
    # print white_sorted_set
    # print len(white_sorted_set)
    code = [len(list(group)) for key, group in groupby(white_sorted_set)]

    if len(code) == 5:
        print finaloutput
    elif len(code) <= 4:
        hl_easy_pick()


def randomhl_number_gen():
    ball = random.randint(1, 47)
    return ball


def quick_hl_pick():
    howmany = raw_input('How many Hot Lotto sets? (max of 5:)')
    # #--------check to see if the user entered the correct data.----------
    try:
        howmany = int(howmany)
    except ValueError:
        print("Please choose a number between 1 - 5 !")
        quick_hl_pick()

    if howmany <= 0 or howmany >= 6:
        print ("Please choose a number between 1 - 5 !")

    if howmany == 1:
        print ''
        print ''
        hl_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 2:
        print ''
        print ''
        for i in range(2):
            hl_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 3:
        print ''
        print ''
        for i in range(3):
            hl_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 4:
        print ''
        print ''
        for i in range(4):
            hl_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 5:
        print ''
        print ''
        for i in range(5):
            hl_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    hotlotto_tool()


# #===================BEGIN FUCNTION check_pb_numbers()=================#


def check_hl_numbers():
    with open("hotlotto-numbers-180.csv") as f1:
        csv_f = csv.reader(f1)
        for i, row in enumerate(csv_f):
            print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
            if i >= 1:
                raw_input('press enter to continue')
                break  # #keyword that ends this function and returns to the calling function.

# #===================END FUCNTION check_pb_numbers()=================#


def hlfm():
    f = open("hotlotto-numbers-30.csv")
    csv_f = csv.reader(f)
    for row in csv_f:
        print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
    raw_input('press enter to continue')


# #===========================GET ALL AVERAGAES FOR NUMBERS OVER 6 MONTHS=======start

# This function is calls 6 functions that send back the average for a 6 month period for each ball in the powerball.


def get_allhl_avgs():
    print avg1hlball(), ',', avg2hlball(), ',', avg3hlball(), ',', avg4hlball(), ',', avg5hlball(), ', HB', avghlball()
    time.sleep(.2)
    raw_input('press enter to continue')
    hotlotto_tool()


def avg1hlball():
    with open('hotlotto-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column1 = 1
        datatype = float
        data1 = (datatype(row[column1]) for row in incsv)
        least_value = sum(data1) / file_len('hotlotto-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg2hlball():
    with open('hotlotto-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column2 = 2
        datatype = float
        data1 = (datatype(row[column2]) for row in incsv)
        least_value = sum(data1) / file_len('hotlotto-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg3hlball():
    with open('hotlotto-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column3 = 3
        datatype = float
        data1 = (datatype(row[column3]) for row in incsv)
        least_value = sum(data1) / file_len('hotlotto-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg4hlball():
    with open('hotlotto-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column4 = 4
        datatype = float
        data1 = (datatype(row[column4]) for row in incsv)
        least_value = sum(data1) / file_len('hotlotto-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg5hlball():
    with open('hotlotto-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column5 = 5
        datatype = float
        data1 = (datatype(row[column5]) for row in incsv)
        least_value = sum(data1) / file_len('hotlotto-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avghlball():
    with open('hotlotto-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        powerballs = 6
        datatype = float
        data1 = (datatype(row[powerballs]) for row in incsv)
        least_value = sum(data1) / file_len('hotlotto-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def cash25_tool():
    print('\n' * 2)
    # BUILD MENU
    print ('Welcome to the Cash 25 Tool!')
    print '   '
    print ("Tool:                   Type")
    print ("----------------------------")
    print ("Easy Pick Tool ---------- 1")
    print ("Get Winning Numbers ----- 2")
    print ("Month of Cash 25 Numbers- 3")
    print ("6 Month Avg Cash 25 ----- 4")
    print ("Back to Main Menu ------- 5")
    print ("----------------------------")
    print ("\n" * 1)
    val = raw_input("Please select an option:")
    try:
        val = int(val)
    except ValueError:
        print("Please type a number from the menu above!")
        cash25_tool()

    if val <= 0 or val >= 7:
        print ("Please choose a number from the above menu")
        cash25_tool()
    if val == 1:
        quick_c25_pick()
    if val == 2:
        check_c25_numbers()
        cash25_tool()
    if val == 3:
        c25fm()
        time.sleep(.3)
        cash25_tool()
    if val == 4:
        get_allc25_avgs()
    if val == 5:
        main()


def c25_easy_pick():
    ball1 = random_c25number_gen()
    ball2 = random_c25number_gen()
    ball3 = random_c25number_gen()
    ball4 = random_c25number_gen()
    ball5 = random_c25number_gen()

    white_set = [ball1, ball2, ball3, ball4, ball5]
    white_sorted_set = sorted(white_set)
    turn2str = str(white_sorted_set)[1:-1]
    finaloutput = turn2str

    ''' The code below checks for duplicate numbers in the white_sorted_set variable,
        if there is less than 5 unique numbers the c25_easy_pick() is run again.'''
    code = [len(list(group)) for key, group in groupby(white_sorted_set)]
    if len(code) == 5:
        print finaloutput
    elif len(code) <= 4:
        c25_easy_pick()


def random_c25number_gen():
    ball = random.randint(1, 25)
    return ball


def quick_c25_pick():
    howmany = raw_input('How many Cash 25 sets? (max of 5:)')
    # #--------check to see if the user entered the correct data.----------
    try:
        howmany = int(howmany)
    except ValueError:
        print("Please choose a number between 1 - 5 !")
        quick_c25_pick()

    if howmany <= 0 or howmany >= 6:
        print ("Please choose a number between 1 - 5 !")

    if howmany == 1:
        print ''
        print ''
        c25_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 2:
        print ''
        print ''
        for i in range(2):
            c25_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 3:
        print ''
        print ''
        for i in range(3):
            c25_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 4:
        print ''
        print ''
        for i in range(4):
            c25_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 5:
        print ''
        print ''
        for i in range(5):
            c25_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    cash25_tool()


# #===================BEGIN FUCNTION check_c25_numbers()=================#


def check_c25_numbers():
    with open("cash25-numbers-180.csv") as f1:
        csv_f = csv.reader(f1)
        for i, row in enumerate(csv_f):
            print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
            if i >= 1:
                raw_input('press enter to continue')
                break

# #===================END FUCNTION check_pb_numbers()=================#


def c25fm():
    f = open("cash25-numbers-30.csv")
    csv_f = csv.reader(f)
    for row in csv_f:
        print '{:<13}{:^10}{:^10}{:^10}{:^10}{:^10}{:^8}'.format(*row)
    raw_input('press enter to continue')
    # #===========================GET ALL AVERAGAES FOR NUMBERS OVER 6 MONTHS=======start


# This function is calls 6 functions that send back the average for a 6 month period for each ball in the powerball.


def get_allc25_avgs():
    print avg1c25ball(), ',', avg2c25ball(), ',', avg3c25ball(), ',', avg4c25ball(), ',', avg5c25ball(), ',',\
        avgc25ball()
    time.sleep(.2)
    raw_input('press enter to continue')
    cash25_tool()


def avg1c25ball():
    with open('cash25-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column1 = 1
        datatype = float
        data1 = (datatype(row[column1]) for row in incsv)
        least_value = sum(data1) / file_len('cash25-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg2c25ball():
    with open('cash25-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column2 = 2
        datatype = float
        data1 = (datatype(row[column2]) for row in incsv)
        least_value = sum(data1) / file_len('cash25-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg3c25ball():
    with open('cash25-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column3 = 3
        datatype = float
        data1 = (datatype(row[column3]) for row in incsv)
        least_value = sum(data1) / file_len('cash25-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg4c25ball():
    with open('cash25-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column4 = 4
        datatype = float
        data1 = (datatype(row[column4]) for row in incsv)
        least_value = sum(data1) / file_len('cash25-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg5c25ball():
    with open('cash25-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column5 = 5
        datatype = float
        data1 = (datatype(row[column5]) for row in incsv)
        least_value = sum(data1) / file_len('cash25-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avgc25ball():
    with open('cash25-numbers-180.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row http://www.wvlottery.com/assets/diw/downloads/cash25-numbers-180.csv
        powerballs = 6
        datatype = float
        data1 = (datatype(row[powerballs]) for row in incsv)
        least_value = sum(data1) / file_len('cash25-numbers-180.csv') - 1
        least_value = round(least_value, 2)

    return least_value
# #---------------------------- END -  Cash 25 CODE-------------------------------#


def daily3_tool():
    print('\n' * 2)
    # ----------------------------------------------------------------
    # BUILD MENU
    print ('Welcome to the Daily 3 Tool!')
    print '   '
    print ("Tool:                   Type")
    print ("----------------------------")
    print ("Easy Pick Tool ---------- 1")
    print ("Get Winning Numbers ----- 2")
    print ("Month of Daily 3 Numbers- 3")
    print ("1 Month Avg Daily 3 ----- 4")
    print ("Back to Main Menu ------- 5")
    print ("----------------------------")
    print ("\n" * 1)
    val = raw_input("Please select an option:")
    try:
        val = int(val)
    except ValueError:
        print("Please type a number from the menu above!")
        daily3_tool()

    if val <= 0 or val >= 7:
        print ("Please choose a number from the above menu")
        daily3_tool()
    if val == 1:
        quick_d3_pick()
    if val == 2:
        check_d3_numbers()
        daily3_tool()
    if val == 3:
        d3fm()
        time.sleep(.3)
        daily3_tool()
    if val == 4:
        get_alld3_avgs()
    if val == 5:
        main()


def d3_easy_pick():
    ball1 = random_d3number_gen()
    ball2 = random_d3number_gen()
    ball3 = random_d3number_gen()

    white_set = [ball1, ball2, ball3]
    # white_sorted_set = sorted(white_set)
    turn2str = str(white_set)[1:-1]
    # turnpb2str = str(pball)
    # addpbtext = ', HB'
    # finaloutput = turn2str + ' '  ' ' + turnpb2str
    print turn2str

    # print len(white_sorted_set)


def random_d3number_gen():
    ball = random.randint(0, 9)
    return ball


def quick_d3_pick():
    howmany = raw_input('How many Daily 3 sets? (max of 5:)')
    # #--------check to see if the user entered the correct data.----------
    try:
        howmany = int(howmany)
    except ValueError:
        print("Please choose a number between 1 - 5 !")
        quick_d3_pick()

    if howmany <= 0 or howmany >= 6:
        print ("Please choose a number between 1 - 5 !")

    if howmany == 1:
        print ''
        print ''
        d3_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 2:
        print ''
        print ''
        for i in range(2):
            d3_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 3:
        print ''
        print ''
        for i in range(3):
            d3_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 4:
        print ''
        print ''
        for i in range(4):
            d3_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    if howmany == 5:
        print ''
        print ''
        for i in range(5):
            d3_easy_pick(), '\n'
        print ''
        print ''
        raw_input('press enter to continue')
    daily3_tool()


# #===================BEGIN FUCNTION check_c25_numbers()=================#


def check_d3_numbers():
    with open("daily3-numbers-180.csv") as f1:
        csv_f = csv.reader(f1)
        for i, row in enumerate(csv_f):
            print '{:<13}{:^10}{:^10}{:^10}'.format(*row)
            if i >= 1:
                raw_input('press enter to continue')
                break

# #===================END FUCNTION check_pb_numbers()=================#


def d3fm():
    f = open("daily3-numbers-30.csv")
    csv_f = csv.reader(f)
    for row in csv_f:
        print '{:<13}{:^10}{:^10}{:^10}'.format(*row)
    raw_input('press enter to continue')

    # #===========================GET ALL AVERAGAES FOR NUMBERS OVER 1 MONTH=======start


# This function is calls 6 functions that send back the average for a 6 month period for each ball in the powerball.


def get_alld3_avgs():
    print avg1d3ball(), ',', avg2d3ball(), ',', avg3d3ball()
    time.sleep(.2)
    raw_input('press enter to continue')
    daily3_tool()


def avg1d3ball():
    with open('daily3-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column1 = 1
        datatype = float
        data1 = (datatype(row[column1]) for row in incsv)
        least_value = sum(data1) / file_len('daily3-numbers-30.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg2d3ball():
    with open('daily3-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column2 = 2
        datatype = float
        data1 = (datatype(row[column2]) for row in incsv)
        least_value = sum(data1) / file_len('daily3-numbers-30.csv') - 1
        least_value = round(least_value, 2)

    return least_value


def avg3d3ball():
    with open('daily3-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column3 = 3
        datatype = float
        data1 = (datatype(row[column3]) for row in incsv)
        least_value = sum(data1) / file_len('daily3-numbers-30.csv') - 1
        least_value = round(least_value, 2)

    return least_value

# #======================================End get all averages============================#
# #---------------------------- END -  Daily 3 CODE-------------------------------#


def daily4_tool():
    print('\n' * 2)
    # ----------------------------------------------------------------
    # BUILD MENU
    print ('Welcome to the Daily 4 Tool!')
    print '   '
    print ("Tool:                   Type")
    print ("----------------------------")
    print ("Easy Pick Tool ---------- 1")
    print ("Get Winning Numbers ----- 2")
    print ("Month of Daily 4 Numbers- 3")
    print ("1 Month Avg Daily 4 ----- 4")
    print ("Back to Main Menu ------- 5")
    print ("----------------------------")
    print ("\n" * 1)
    val = raw_input("Please select an option:")
    try:
        val = int(val)
    except ValueError:
        print("Please type a number from the menu above!")
        daily4_tool()

    if val <= 0 or val >= 7:
        print ("Please choose a number from the above menu")
        daily4_tool()
    if val == 1:
        quick_d4_pick()
    if val == 2:
        check_d4_numbers()
        daily4_tool()
    if val == 3:
        d4fm()
        time.sleep(.3)
        daily4_tool()
    if val == 4:
        get_alld4_avgs()
    if val == 5:
        main()


def d4_easy_pick():
    ball1 = random_d4number_gen()
    ball2 = random_d4number_gen()
    ball3 = random_d4number_gen()
    ball4 = random_d4number_gen()

    white_set = [ball1, ball2, ball3, ball4]
    # white_sorted_set = sorted(white_set)
    turn2str = str(white_set)[1:-1]
    # turnpb2str = str(pball)
    # addpbtext = ', HB'
    # finaloutput = turn2str + ' '  ' ' + turnpb2str
    print turn2str

    # print len(white_sorted_set)


def random_d4number_gen():
    ball = random.randint(0, 9)
    return ball


def quick_d4_pick():
    howmany = raw_input('How many Daily 4 sets? (max of 5:)')
    # #--------check to see if the user entered the correct data.----------
    try:
        howmany = int(howmany)
    except ValueError:
        print("Please choose a number between 1 - 5 !")
        quick_d4_pick()

    if howmany <= 0 or howmany >= 6:
        print ("Please choose a number between 1 - 5 !")

    if howmany == 1:
        print ''
        d4_easy_pick(), '\n'
        print ''
        raw_input('press enter to continue')
    if howmany == 2:
        print ''
        for i in range(2):
            d4_easy_pick(), '\n'
        print ''
        raw_input('press enter to continue')
    if howmany == 3:
        print ''
        for i in range(3):
            d4_easy_pick(), '\n'
        print ''
        raw_input('press enter to continue')
    if howmany == 4:
        print ''
        for i in range(4):
            d4_easy_pick(), '\n'
        print ''
        raw_input('press enter to continue')
    if howmany == 5:
        print ''
        for i in range(5):
            d4_easy_pick(), '\n'
        print ''
        raw_input('press enter to continue')
    daily4_tool()


# #===================BEGIN FUCNTION check_c25_numbers()=================#


def check_d4_numbers():
    with open("daily4-numbers-180.csv") as f1:
        csv_f = csv.reader(f1)
        for i, row in enumerate(csv_f):
            print '{:<13}{:^10}{:^10}{:^10}{:^10}'.format(*row)
            if i >= 1:
                raw_input('press enter to continue')
                break

# #===================END FUCNTION check_pb_numbers()=================#


def d4fm():
    f = open("daily4-numbers-30.csv")
    csv_f = csv.reader(f)
    for row in csv_f:
        print '{:<13}{:^10}{:^10}{:^10}{:^10}'.format(*row)
    raw_input('press enter to continue')

    # #===========================GET ALL AVERAGAES FOR NUMBERS OVER 6 MONTHS=======start


# This function is calls 6 functions that send back the average for a 6 month period for each ball in the powerball.


def get_alld4_avgs():
    print avg1d4ball(), ',', avg2d4ball(), ',', avg3d4ball(), ',', avg4d4ball()
    time.sleep(.2)
    raw_input('press enter to continue')
    daily4_tool()


def avg1d4ball():
    with open('daily4-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column1 = 1
        datatype = float
        data1 = (datatype(row[column1]) for row in incsv)
        least_value = sum(data1) / file_len('daily4-numbers-30.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg2d4ball():
    with open('daily4-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column2 = 2
        datatype = float
        data1 = (datatype(row[column2]) for row in incsv)
        least_value = sum(data1) / file_len('daily4-numbers-30.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg3d4ball():
    with open('daily4-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column3 = 3
        datatype = float
        data1 = (datatype(row[column3]) for row in incsv)
        least_value = sum(data1) / file_len('daily4-numbers-30.csv') - 1
        least_value = round(least_value, 1)

    return least_value


def avg4d4ball():
    with open('daily4-numbers-30.csv', 'rb') as inf:
        has_header = csv.Sniffer().has_header(inf.read(1024))
        inf.seek(0)  # rewind
        incsv = csv.reader(inf)
        if has_header:
            next(incsv)  # skip header row
        column4 = 4
        datatype = float
        data1 = (datatype(row[column4]) for row in incsv)
        least_value = sum(data1) / file_len('daily4-numbers-30.csv') - 1
        least_value = round(least_value, 1)

    return least_value

# #======================================End get all averages============================#
# #---------------------------- END -  Daily 4 CODE-------------------------------#


def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
main()
\$\endgroup\$
1
  • \$\begingroup\$ I don't know python, but won't most of these functions stack overflow given sufficient time and (in)correct inputs? Most of them seem to call themselves at one point or another. \$\endgroup\$ Commented Aug 11, 2017 at 23:58

3 Answers 3

4
\$\begingroup\$

First, if you use the context manager (the with statement), it will safely close your file for you, so in

with open('powerball-numbers-180.csv', 'wb') as a:
    a.write(urllib2.urlopen(pb6).read())
    a.close()

(and similar blocks) the statement

    a.close()

is useless.


Second, your long series of blocks, starting with

with open('powerball-numbers-180.csv', 'wb') as a:
    a.write(urllib2.urlopen(pb6).read())
    a.close()
with open('megamillions-numbers-180.csv', 'wb') as b:
    b.write(urllib2.urlopen(mm6).read())
    b.close()
with open('hotlotto-numbers-180.csv', 'wb') as c:
    c.write(urllib2.urlopen(hl6).read())
    c.close()

will be more clear if you first create a lists of the corresponding files and urls, something as

files_urls = [
    ('powerball-numbers-180.csv',    pb6),
    ('megamillions-numbers-180.csv', mm6),
    ('hotlotto-numbers-180.csv',     h16),
]

and then use them in a loop:

for file, url in files_urls:
    with open(file, 'wb') as f:
        f.wirte(urllib2.urlopen(url).read())
\$\endgroup\$
2
  • \$\begingroup\$ files_urls = [ ('powerball-numbers-180.csv', pb6), ('megamillions-numbers-180.csv', mm6), ('hotlotto-numbers-180.csv', h16), ] <----not familiar with this, does this auto assign variables to the files like this?? \$\endgroup\$
    – Danny
    Commented Aug 14, 2017 at 1:52
  • \$\begingroup\$ @Danny - No, this is only a list of tuples (particularly pairs) then used in the loop for file, url in files_urls: where first members of pairs are sequentially assigned to the variable file and second ones to the variable url. \$\endgroup\$
    – MarianD
    Commented Aug 14, 2017 at 2:22
3
\$\begingroup\$

Try keeping the DRY principle (Don't Repeat Yourself):

You use the same csv names both for remote sites, as in this excerpt:

pb_30 = 'http://www.wvlottery.com/assets/diw/downloads/powerball-numbers-30.csv'
mm_30 = 'http://www.wvlottery.com/assets/diw/downloads/megamillions-numbers-30.csv'
hl_30 = 'http://www.wvlottery.com/assets/diw/downloads/hotlotto-numbers-30.csv'

and for your local files, as in this excerpt:

with open('powerball-numbers-30.csv', 'wb') as a:
    a.write(urllib2.urlopen(pb_30).read())
    a.close()
with open('megamillions-numbers-30.csv', 'wb') as b:
    b.write(urllib2.urlopen(mm_30).read())
    b.close()
with open('hotlotto-numbers-30.csv', 'wb') as c:
    c.write(urllib2.urlopen(hl_30).read())
    c.close()

Why don't make a list of them, e. g.

names = [
    'powerball-numbers-30.csv',
    'megamillions-numbers-30.csv',
    'hotlotto-numbers-30.csv',
    ]

give a name for the common prefix

prefix = 'http://www.wvlottery.com/assets/diw/downloads/'

and then (see my previous answer - this is just the next step in the improvement) use that list in a loop

for name in names:
    with open(name, 'wb') as f:
        f.wirte(urllib2.urlopen(prefix + name).read())

(So the assignments as in the first excerpt of this answer - for names pb_30, mm_30, and so on become superfluous and may be deleted from your code.)

\$\endgroup\$
0
1
\$\begingroup\$

Notes to the definition of your function quick_d3_pick():

if howmany <= 0 or howmany >= 6:

Simpler:

if howmany not in range(1, 6):

Instead of

print ''

you may use simply

print

Instead of long if series starting with

if howmany == 1:
    print ''
    print ''
    d3_easy_pick(), '\n'
    print ''
    print ''
    raw_input('press enter to continue')
if howmany == 2:
    print ''
    print ''
    for i in range(2):
        d3_easy_pick(), '\n'
    print ''
    print ''
    raw_input('press enter to continue')

you may use the howmany value without testing it in if statements - directly in range() function of the for loop, so your whole series will be reduced to

print
print
for __ in range(howmany):
    d3_easy_pick(), '\n'
print
print
raw_input('press enter to continue')

Note the use of __ (2 consecutive underlines characters) instead of the name i in the for loop - it is a good practice to use it in the place of not used names.

\$\endgroup\$
4
  • \$\begingroup\$ Yes, i am just now getting comfortable with the range(). All very good advice, and will make me be a better python coder. Learning a lot from your comments, so thank you very much. \$\endgroup\$
    – Danny
    Commented Aug 11, 2017 at 18:30
  • \$\begingroup\$ You're welcome. Python is a beautiful language. \$\endgroup\$
    – MarianD
    Commented Aug 11, 2017 at 19:06
  • 1
    \$\begingroup\$ The first suggestion may also be if not 0 < howmany < 6 \$\endgroup\$
    – Quelklef
    Commented Aug 12, 2017 at 0:29
  • \$\begingroup\$ @Quelklef - May be - it is a matter of personal style. For me it is a little less straightforward. \$\endgroup\$
    – MarianD
    Commented Aug 12, 2017 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.