简体   繁体   中英

What better ways could i have written this python code

Hello everyone I'm new to stack overflow and Python i have only been coding in Python for a little under a month now. I am all about writing leaner and more effective code i was just wondering how i could possibly make this better. Any help would be greatly appreciated thank you in advance.

<!-- language-all: lang-python -->

from __future__ import division
from random import randint

die1 = 0
die2 = 0
die3 = 0
die4 = 0
die5 = 0
die6 = 0

for rolls in range(0, 10000):
    while True:
        rand = randint(1, 6)
        if rand == 1:
            die1 += 1
            break
        elif rand == 2:
            die2 += 1
            break
        elif rand == 3:
            die3 += 1
            break
        elif rand == 4:
            die4 += 1
            break
        elif rand == 5:
            die5 += 1
            break
        elif rand == 6:
            die6 += 1
            break
print 'the result was'
print 'die1 =', die1
print 'die2 =', die2
print 'die3 =', die3
print 'die4 =', die4
print 'die5 =', die5
print 'die6 =', die6

Using a list would make your code much more concise. For example,

from random import randint

dice = [0 for i in range(6)]

for rolls in range(0, 10000):
    rand = randint(1, 6)
    dice[rand-1] += 1

print 'the result was'
print dice

Use a list, for one. I've got no access to an interpreter right now, but something like this will do.

dice = [0, 0, 0, 0, 0, 0]

for rolls in range(0, 10000):
    rand = randint(1, 6)
    dice[rand] = dice[rand] + 1

print 'the result was'
for i in range(0, 6):
    print 'die', i, '=', dice[i]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM