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")
time.sleep(2)
print ("I have chosen a number between 1 and 20")
time.sleep(2)       
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...")
time.sleep(2)
guess2 = input ("Have another go: ")
if guess2 == comnum:
    print ("Well done")
    raw_input (enter)
    sys.exit (0)
else: print ("Oh dear")
time.sleep(1)

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")
time.sleep(2)
print ("Do you want to know what it was...")
time.sleep(1)
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
adamjamesh22
 
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')
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 842
Joined: Fri Feb 08, 2013 1:35 am
Location: UK


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider], snippsat, W3C [Linkcheck] and 3 guests