Newby, wanting to loop

This is the place for queries that don't fit in any of the other categories.

Newby, wanting to loop

Postby adamjamesh22 » Mon Dec 09, 2013 4:47 pm

Hi guys, i have just started using Python... as in today :/ (have to start somewhere) and i have followed some tutorials and made a three phase guessing game (will look completley amateur to you guys) il drop a copy of the code on at the end.

At the end of the scrip i want to ask if they user would like to play again. if Y then start the whole process again. so of an infinite loop, is this at all possible and is there an easy way to do it

Any help would be appreciated, thanks again
Code: Select all
import random
import sys
import time

enter = ("Please press enter to continue...")

print ("Welcome to the guessing game")
print ("I have chosen a number between 1 and 20")
comnum = random.randint (1, 20)
guess1 = input ("What's your first guess? ")
if guess1 == comnum:
    print ("Winner Winner Chicken Dinner")
    raw_input (enter)
    sys.exit (0)
else: print ("Oops...")
guess2 = input ("Have another go: ")
if guess2 == comnum:
    print ("Well done")
    raw_input (enter)
    sys.exit (0)
else: print ("Oh dear")

guess3 = input ("One last try: ")
if guess3 == comnum:
    print ("Well done you finally did it")
    raw_input (enter)
    sys.exit (0)
else: print ("Better luck next time")
print ("Do you want to know what it was...")
comnum = str (comnum)
print ("It was" +comnum)
Last edited by Yoriz on Mon Dec 09, 2013 5:46 pm, edited 2 times in total.
Reason: First post lock, Added code tags
Posts: 1
Joined: Mon Dec 09, 2013 4:40 pm

Re: Newby, wanting to loop

Postby Yoriz » Mon Dec 09, 2013 5:39 pm

Hi welcome to the forum, please read the 'new users read this' link in my signature.
I've added code tags to your code so the indentation is shown correctly,
please use them as stated in the given link when posting code.

You could use a while loop, see the example below
Code: Select all
print('code before loop')
while True: # loop forever
    print('code inside loop')
    do_exit = input('type yes to stop the loop')
    if do_exit.lower() == 'yes':
        break #stops the while loop
print('code after loop')
Due to the reasons discussed here we will be moving to on October 1 2016
This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
Posts: 1672
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot], Yahoo [Bot] and 9 guests