search
HomeBackend DevelopmentPython TutorialHow to run a line of code multiple times based on input?

How to run a line of code multiple times based on input?

Question content

Using python, I'm trying to find a faster way to run randint multiple times based on input without having to write out each input possibility. This is a dice roller for tabletop games. code show as below

import random
from random import randint

i1=input("what type of die?: ")
i2=input("how many times?:")

roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
    
    if i1=="d6":
        if i2=="1":
            value1=randint(1,6)
            print(value1)
            roll_again = input("roll again?")
        if i2=="2":
            value1=randint(1,6)
            value2=randint(1,6)
            print(value1,value2)
            roll_again = input("roll again?")
        if i2=="3":
            value1=randint(1,6)
            value2=randint(1,6)
            value3=randint(1,6)
            print(value1,value2,value3)
            roll_again = input("roll again?")
        if i2=="4":
            value1=randint(1,6)
            value2=randint(1,6)
            value3=randint(1,6)
            value4=randint(1,6)
            print(value1,value2,value3,value4)
            roll_again = input("roll again?")
    
    elif i1=="d4":
        if i2=="1":
            value1=randint(1,4)
            print(value1)
            roll_again = input("roll again?")
        if i2=="2":
            value1=randint(1,4)
            value2=randint(1,4)
            print(value1,value2)
            roll_again = input("roll again?")
        if i2=="3":
            value1=randint(1,4)
            value2=randint(1,4)
            value3=randint(1,4)
            print(value1,value2,value3)
            roll_again = input("roll again?")
        if i2=="4":
            value1=randint(1,4)
            value2=randint(1,4)
            value3=randint(1,4)
            value4=randint(1,4)
            print(value1,value2,value3,value4)
            roll_again = input("roll again?")

I'm continuing to add other dice types. Basically I want to be able to put 100 as input and have it give me 100 randint without having to manually code until if i2=="100" but still keep the different "ifs". I also want to print the sum of the rolling values

For the second part, I tried print(sum(value1,value2)) but since value1 and value2 are not integers, I got the error


Correct answer


If I understand correctly, you want to simplify the operation of the algorithm.

My code works as follows.

The user enters the type of dice (e.g. "d6", "d10") and the number of throws. The program checks that the entered die is of the correct type (starts with "d" and has a positive number of sides).

If the data is correct, the program will generate the given number of throws using the given dice, save the results to a list of values ​​and print them.

The program calculates the sum of the obtained results and prints it.

The program asks the user if he wishes to proceed with another throw.

If the user decides to roll again, the program will repeat the process of generating and printing the result.

If the user enters incorrect data (for example, the dice is in the wrong format or the number of rolls is less than 1), the program will print an error message.

I assume you will modify this code to suit your needs

from random import randint

i1 = input("Enter the type of dice (e.g., d6, d4): ")
i2 = int(input("Enter the number of dice rolls: "))

if i1.startswith("d") and i2 > 0:
    dice_type = int(i1[1:])
    values = []

    for _ in range(i2):
        values.append(randint(1, dice_type))

    print(*values)
    print("Sum:", sum(values))
    roll_again = input("Roll again? (yes/no): ").lower()

    while roll_again == "yes":
        values = []

        for _ in range(i2):
            values.append(randint(1, dice_type))

        print(*values)
        print("Sum:", sum(values))
        roll_again = input("Roll again? (yes/no): ").lower()

else:
    print("Invalid input. Please enter a valid dice type and number of rolls.")

The above is the detailed content of How to run a line of code multiple times based on input?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools