could someone please help me in forming a loop as i am stuck...

def numbergen():
    randomnumber = random.randint(0,100)
    print randomnumber
def main():
    Question = float(raw_input("Do you wish to play the Guess a Number Game?(Y/N)"))
   for Question:
        if Question == N:
            break
        else:
            print "randomnumber"

main()

Edited 6 Years Ago by joshua91: n/a

This should get you started.

def numbergen():
    randomnumber = random.randint(0,100)  #randrange is better
    return randomnumber
def main():
    while True:
        question = raw_input("Do you wish to play the Guess a Number Game?(Y/N)")
        #variables tend to be lowercase, and classes are uppercase
        if question.lower() == "n":
            break
        else:
            print numbergen()

main()

Edited 6 Years Ago by jcao219: n/a

This looks similar to jcao219's solution. The difrence is the if/elif/else statments. I included this to show the importants of error handling.
If the user entered "no" or "something stupid" as the input, the else statement would catch it.

You could also handle errors with try/except statements also.

import sys, random

def numbergen():
    randomnumber = random.randint(0,100)
    print randomnumber

def main():
  while 1:
    Question = raw_input("Do you wish to play the Guess a Number Game?(Y/N)")    
    if Question.lower() == "n":
      sys.exit()
    elif Question.lower() == "y":
      numbergen()
    else: 
      print "Incorect input, y or n"

main()

This is my opinion of having a yes/no question with a default, but you should capitalize the default letter and leave the other lowercase. You also need to take into account that the raw_input() function will provide you with a line break as well (\n) and therefore should be striped.

For example, your script is wanting to play the game (why would you run it if it wasn't?), therefore the default would logically be 'Y', so:

#!/usr/bin/env python

import sys, random

def numbergen():
    randomnumber = random.randint(0,100)
    print randomnumber
    
    return

def main():
    Question = raw_input("Do you wish to play the Guess a Number Game? [Y/n]").strip()
    
    if Question.lower() == "n":
        sys.exit()
        pass

    elif Question.lower() == "y":
        numbergen()
        pass
    
    else: 
        print "Incorect input, y or n"
        pass

    return

while 1:
    main()
    pass

sys.exit()

I'm kind of stickler for syntax and 'pass', 'continue' and 'return' statements since emacs and other CLI editors make note of those for the auto indent features.

In any case, given what's here, you should be well on your way. :)

I'm kind of stickler for syntax and 'pass', 'continue' and 'return' statements since emacs and other CLI editors make note of those for the auto indent features.

In any case, given what's here, you should be well on your way. :)

I am sorry but you lost me with these comments. Could you clarify this comment?

I would put pass somewhere where need a statement and I have it not ready and want to mark it for future to put one and test before it is ready.

Return without anything I would use sometimes for clarity instead of falling through out of function or when exiting from the middle of control flow from the function (when I do not want to execute rest of the statements in the function) i.e. like break from the loop.

Continue with next iteration of the loop instead of breaking out of it with 'break'.

Sorry but I find the syntax very confusing, even I understand that you want not to give solution ready for this poster.

My comment for original code and small corrections:

def numbergen():
    ## we do not need this variable randomnumber
    return random.randint(0,100)
##    print randomnumber ## to return value we give number back by return  
    
def main():
    Question = raw_input("Do you wish to play the Guess a Number Game?(Y/n)") ## our aswer is float not Y or N, 
   for Question:
        if Question == N:
            break  ## to exit from funcition 
        else:
            print "randomnumber" 
## this is not C-language, should be main loop here
main()

Generally I would recommend to learn from beginning to return values from the functions not use print statements other than to log the activity's progress ("Executing this long action") or when the code in the function is interactive, which generating random number is not.

I would suggest this pseudo code for the program. Let's keep the make random number as exercise of calling. It would nice for your future programs also have get_yes_or_no(default answer) function. This function is really one neat code which even beginner can do. You feel proud of yourself after finishing it and showing it to your friends!

  1. print generated random number from my random function
  2. while get_yes_or_no('Y'):
    1. print generated random number from my random function

Then make the function for random number return random number with return statement and prepare the get_yes_or_no.

Help for creating prompting function
If you want this prompt function to be able to persistently ask for ever for correct answer I give the main part of function as it is maybe little advanced for you (by giving the default='', we allow no parameter or parameter '' for this persistent questioning):

def get_yes_or_no(default=''): 
## get users input
##  return False when want to finish and True when want to continue
## when parameter is 'y' or 'Y',  only 'n' or 'N' gives False
## when parameter is 'n' or 'N', only 'y' or 'Y' will return True
 if default=='':  ##here we have tested allready that users answer is  not y/Y or n/N
      print 'You did not give right answer. Try again!'
      return get_yes_or_no() ## we do another question for the user

Edited 6 Years Ago by pyTony: n/a

This is my opinion of having a yes/no question with a default, but you should capitalize the default letter and leave the other lowercase. You also need to take into account that the raw_input() function will provide you with a line break as well (\n) and therefore should be striped.

...

Wrong!

# show that raw_input() does not add a 
# newline character to the input string

name = raw_input("Enter your name: ")
if '\n' in name:
    print( "name %s ends with newline character" % name )
else:
    print( "no newline character in %s" % name )

Originally Posted by tonyjv

Originally Posted by Hummdis
I'm kind of stickler for syntax and 'pass', 'continue' and 'return' statements since emacs and other CLI editors make note of those for the auto indent features.

In any case, given what's here, you should be well on your way.

I am sorry but you lost me with these comments. Could you clarify this comment?

I would put pass somewhere where need a statement and I have it not ready and want to mark it for future to put one and test before it is ready.

Return without anything I would use sometimes for clarity instead of falling through out of function or when exiting from the middle of control flow from the function (when I do not want to execute rest of the statements in the function) i.e. like break from the loop.

Continue with next iteration of the loop instead of breaking out of it with 'break'.

Sorry but I find the syntax very confusing, even I understand that you want not to give solution ready for this poster.

How do I put this, some editors (such as emacs) have an autoindent feature. When you use 'pass' lines as a place-holder, the code automatically moves back an indent marker. For example, you write this code:

def sample(text):
    if text == 'Hi':
        print "Nice to meet you."

    return

When you press RETURN or ENTER (whatever you like to call the carriage return :) ) emacs puts you on the same indent level as the 'print' statement. If you press RETURN again, you remain on the same indent level. However, if you write this:

def sample(text):
    if text == 'Hi':
        print "Nice to meet you."
        pass
    return

Then, after you type 'pass' and press RETURN, emacs automatically moves you back one indent level, in this case, the same indent level as the "if" statement. Therefore, I use 'pass' and 'continue' in places where it may not be needed for the code to actually work. Both sets of code above work in the exact same way, but the latter one makes emacs operate differently.

In addition, when using the place holder as latter set of code above, I know that there are no lines below that point belonging to the 'if' statement. This allows me to know if I need to add or change a line should the "if" condition be true, I need to add the line above the 'pass' since that 'pass' line states it's the end of the 'if' statement.

Python allows you to write code in many different ways depending on how you choose to code (aside from it's syntax rules, such as indentation, of course) in a fashion that best suits you.

My experience has shown that 'continue' is not needed for loops because they will loop until the conditions of the loop are met or are no longer met based on how you setup the loop. However, by using 'continue' as a place holder, I know that its the end of the loop.

Edited 6 Years Ago by Hummdis: Clarification

Wrong!

# show that raw_input() does not add a 
# newline character to the input string

name = raw_input("Enter your name: ")
if '\n' in name:
    print( "name %s ends with newline character" % name )
else:
    print( "no newline character in %s" % name )

If I'm wrong, then explain this post that you didn't have an answer to (and couldn't duplicate) but the fix was to add the .strip() to the end of the raw_input.

It would appear that the problem may exist in Python on certain systems. Python 2.5 and 2.6 don't show the problem, but Python 2.2 does. At least in my Linux environment it does. I was able to duplicate his problem exactly.

Adding the .strip() doesn't break anything and prevents the EOL character from being added, it's also better than adding code to check for a newline character and removing it if it exists.

Since it's not clear what version of Python this poster is using, to assume that everyone uses 2.5 or higher on Windows is unacceptable.

Edited 6 Years Ago by Hummdis: Grammatical

Under normal conditions, raw_input should never have a "\n" at the end, since it is designed to read stdin until it encounters a line break, not including the line break. It's most likely safe to leave off the .strip(), but it isn't wrong either, unless if you are really shooting for optimum performance and succinctness.

Edited 6 Years Ago by jcao219: n/a

Not needed to write long if/elif/else lopp,for something simple as this.

Question = raw_input("Do you wish to play the Guess a Number Game? [Y/n]: ")
if Question.lower() not in ['y', 'n']:
   print "Not a valid option"
else:
    print 'Do something'

Under normal conditions, raw_input should never have a "\n" at the end, since it is designed to read stdin until it encounters a line break, not including the line break. It's most likely safe to leave off the .strip(), but it isn't wrong either, unless if you are really shooting for optimum performance and succinctness.

I absolutely agree with that and I have exactly one system of many, many systems that can duplicate that problem. My other Linux machines, Windows, and even Mac OS X don't show that problem.

I also agree that unless you're shooting for full optimum performance, adding the .strip() will only add fractions of a millisecond to the process.

I just wanted to shed light on the fact that there are systems where even raw_input *may* need to have the .strip() added.

Edited 6 Years Ago by Hummdis: Code tag correction.

This question has already been answered. Start a new discussion instead.