Need help with my code

+1 Emir KUY · December 28, 2015
Hey guys, I recently started watching Bucky's python tutorials and I was doing some coding on my own. I wrote my code down below and what I need help with is, as you can see, when you enter a number that doesnt suit the conditions like 120 it says 'it must be between 0 and 100' but i dont want it to end there. How can I ask for user input again? Like it says it must be between 0 and 100 try again. I found a code that puts the input in a loop but i think i need to put it inside my for loop... Thank you for your attention.


magicNumber = input("Please, pick a number, any number:")

for x in range(101):
   if x is magicNumber and 0 < x < 101:
      print 'Congrats!' ,x,',is the magic number'
      break
   elif magicNumber > 100 or magicNumber < 0:
      print 'Magic number is suppose to be between 0 and 100.'
      break
   elif magicNumber <> int(magicNumber):
      print 'Magic number is suppose to be a integer number.'
      break
    else:
      print x

Post a Reply

Replies

Oldest  Newest  Rating
0 Michael Bianchi · December 31, 2015
You probably don't need the break statements. You want it to do all the checks without breaking. Also, you're using the range function, which allows up to 3 parameters. They are start, step, and stop.

For you, you can "start" on magicNumber and "stop" at 100 like so:

range(magicNumber, 100)
+1 Kartheyan Sivalingam · December 29, 2015
You could use functions
def game():
   magicNumber = input("Please pick a number, any number")
   for x in range(101):
       if x is magicNumber and 0 < x < 101:
           print 'Congrats!' ,x,',is the magic number'
           break
       elif magicNumber > 100 or magicNumber < 0:
           print 'Magic number is suppose to be between 0 and 100.'
           game()
       elif magicNumber <> int(magicNumber):
           print 'Magic number is suppose to be a integer number.'
           game()
       else:
          print x
+2 James Kon · December 28, 2015
Try using while.

For example, if the magic number isn't 101, it would ask to enter another number. Note I'm using Python 3 so you may have to translate this.
magicNumber = input("Please, pick a number, any number:")
status = 0

while status == 0:
    if x == magicNumber:
         print("Correct!!!")
         status = 1
    else:
         magicNumber = input("Enter another number: ")

         
  • 1

Python

107,071 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator