Reputation: 4148
As shown below, I'm providing the user with an option to spend points, I'm ensuring that the input contains either of 'y yes n no'. If the user would like to spend points he's prompted to select a number which differs the assignment of v
, I'm ensuring the input is a number using .isdigit()
. If the user wouldn't like to spend points v
is simply assigned to 0.0
while True:
choice = raw_input('\nSpend points?')
if choice.lower().strip() in "y yes n no".split():
while True:
if choice.lower().strip() in "y yes".split():
c = raw_input('Enter Value 1-6: ')
if c.isdigit() and int(c) <= 6:
if choice.lower().strip() in "y yes".split():
if c == '1':
v = 0.3
if c == '2':
v = 0.25
if c == '3':
v = 0.2
if c == '4':
v = 0.1
if c == '5':
v = 0.05
if c == '6':
v = 0.75
break
if choice.lower().strip() in "n no".split():
v = 0.0
break
else:
continue
else:
continue
print v
However, although the code works fine, after v
seems to be printed successfully, the code will continue looping back to 'Would you like to spend credits?'
I believe the problem lies with my break
statement, but I'm not sure where it's supposed to go.
Upvotes: 0
Views: 50
Reputation: 16224
You can re-write the idea by doing this, and as @Wyatt used a map, is a nice idea use it too:
choice = raw_input('\nSpend points?')
v = 0.0
value_map = {
1: 0.3,
2: 0.25,
3: 0.2,
4: 0.1,
5: 0.05,
6: 0.75,
}
while not (choice.lower() in "y yes n no".split()):
print("invalid input, valid input are 'y, yes, n, no'")
choice = raw_input('\nSpend points?')
if choice.lower().strip() in "y yes".split():
c = raw_input('Enter Value 1-6: ')
while not(c.isdigit() and int(c) <= 6):
print("please, enter a digit between 1 and 6")
c = raw_input('Enter Value 1-6: ')
v = value_map[int(c)]
print v
Upvotes: 0
Reputation:
value_map = {
1: 0.3,
2: 0.25,
3: 0.2,
4: 0.1,
5: 0.05,
6: 0.75,
}
# Prompt user to spend points until they quit
while True:
answer = raw_input('Spend points? y(es) n(o) q(uit) ')
answer = answer.strip().lower()
if not answer:
continue
if answer in ('q', 'quit'):
print('Quit')
# Break out of outer loop
break
elif answer in ('y', 'yes'):
# Prompt until a valid selection is made
while True:
selection = raw_input('Value in 1-6 ')
if not selection.isdigit():
print 'Please select a number in 1-6'
continue
selection = int(selection)
if selection < 1:
print 'Selection out of range (too low)'
continue
if selection > 6:
print 'Selection out of range (too high)'
continue
# Break out of inner loop
break
value = value_map[selection]
elif answer in ('n', 'no'):
value = 0.0
else:
print 'Please select one of y, n, or q'
continue
print value
Upvotes: 1