2

I am a complete beginner in Python and I'm trying to make improvements in my code for my GCSE Computer Science coursework. All I want to be able to do is limit the number of digits inputted to 7. Here is all of what I have so far:

print("Hello")
time.sleep(0.5)
print("What is your 7-digit product number?")
while True:
try:
    productnumber=  (str(int(input(" "))))
    break
except ValueError:
    print("Please only enter numbers")
    time.sleep(1)
    print()
    print("What is your 7-digit number?")

Any help is appreciated, I tried adding a nested loop but I've had no luck so far with anything I do, as I mentioned before, I am a compleeete beginner. Thanks a lot!

3
  • Please edit your post and add the exact/specific error you're observing. This will help others more easily help you. Commented Jan 14, 2017 at 22:59
  • @xlm Although I've already got my answer, I'll definitely do that, thanks for the feedback! Commented Jan 16, 2017 at 23:45
  • check if len(productnumber) <= 7?? Commented Jan 16, 2017 at 23:49

1 Answer 1

2

Your code above is not indented properly because nothing is inside the infinite loop starting with while True:. I suspect just the try-except block is supposed to go in there. What you need to limit the entry to seven characters is an if. Consider the following:

while True:
  try:
    productnumber = str(int(input(" ")))
    if len(productnumber) > 7:
      print("You may only enter seven digits")
    else:
      break
  except ValueError:
    print("Please only enter numbers")
    time.sleep(1)
    print()
    print("What is your 7-digit number?")

The len functions computes the length of a string.

There are several other ways to make your code better including using camelCase for your variable names.

Happy python learning!

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much for your super fast reply, I really appreciate it! Also thanks for the advice, I incorporated your code into mine and it worked perfectly! Thank you so so much, you're an absolute life saver!
Read PEP-8. snake_case is recommended for method and variable names, not camelCase. This isn't JavaScript.
@MattDMo I see! Thank you very much for telling me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.