- You can test for emptiness of
number
by just if not number
- After testing for emptiness, you could go straight to an int by adding
number = int(number)
- Inside the loops, when you test for
i % 2 == 0:
, and then put None
as the loop body (that should really be pass
), you could just test for if i % 2 != 0:
, and replace None
with the else
body, and remove the else
.
0
is even, so you can remove that test.
- You can replace
int(number) % 2 == 0
with not int(number) % 2
.
- Looking at the
for
loops, the range
could be changed to range(1, number-1, 2)
, removing the need for an if
statement.
- You can also invert the last
range
, so the subtracting from number
and 1
is not needed.
- Python automatically adds newlines, so the
\n
s aren't really needed.
That leaves us with (after removing a few useless brackets):
while True:
number = raw_input("Enter an odd number or hit ENTER to quit program: ")
if not number:
print "Quitting program..."
break
number = int(number)
if not number % 2:
print "That's an even number, try again."
else:
for i in range(1, number + 1, 2):
print ("*" * i).center(number)
for i in range(number - 2, 0, -2):
print ("*" * i).center(number)
If you want to go functional, you can move your user input checking into a function. In this function you could also check if the user inputs a non-number, such as abc
, by catching the exception or using str.isdigit
:
def get_input():
while True:
number = raw_input("Enter an odd number or hit ENTER to quit program: ")
if not number:
return # return None when the user wants to quit
if number.isdigit() and int(number) % 2:
return int(number) # return the number, as its odd
print "That's not a valid input (must be an odd integer), try again."
With this function, the rest of your program reduces to:
for number in iter(get_input, None):
for i in range(1, number + 1, 2):
print ("*" * i).center(number)
for i in range(number - 2, 0, -2):
print ("*" * i).center(number)
print "Quitting program..."
iter
calls the function and gives its value until the function returns None
(the sentinel value).
On a stylistic note:
- You should always have spaced around operators, so
range(int(number)+1)
should be range(int(number) + 1)
(that's PEP8).
- You may want to add a big fat comment at the start of your program describing what it does.
Also, nice use of str.center
, it avoided having too many loops!