-2

im really new in Python 3.7 im testing some stuff out, and i try to understand how can i ask someone his age. but if he enter a letter or a negative number it say, only positive number please then it ask the question again, if the number is positive then the program continue. here is my code so far giving me an error:

while true :
age = input('Your age : ')

try: 
    age = int(age)
except ValueError:
    print ('Numbers only')
    continue
else: 
    break

giving me as error : ,

> line 10  
    age = input()  
       ^  
SyntaxError: expected an indented block
Eli Korvigo
  • 10,265
  • 6
  • 47
  • 73
  • The code as posted does not produce the you show. (It _does_ produce a `NameError:: name 'true' is not defined`.) From the exception information, it looks like, unlike the code you posted here, which has a correctly indented `age = input('Your age : ')`, your actual code has a completed different line, `age = input()`, which is _not_ indented, and the error is caused by it not being indented. – abarnert Aug 29 '18 at 18:54
  • The error message is pretty clear: your indentation is broken. All code below `while` must be indented to the right. – Eli Korvigo Aug 29 '18 at 18:55
  • How do i correct that? – Sebastien Marchand Aug 29 '18 at 18:56
  • Well, indent the code one step to the right – Eli Korvigo Aug 29 '18 at 18:57
  • Ok i just figured out, im so dumb... – Sebastien Marchand Aug 29 '18 at 19:00

1 Answers1

0

Does this help? This works:

while True:
    age = input('Your age')
    try:
        age = int(age)
        break
    except ValueError:
        print ('Numbers only')

Explanation: condition 'True' is True by definition, so the loop occurs indefinitely until it hits a "break." Age takes standard input and tries to convert it to an integer. If a non-integer character was entered, then an exception (ValueError) will occur, and "Numbers only" will be printed. The loop will then continue. If the user enters an integer, the input will be converted to an integer, and the program will break from the loop.

In regard to syntax errors: In Python syntax, it the keyword is "True" instead of true. You need to indent all items following a loop or conditional (in this instance, the error occurred when the program encountered age=input('Your age :'), which needs to be indented.

Matthew
  • 115
  • 10