2017-05-12 2 views
1

Ich bin neu in Python und Programmierung und ich versuche, das Spiel "Raten Sie die Zahl" zu machen. Ich habe es funktioniert, aber ich möchte die Option hinzufügen, um das Spiel mit der Bremse Anweisung zu schließen. Ich habe seit 2 Tagen versucht, aber ich denke, ich bin steckengeblieben. HierRate die Zahl in Python. Option zum Schließen des Spiels

ist der Code, der funktioniert (ohne die Möglichkeit, das Spiel zu schließen):

import random 
attempts = 0 
secretNumber = random.randint(1,100) 
while True: 
    print("Guess a number between 1 and 100") 
    guess=input() 
    guess = int(guess) 
    attempts = attempts + 1 
    if guess >100 or guess<=0: 
     attempts = attempts - 1 
     print("Not allowed.Only numbers between 1 and 100 allowed! \n") 
    elif guess < secretNumber and guess >0: 
     print("Nope!Try a higher number! \n") 
    elif guess > secretNumber and guess <100: 
     print("Nope!Try a lower number \n") 
    if guess == secretNumber: 
     break 

if guess == secretNumber: 
      attempts = str(attempts) 
print("Congratulations you found it after " + attempts + " attempts") 

-Code (mit der Option, das Spiel zu schließen), dass nicht funktioniert:

import random 
attempts = 0 
secretNumber = random.randint(1,100) 
while True: 
    print("Guess a number between 1 and 100. You can exit game anytime by typing quit ") 
    stop=input() 
    stop=str(stop) 
    if stop == "quit": 
     break 
     print("You quitted the game") 
    else: 
      continue 
    guess=input() 
    guess = int(guess) 
    attempts = attempts + 1 
    if guess >100 or guess<=0: 
     attempts = attempts - 1 
     print("Not allowed.Only numbers between 1 and 100 allowed! \n") 
    elif guess < secretNumber and guess >0: 
     print("Nope!Try a higher number! \n") 
    elif guess > secretNumber and guess <100: 
     print("Nope!Try a lower number \n") 
    if guess == secretNumber: 
     break 

if guess == secretNumber: 
      attempts = str(attempts) 
print("Congratulations you found it after " + attempts + " attempts") 

Ich bin Entschuldigung für die lange Post, jede Hilfe auf, was ich falsch mache oder sogar einen anderen Ansatz, um dies zu erreichen mit der brechen Anweisung und ohne die Def-Funktion verwenden wird sehr geschätzt werden. Vielen Dank im Voraus.

+0

Entfernen Sie Ihr 'else: continue'. Mit 'continue 'wird der Code am Anfang der Schleife erneut fortgesetzt. –

+0

Und 'print' vor dem Ausbrechen – timgeb

+0

Danke für deine Antwort @Nick A und timgeb. Ich habe beides gemacht, aber es funktioniert immer noch nicht. Nach der Eingabe einer Nummer passiert nichts, ich muss die Nummer erneut eingeben, um zu arbeiten, wenn ich nicht dont und nur erneut drücken, bekomme ich einen ValueError und wenn ich quit, funktioniert es, aber ich bekomme einen NameError .. –

Antwort

1

paar Änderungen und alles ist gut

import random 
attempts = 0 
secretNumber = random.randint(1,100) 
while True: 
    print("Guess a number between 1 and 100. You can exit game anytime by typing q ") 
    guess=input() 
    stop=str(guess) 
    if stop== 'q': 
     print("You quitted the game") 
     break 
    elif not guess.isdigit(): 
     print("Only numbers are allowed") 
    else:   
     guess = int(guess) 
     attempts = attempts + 1 
     if guess >100 or guess<=0: 
      attempts = attempts - 1 
      print("Not allowed.Only numbers between 1 and 100 allowed! \n") 
     elif guess < secretNumber and guess >0: 
      print("Nope!Try a higher number! \n") 
     elif guess > secretNumber and guess <100: 
      print("Nope!Try a lower number \n") 
     if guess == secretNumber: 
      attempts = str(attempts) 
      print("Congratulations you found it after " + attempts + " attempts") 
      break 
+0

Vielen Dank @legendisback !! Definitiv eine Legende. Es hat funktioniert! –

+0

Ich habe versucht, die .isdigit() -Methode zu verwenden, um einen ValueError zu vermeiden, wenn der Benutzer str statt int eingibt, ich habe versucht, das "q" -Wort auf 0 zu ändern, um Konflikte mit keinem Glück zu vermeiden. Ist das möglich? Irgendwelche Gedanken ?? Vielen Dank für Ihre Zeit .. –

+0

@Mike_R bearbeitet das Programm, jetzt .isdigit() hinzugefügt, um nur Zahlen zum Raten zu erlauben –

0

Unter was Nick A und timgeb in ihren Kommentaren erwähnt, Sie ein paar Dinge anpassen konnte. Wie ich im folgenden Skript vorschlage, möchten Sie vielleicht einen Blick auf try and except werfen. Bitte finden Sie Kommentare im Skript.

import random 
attempts = 0 
secretNumber = random.randint(1,100) 
# you can prompt the user within input() 
stop=input("Guess a number between 1 and 100. You can exit game anytime by typing quit ") 

while True: 
    if stop == "quit": # as the the output of input() is a string, you can compare it with a string without str() 
     print("You quitted the game") 
     break 
    try: # work with try and except to avoid problems whenever the user writes something else than 'quit' or an integer 
     guess = int(stop) 
     attempts += 1 
     if guess >100 or guess<=0: 
      attempts = attempts - 1 
      print("Not allowed.Only numbers between 1 and 100 allowed! \n") 
     elif guess < secretNumber and guess >0: 
      print("Nope!Try a higher number! \n") 
     elif guess > secretNumber and guess <=100: # note that it's <=. Otherwise nothing happens when the users chose 100 
      print("Nope!Try a lower number \n") 
    except: # if it's not possible to turn 'stop' into an integer we'd like to perform the following 
     stop = input("No valid input, please guess again ") # Don't stop the script, let the user guess again 
     continue # don't stop, but leave the current iteration (don't execute the rest) and start again at the beginning of the loop 
    if guess == secretNumber: 
     attempts = str(attempts) 
     print("Congratulations you found it after " + attempts + " attempts") 
     break 
    stop = input("Guess again ") # prompt for a new number every round of the loop 
+0

Vielen Dank @trotta! Tolle Erklärung in den Kommentaren, du hast sehr geholfen! –

+0

Es funktioniert gut, aber ich möchte nicht das Programm zu stoppen, wenn Benutzer einen ungültigen Wert übermittelt, so dass ich die "Pause" nach dem "außer:" entfernt und die Schleife nicht beendet. Das Problem tritt auf, wenn der erste übergebene Wert ungültig ist .. ich bekomme einen NameError. Irgendwelche Gedanken darüber, wie ich das lösen könnte? Nochmals vielen Dank für Ihre Zeit! –

+0

Wenn Sie 'break' entfernen und der Benutzer eine ungültige Eingabe sendet, ist 'guess' nicht definiert, da es nicht möglich ist, die ungültige Eingabe in eine Ganzzahl umzuwandeln. Was Sie grundsätzlich tun könnten, ist, die jeweilige 'if'-Anweisung zu ändern und mit 'continue' statt mit' break' zu arbeiten. Ich habe das Skript aktualisiert und Kommentare geschrieben, wie es funktioniert. Sie können mehr über die continue-Anweisung [hier] (https://docs.python.org/3/tutorial/controlflow.html) erfahren. Fühlen Sie sich frei, weitere Fragen zu stellen! – trotta

Verwandte Themen