-2

I recently started programming in Python and I made a small shop. I want it to ask you if you want to buy anything else, and if the answer is yes, it will loop to the start of the program. I have tried other solutions but none of them worked. I'm using Python 3.x. If you want to take a look here it is:

import datetime
now = datetime.datetime.now()
hours = now.hour

if hours < 12:
    greeting = "Good morning"
elif hours < 15:
    greeting = "Good afternoon"
elif hours < 18:
    greeting = "Good evening"
elif hours < 24:
    greeting = "Good night"       
print('{}!'.format(greeting),)

a = input('would you like to buy a console? (y/n) ')

if a == 'y':                                                                                                                                                                                                              
    consoleQ = input('What console would you like? (ps4/switch/xboxone) ')
    if consoleQ == 'ps4':
        print('Ok! Here is your Ps4! Have a good day!')
    elif consoleQ == 'xboxone':
        print('Ok! Here is your Xbox One! Have a good day!')
    elif consoleQ == 'switch':
        print('Ok! Here is your Switch! Have a good day!')   
        exit(print('Have a {}!'.format(greeting),))

elif a == 'n':
    print('Okay, have a good day!')
    exit()

I have tried using this to loop: (didn't work)

loop = input('Would you like anything else? (y/n)')

while loop == 'y':
    a = input('Would you like to buy a console? (y/n)')

I have just started, so please don't be harsh. I know that I don't REALLY know a lot of stuff, after all, this is my second week programming. Thanks in advance!

The Godfather
  • 4,235
  • 4
  • 39
  • 61
  • [This](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) topic should be very useful. You just need to adjust from "user did give wrong input" to "user wants to continue". – timgeb Jun 10 '20 at 13:42
  • Duplicated question! – ozturkib Jun 10 '20 at 13:45

2 Answers2

1

Here is what you can do:

while True:
    do_something()
    loop = input("Would you like to buy anything else? (y/n)")
    if loop != 'y':
        break # Break out of loop if not answered yes
    # else, continue looping
MrNobody33
  • 6,413
  • 7
  • 19
Red
  • 26,798
  • 7
  • 36
  • 58
0

Because your loop variable is set outside the loop, if the user answers yes the first time, it will loop forever. Try putting the loop input inside the while loop.

loop = input('Would you like anything else? (y/n) ')

while loop == 'y':
    a = input('Would you like to buy a console? (y/n) ')
    #Do all the buying a console stuff in the middle here
    loop = input('Would you like anything else? (y/n) ')
willturner
  • 104
  • 6