The program goes as follows, asks to choose a product, then asks for the amount of the choice, then the user inputs the amount, but if the amount is different from the declared values (mo), the program prints "wrong coins", but when the user inputs the correct coin and amount, it should print only the "change" part of the code. In my program, it prints "change" and then wrong coin value
prod = ["Coffe", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
mo = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nPick an item:")
for number in range(0, item_number, 1):
print(number + 1,
prod [number],
'{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) -1
if choice < item_number and choice >= 0:
print("You should input", "{0:.2f}€".format(cost[choice]), 'in total')
else:
print("Exiting the program")
exit(0)
money = float(input("How much do you enter?; "))
while money < cost[choice]:
money += float(input("You should insert "+str("{:.2f}".format(cost[choice] - money))))
if money != mo:
print("Invalid amount.\nPlease enter a valid coin: 0.1 / 0.2 / 0.5 / 1 / 2 / 5 / 10")
else:
print("Try again")
change = money - cost[choice]
print("Change {0:.2f}€".format(change))
The logic may be different
continuously ask for money (a while True allow to write the input once)
verify if the choosen is in the list not equal (a float can't be equal to a list)
increment your total money
stop if you have enough
money = 0
while True:
new_money = float(input(f"You should insert {cost[choice] - money:.2f}: "))
if new_money not in mo:
print("Invalid amount.\nPlease enter a valid coin: " + "/".join(map(str, mo)))
continue
money += new_money
if money >= cost[choice]:
break
change = money - cost[choice]
print(f"Change {change:.2f}€")
The other code, with some improvments
print("\nPick an item:")
for number in range(item_number, ):
print(f'{number + 1} {prod[number]} {cost[number]:.2f}€')
print("0 Exit")
choice = int(input("Please pick an item from (1-4) or hit 0 to exit: ")) - 1
if 0 < choice <= item_number:
print(f"You should input {cost[choice]:.2f}€", 'in total')
else:
print("Exiting the program")
exit(0)
Related
I was following along with a youtube video to a ATM using python and I got expected expression. I dont know how to fix it. line 32, 37 and 40.
enter image description here
You can't have an elif after an else. This is because else will capture all the remaining cases. Indentation, meaning spaces or tabs before the line is very important in Python.
Here is what I think you meant to write:
balance = 1000
print("""
Welcome to Dutch Bank
Choose Transaction
1) BALANCE
2) WITHDRAW
3) DEPOSIT
4) EXIT
""")
while True:
option = int(input("Enter Transaction"))
if option == 1:
print ("Your Balance is", balance)
anothertrans = input("Do You Want to make another Transaction? Yes/No: ")
if anothertrans == "YES":
continue
else:
break
elif option == 2:
withdraw = float(input("Enter Amount To Withdraw"))
if (balance > withdraw):
total = balance - withdraw
print("Success")
print("Your New Balance is: ",total)
else:
print("Insufficient Balance")
elif option == 3:
deposit = float(input("Enter Amount To Deposit"))
totalbalance = balance + deposit
print("Sucess")
print("Total Balance Now is: ", totalbalance)
elif option == 4:
print("Thank You ForBanking With Dutch Bank")
exit()
else:
print ("No selected Transaction")
I am trying to restart the program to start over if I press Yes if I wish to continue but after quite a bit of reading could not figure out a solution. I am trying to restart the funciton buth with no success. When I press Y to continue it does completely wrong calculations not bringing me back to start all over. Any help would be appreciated.
oo_large_value = 100000
dimes = -1
quarters = -1
nickels = -1
pennies = 0
continue_execution = 'Y'
#Continue Until User doesn't want to exit
while continue_execution == 'Y':
print("Please enter the number of coins:")
#input quarters
while quarters < 0 or quarters >= too_large_value:
try:
quarters = int(input("# of quarters:"))
#if user entered negative value, give error
if quarters < 0:
print("Please Enter a positive Value:")
#if user entered too large value, give error
elif quarters >= too_large_value:
print("Entered Value is too large.\nPlease Enter between 0 and 99999:")
#if user didn't enter an integer,throw exception
except ValueError as e:
print("Please Enter Integer value only:")
quarters=quarters*25
while dimes < 0 or dimes >= too_large_value:
try:
dimes = int(input("# of dimes:"))
# if user entered negative value, give error
if dimes < 0:
print("Please Enter a positive Value:")
# if user entered too large value, give error
elif dimes >= too_large_value:
print("Entered Value is too large.\nPlease Enter between 0 and 99999:")
# if user didn't enter an integer,throw exception
except ValueError as e:
print("Please Enter Integer value only:")
dimes=dimes*10
while nickels < 0 or nickels >= too_large_value:
try:
nickels = int(input("# of nickels:"))
# if user entered negative value, give error
if nickels < 0:
print("Please Enter a positive Value:")
# if user entered too large value, give error
elif nickels >= too_large_value:
print("Entered Value is too large.\nPlease Enter between 0 and 99999:")
# if user didn't enter an integer,throw exception
except ValueError as e:
print("Please Enter Integer value only:")
nickels=nickels*5
#calculate pennies
pennies = quarters + dimes + nickels
#print total pennies
print(f'The total is {pennies} pennies')
#Ask if user wants to Continue or not
print("Do You want to Enter another value?")
continue_execution = input("Y for Yes and N for N:")
#makes sure user enters only 'Y' or 'N'
while continue_execution != 'Y' and continue_execution != 'N':
print("Invalid Choice\nPlease Enter again")
continue_execution = input("Y for Yes and N for N: ")
print("Thank you for doing business with us!")
I'm struggling to print the remaining amount inside the input
I tried to remove the money the users enter from the cost choice but it doesn't work
prod = ["Coffee", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
m = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nYour choices:")
for number in range(0, item_number, 1):
print(number + 1,
prod [number],
'{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please enter a choice between (1-4) or hit 0 for exit: ")) -1
if choice < item_number and choice >= 0:
print("Please enter", "{0:.2f}€".format(cost[choice]), 'in total')
else:
print("Exiting the program")
exit(0)
money = float(input("Please fill the remaining amount ; "))
while money < cost[choice]:
money += float(input("You still have to enter ", cost[choice] - money))
change = money - cost[choice]
print("Your change {0:.2f}€".format(change))
Does this Help?
prod = ["Coffee", "Coffee with milk", "Chocolate", "Chocolate with milk"]
cost = [1.5, 1.8, 2.1, 2.4]
m = [0.1, 0.2, 0.5, 1, 2, 5, 10]
item_number = len(prod)
print("\nYour choices:")
for number in range(0, item_number, 1):
print(number + 1,
prod [number],
'{0:.2f}€'.format(cost[number]))
print ("0 Exit")
choice = int(input("Please enter a choice between (1-4) or hit 0 for exit: "))
-1
if choice < item_number and choice >= 0:
print("Please enter", "{0:.2f}€".format(cost[choice]), 'in total')
else:
print("Exiting the program")
exit(0)
money = float(input("Please fill the remaining amount ; "))
while money < cost[choice]:
money += float(input("You still have to enter "+str("{:.2f}".format(cost[choice] - money))))
change = money - cost[choice]
Your problem is in this line.
money += float(input("You still have to enter ", cost[choice] - money))
which should be
money += float(input("You still have to enter " + str(cost[choice] - money)))
Make the calculation first (inside parentheses) then, convert it to a string to concentrate with the input string.
creating a pizza ordering program for IT class, almost finished with it but I'm currently stuck with a problem that I can't seem to fix or don't know how to. As the user is finished choosing their pizza it was suppose to add up the total cost of the pizza they have chosen but the problems is they don't add up the instead the price stays the same
Name:Jack
Telephone:47347842
ORDER:
['2. Hawaiian pizza', 8.5]
['1. Pepperoni pizza', 8.5]
['3. Garlic cheese pizza (with choice of sauce)', 8.5]
Total Price: 8.50
Here's the price list that they have to choose from
['1. Pepperoni pizza', 8.5]
['2. Hawaiian pizza', 8.5]
['3. Garlic cheese pizza (with choice of sauce)', 8.5]
['4. Cheese pizza (with choice of sauce)', 8.5]
['5. Ham and cheese pizza', 8.5]
['6. Beef & onion pizza', 8.5]
['7. Vegetarian pizza', 8.5]
['8. BBQ chicken & bacon aioli pizza', 13.5]
['9. Boneless pizza (italian style anchovy with no bones)', 13.5]
['10. Pizza margherita', 13.5]
['11. Meat-lover’s pizza', 13.5]
['12. Tandoori pizza', 13.5]
I don't know if the problems lies in this code but it seem like it is. I originally I tried using 'cost.append' but it only came up with an error like this
unsupported operand type(s) for +: 'int' and 'str'
def Choice_of_pizza():
for i in range(1,pizza_no
+1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
cost.append(MENU[pizza_kind-1][0][pizza])
customerOrder.append(MENU[pizza_kind-1][pizza])
global total_cost
total_cost = sum(cost) #Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza()
So I went and replace it with 'cost=+customerOrder[i][1]' but even then it somewhat works with the names of the pizza being added but not the prices unto the customer details.
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
for i in range(len(customerOrder)):
cost=+customerOrder[i][1]
global total_cost
total_cost=0
#Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost=+cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost=+cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza(
The intended goal was, as the user input there choice one by one it takes out the name and places the price into the cost list but it doesn't seem to do that.
here's the original full code
#----------------------------important stuff-----------------------------------
#time delay
import time
#loop system for the details section
running = True #Loop
import re
Delivery_cost = 3.0
cost=[]
customerOrder=[]
customer_name=[]
customer_name_2=[]
customer_telephone_2=[]
house_no=[]
street_name=[]
#------------------------------menu list --------------------------------------
MENU =[
['1. Pepperoni pizza', 8.50], ['2. Hawaiian pizza', 8.50], ['3. Garlic cheese pizza (with choice of sauce)', 8.50],['4. Cheese pizza (with choice of sauce)', 8.50], ['5. Ham and cheese pizza', 8.50], ['6. Beef & onion pizza', 8.50], ['7. Vegetarian pizza', 8.50], ['8. BBQ chicken & bacon aioli pizza', 13.50], ['9. Boneless pizza (italian style anchovy with no bones)', 13.50], ['10. Pizza margherita', 13.50],['11. Meat-lover’s pizza', 13.50],['12. Tandoori pizza', 13.50]
]
#-----------------------------details------------------------------------
def pick_or_deli():
global delivery
delivery = input("P - pick up / D - delivery:")
delivery = delivery.upper() #Changes the letter inputted to an uppercase
if delivery == "D": #statement if person choosed delivery
while running == True:
global customer_name #This can be called when printing out final order and details
customer_name = input("Name:")
if not re.match("^[a-zA-Z ]*$", customer_name): #Checks whether input is letters only
print("Please use letters only")
elif len(customer_name) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
customer_name = customer_name.title()
break #Breaks the loop when valid input has been entered
while running == True:
global customer_telephone
customer_telephone = input("Telephone:")
if not re.match("^[0-9 ]*$", customer_telephone): #Checks whether input is numbers only
print("Please use numbers only")
elif len(customer_telephone) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
while running == True:
global house_no
house_no = input("House number:")
if not re.match("^[0-9 /]*$", house_no): #Checks whether input is numbers only
print("Please use numbers only")
elif len(house_no) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
while running == True:
global street_name
street_name = input("Street name:")
if not re.match("^[a-zA-Z ]*$", street_name): #Checks whether input is letters only
print("Please use letters only")
elif len(street_name) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
street_name = street_name.title()
break #Breaks the loop when valid input has been entered
elif delivery == "P": #statement for if person choosed pickup
while running == True:
global customer_name_2
customer_name_2 = input("Name:")
if not re.match("^[a-zA-Z ]*$", customer_name_2): #Checks whether input is letters only
print("Please use letters only")
elif len(customer_name_2) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
customer_name_2 = customer_name_2.title()
break #Breaks the loop when valid input has been entered
while running == True:
global customer_telephone_2
customer_telephone_2 = input("Telephone:")
if not re.match("^[0-9 ]*$", customer_telephone_2): #Checks whether input is numbers only
print("Please use numbers only")
elif len(customer_telephone_2) == 0: #User has not inputted anything, therefore invalid input
print("Please enter a valid input")
else:
break #Breaks the loop when valid input has been entered
else:
print("Please enter P or D")
pick_or_deli()
pick_or_deli()
#-----------------------------order script-------------------------------------
print('''\nWelcome to ~~~~~ Dream Pizza ~~~~~
To pick an order from the Menu pick the designated number that is next to the product.\n
From 1 for Pepperoni pizza.\n
Or 2 for Hawaiian pizza.\n
and so on.\n
The delivery cost is $3\n
To cancel the order throughout press 0 and it will reset itself.\n
But first decide how many pizza you want.\n''')
time.sleep(3.0)
#--------------menu text and design can be called again------------------------
def menu_design():
print(*MENU, sep = "\n")\
menu_design()
#------------------deciding how many pizzas they want---------------------------
def order():
global pizza_no
while True:
try: #Validating the inputs
pizza_no = int(input('''\nNo. of pizzas you want (min 1 - max 5):\n'''))
if pizza_no < 1:
print("Please order between 1 - 5 pizzas") #Checks whether input is between 1 and 5
continue
if pizza_no > 12:
print("Please order between 1 - 5 pizzas")
continue
else:
break #Breaks the loop when valid input has been entered
except ValueError: #Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
order()
#--------------------------------picking pizza-----------------------------------
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
for i in range(len(customerOrder)):
cost=+customerOrder[i][1]
global total_cost
total_cost=0
#Sum of the pizzas
global Combined_Total
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost=+cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost=+cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
Choice_of_pizza()
#-----------------------------------reciept---------------------------------------
def customerDetails(): #Prints customer order and details
if delivery == "D": #if person choosed delivery
print ("")
print ("CUSTOMER and ORDER DETAILS")
print ("")
print ('Name: {}' .format(customer_name))
print ('Telephone: {}' .format(customer_telephone))
print ('Address:')
print (house_no, street_name)
print ("")
print ('ORDER:')
print(*customerOrder, sep = "\n")
print ('Total Price: $ {:.2f}' .format(total_cost))
print ('Total Price + Delivery Cost: $ {:.2f}' .format(Combined_Total))
else: #if person choosed pickup don't have to speccify
print ("")
print ("CUSTOMER and ORDER DETAILS")
print ("")
print ('Name:{}' .format(customer_name_2))
print ('Telephone:{}' .format(customer_telephone_2))
print ("")
print ('ORDER:')
print(*customerOrder, sep = "\n")
print ('Total Price: {:.2f}' .format( total_cost))
customerDetails()
#-----------confrimation of customers order proceed or cancel---------------------
print ("")
def confirm(): #Confirms details of customer and order
confirmation = input("Y - confirm order / N - cancel order:")
confirmation = confirmation.upper() #Changes the letter inputted to an uppercase
if confirmation == "Y": #if Y is entered, order is confirmed
print("DETAILS CONFIRMED")
elif confirmation == "N": #if N is entered, order is cancelled
print("DETAILS CANCELLED - order has been reset")
customerOrder[:] = []
cost[:] = []
menu_design()
order()
Choice_of_pizza()
customerDetails()
confirm()
else:
print("Please enter Y or N") #If anything other than Y or N is entered, it will ask again
confirm()
confirm()
#----statement im customer would like to order more or finalised there order---
print ("")
def order_more(): #Placing another order
order_more = input("Z - order more / x - exit program:")
order_more = order_more.upper() #Changes the letter inputted to an uppercase
'''cost[:] = []'''
if order_more == "Z":
menu_design() #Calls the functions - will run the code that the def defines
order()
Choice_of_pizza()
customerDetails()
confirm()
print ("")
print ("THANK YOU FOR YOUR SHOPPING AT DREAMS PIZZA")
if delivery == "D":
print ("Your order will be delivered in 25mins") #Ending statement
elif delivery == "P":
print ("Your order will be ready to pick up in 20mins") #Ending statement
elif order_more == "X":
print ("")
print ("THANK YOU FOR YOUR ORDER")
if delivery == "D":
print ("Your order will be delivered in 25mins") #Ending statement
elif delivery == "P":
print ("Your order will be ready to pick up in 20mins") #Ending statement
else:
print ("Please enter X or Z") #If anything other than X or Z is entered, it will ask again
order_more()
order_more()
Also why I only have one list? it is because I was required to only use one
Code Issues:
For addition assignment the syntax is:
x += y # this assigns x to (x + y)
Not:
x = +y # this assign x to y
Glbols are not causing a problem in your code, but are usually frowned upon and negatively reflect on programming skills i.e. Why are Global Variables Evil?.
Choice_of_pizza function fix
def Choice_of_pizza():
for i in range(1,pizza_no +1): #Repeats a number of times (number user has inputted)
while True:
try: #Validating inputs
pizza_kind = int(input("Choice of pizza(s):"))
if pizza_kind < 1:
print("Refer to PIZZA MENU for number order")
continue
if pizza_kind > 12:
print("Refer to PIZZA MENU for number order")
continue
else:
pizza = pizza_kind - 1 #Makes the list start at 1
print('\nYou have chosen {}\n'.format(MENU[pizza_kind-1][0]))
customerOrder.append(MENU[pizza_kind-1])
cost = 0
for i in range(len(customerOrder)):
cost += customerOrder[i][1]
global total_cost # globals are discouraged
total_cost=0
#Sum of the pizzas
global Combined_Total # globals are discouraged
if delivery == "D": #Adds $3 dollars to the total cost if delivery
total_cost += cost
Combined_Total = total_cost + Delivery_cost
else: #Price stays the same if pick up
total_cost += cost
Combined_Total = total_cost
break
except ValueError:#Validating inputs - accepts only numbers and can't be left blank
print("Please use numbers only")
continue
I have the following code for a random number guessing game:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = input()
if guess1 == number:
print ("Good job, you got it!")
while guess1 != number:
if guess1 > number:
print ('your guess is too high')
if guess1 < number:
print ('your guess is too low')
which throws the error that > or < cannot be used between str and int.
What should I do so it doesn't trigger that error?
There are two errors in your code.
You need to convert the input for guess1 from a string (by default) to an integer before you can compare it to the number (an integer).
The while loop will never stop since you are not letting the user input another value.
Try this:
import random
number = random.randint(1,100)
name = input('Hi, Whats your name?')
print ("Well", name, "i am thinking of a number between 1 and 100, take a guess")
guess1 = int(input()) # convert input from string to integer
while guess1 != number:
if guess1 > number:
print ('your guess is too high. Try again.')
elif guess1 < number:
print ('your guess is too low. Try again.')
guess1 = int(input()) # asks user to take another guess
print("Good job, you got it!")
You can make use of a while loop here - https://www.tutorialspoint.com/python/python_while_loop.htm
The logic should be:
answer_is_correct = False
while not answer_is_correct :
Keep receiving input until answer is correct
I hope this works for you:
import random
myname = input('Hello, what is your name?')
print('Well',myname,'am thinking of a number between 1 and 100')
number = random.randint(1,100)
guess = 0
while guess < 4:
guess_number = int(input('Enter a number:'))
guess += 1
if guess_number < number:
print('Your guess is to low')
if guess_number > number:
print('Your guess is to high')
if guess_number == number:
print('Your guess is correct the number is',number)
break
if guess == 4:
break
print('The number i was thinking of is',number)
from random import randint
print("you wanna guess a number between A to B and time of guess:")
A = int(input("A:"))
B = int(input("B:"))
time = int(input("time:"))
x = randint(1, 10)
print(x)
while time != 0:
num = int(input("Enter: "))
time -= 1
if num == x:
print("BLA BLA BLA")
break
print("NOPE !")
if time == 0:
print("game over")
break
Code in Python 3 for guessing game:
import random
def guessGame():
while True:
while True:
try:
low, high = map(int,input("Enter a lower number and a higher numer for your game.").split())
break
except ValueError:
print("Enter valid numbers please.")
if low > high:
print("The lower number can't be greater then the higher number.")
elif low+10 >= high:
print("At least lower number must be 10 less then the higher number")
else:
break
find_me = random.randint(low,high)
print("You have 6 chances to find the number...")
chances = 6
flag = 0
while chances:
chances-=1
guess = int(input("Enter your guess : "))
if guess<high and guess>low:
if guess < find_me:
print("The number you have entered a number less then the predicted number.",end="//")
print("{0} chances left.".format(chances))
elif guess > find_me:
print("The number you have entered a number greater then the predicted number.",end="//")
print("{0} chances left.".format(chances))
else:
print("Congrats!! you have succesfully guessed the right answer.")
return
else:
print("You must not input number out of range")
print("{0} chances left.".format(chances))
print("The predicted number was {0}".format(find_me))
You can conditions within the while loop to check if its right. It can be done the following way.
import random
print('Hello! What is your name?')
myName = input()
number = random.randint(1, 100)
print('Well, ' + myName + ', I am thinking of a number between 1 and 100.')
inputNumber = int(raw_input('Enter the number')
while inputNumber != number:
print "Sorry wrong number , try again"
inputNumber = int(raw_input('Enter the number')
print "Congrats!"
from random import *
def play_game():
print("Let's play a number guessing game")
# Selecting a random number between 1 and 100
number = randint(1, 100)
choice = int(input("I am thinking of a number between 1 and 100. Could you guess what it is? "))
# Guide the user towards the right guess
# Loop will continue until user guesses the right number
while choice != number:
if choice < number:
choice = int(input("Too low. Can you try again? "))
elif choice > number:
choice = int(input("Too high. Can you try again? "))
continue_game = input("You guessed it right! Would you like to play it again? (Y/N) ")
# Restart the game if user wishes to play again
if continue_game == "Y":
print("--" * 42)
play_game()
else:
print("Thanks for playing :)")
exit(0)
play_game()