Przepraszam z góry, jeśli mój kod jest słabo napisany. Próbuję zrobić program, który umożliwia dodawanie numerów do listy, a następnie podaj użytkownikowi dodanie więcej numerów do tej samej listy. Oto, co mam:
inputgameoption="y"
while inputgameoption=="y":
###this is where the user inputs the first number
creepscore=eval(input("Finished a game? Type your creep score first then press enter. Next, enter the duration of your game and press enter "))
###this is where the user inputs the second number
gameduration=eval(input("Game duration should be rounded to the nearest minute, [ex. 24:25 becomes 24] "))
cs=[]
times=[]
cs.append(creepscore)
times.append(gameduration)
inputgameoption=input("Enter another game?")
Działa dobrze po raz pierwszy, ale jeśli powiesz, że chcesz wprowadzić więcej liczb (wprowadź inne wejście gry), zastępuje swoje pierwsze wejście za pomocą drugiego wejścia, a lista pozostanie z tylko jedną numbe. Dzięki, jestem Newbie Pythona.
3 odpowiedzi
Użyj pętli while
. Wystarczy rzucić swoje wejście do int
zamiast używać eval
.
# initialize the arrays outside the loop
cs = []
times = []
# loop for input until the user doesn't enter 'y'
inputgameoption = 'y'
while(inputgameoption == 'y'):
creepscore = int(input("Finished a game? Type your creep score first then press enter. Next, enter the duration of your game and press enter "))
gameduration = int(input("Game duration should be rounded to the nearest minute, [ex. 24:25 becomes 24] "))
# add their current inputs
cs.append(creepscore)
times.append(gameduration)
# prompt to continue
inputgameoption=input("Enter another game?")
print 'creepscores : ', cs
print 'times : ', times
Twoje linie cs=[]
i times=[]
zastępują cokolwiek w tych listach z pustymi. Przenieść te przed pętlą.
Formatowanie kodu jest raczej niejasne, jednak wystarczy zdefiniować listy przed zachowaniem pętli:
inputgameoption="y"
cs=[]
times=[]
while inputgameoption=="y":
###this is where the user inputs the first number
creepscore=int(input("Finished a game? Type your creep score first then press enter. Next, enter the duration of your game and press enter "))
###this is where the user inputs the second number
gameduration=int(input("Game duration should be rounded to the nearest minute, [ex. 24:25 becomes 24] "))
cs.append(creepscore)
times.append(gameduration)
inputgameoption=input("Enter another game?")
Podobne pytania
Nowe pytania
python
Python to wielozadaniowy, wielozadaniowy język programowania dynamicznie typowany. Został zaprojektowany tak, aby był szybki do nauczenia się, zrozumienia i użycia oraz wymuszania czystej i jednolitej składni. Należy pamiętać, że Python 2 oficjalnie nie jest obsługiwany od 01-01-2020. Mimo to, w przypadku pytań Pythona specyficznych dla wersji, dodaj znacznik [python-2.7] lub [python-3.x]. Korzystając z wariantu Pythona (np. Jython, PyPy) lub biblioteki (np. Pandas i NumPy), należy umieścić go w tagach.