I have a school project for making a betting programme. It asks for the account balance and checks if the user can play more or tells them to stop if they are broke. I do not know how to add a while loop that checks if they have enough money to play again and asks them if they want to play again.
The code is below:
import random
for x in range (1):
x=random.randint(1,31)
point=int(0)
savings = int(input("Enter your total amount of money you have in your bank account"))
betmoney = int(input("Enter the money you are betting"))
num = int(input("Enter a number between 1 and 30"))
bef = (savings - betmoney)
if num == x:
print ("you have guessed the mystery number well done. Your earnings just got multiplied by 6")
point = point + 6
import random
for x in range (1):
x=random.randint(1,31)
if num % 2 == 0:
print("since your number is even, you get double your money back")
point = point + 2
else:
point = point + 0
if num % 10 == 0:
print("since your number is a multiple of 10 you get 3x your money back")
point = point + 3
else:
point = point + 0
for i in range(2,num):
if (num % i) == 0:
point = point +0
break
else:
print(num,"is a prime number so you will get 5x your money back")
point = point + 5
if num < 5:
print("since your number is lower than 5 you get double your money back")
point = point + 2
else:
point = point + 0
else:
print("unfortunatley you have nor guessed the right mystery number. better luck next time.")
win = (point * betmoney)
aft = (bef + win)
print ("Your bank account after playing is now" , aft)
print ("You have won" , win)
print ("btw the mystery number was" , x)
I added a while loop and i came up with this.
The following is the code:
import random
point = int(0)
savings = int(input("Enter your total amount of money you have in your bank account : "))
play = bool(True)
while savings > 0 and play:
for x in range (1):
x = random.randint(0, 30)
betmoney = int(input("Enter the money you are betting : "))
if savings >= betmoney:
savings = savings - betmoney
else:
print("Please enter an amount less than ", savings)
continue
num = int(input("Enter a number between 1 and 30 : "))
if num == x:
print("you have guessed the mystery number well done. Your earnings just got multiplied by 6")
point = point + 6
import random
for x in range (1):
x = random.randint(1, 31)
if num % 2 == 0:
print("since your number is even, you get double your money back")
point = point + 2
else:
point = point + 0
if num % 10 == 0:
print("since your number is a multiple of 10 you get 3x your money back")
point = point + 3
else:
point = point + 0
for i in range(2,num):
if (num % i) == 0:
point = point +0
break
else:
print(num,"is a prime number so you will get 5x your money back")
point = point + 5
if num < 5:
print("since your number is lower than 5 you get double your money back")
point = point + 2
else:
point = point + 0
else:
print("unfortunatley you have nor guessed the right mystery number. better luck next time.")
win = (point * betmoney)
aft = (savings + win)
print("Your bank account after playing is now", aft)
print("You have won", win)
print("The mystery number was" , x)
if savings > 0:
play = bool(input("Do you want to play again (Y/N)? "))
print("You have no more money left. You are broke. Thanks for playing though!")
If you are using an if statement, you could try something by setting a stopping point for the amount of money you need to play (e.g. you must have $1,000 to play).
For now, let's assume that you need $1000 dollars to play, and we'll call that in your already present variable aft. The code would be something along the following:
while aft > 1,000:
#confirms that the user can play
print("You can play! Have fun!")
#(Enter your current code here)
if aft <1,000:
print("Sorry, but your current value of " + aft + "is not enough to play. Please earn more money.")
exit()
Related
When executing this it only runs through the initial if elif statement. If I reach 0 it returns the proper print statement along with when I'm subtracting numbers. However if I try to subtract to reach a negative number and therefore reach the exception, it doesn't print the statement below and reloop through like I want it to.
number = 15
print("Subtract the number", number, "until it has reached 0")
while number != 0:
try:
x = int(input())
number = number-x
if number > 0:
print("You have", number, "points to spend!")
elif number == 0:
print("You have used all your points!")
break
except number < 0:
print("You don't have enough points for that!")
continue
except is used for catching errors. You want this:
while number != 0:
x = int(input())
if number - x > 0:
number -= x
print("You have", number, "points to spend!")
elif number == x:
number = 0
print("You have used all your points!")
break
else:
print("You don't have enough points for that!")
I am new to python and i getting so mad at this one issue which i dont know how to solve and there seems to be no help on the internet which works. If you know what the issue is please help.
guesses = 0
usernum = int(input("pick a number betwen 1 and 10"))
if usernum > 10 or usernum < 1:
print("That number is bigger than 10 or smaller than 1. Try again")
usernum = int(input("pick a number betwen 1 and 10"))
if usernum > 10 or usernum < 1:
print("You failed... again. wow thats sad just restart the program")
print("okay now i will find what your number is...")
while not compnum == usernum:
import random
compnum = random.int(1, 10)
guesses = gueses +1
if not compnum == usernum:
return
the error is
File "", line 16
return
^^^^^^
SyntaxError: 'return' outside function
return must be used in a function. Like this:
def fun():
statements
.
.
return [expression]
On line 14 you wrote guesses = gueses +1, guesesis not defined
Your code should look like this:
import random # import a the top
compnum = random.randint(1, 10) # generate number once
guesses = 0
usernum = int(input("pick a number betwen 1 and 10: "))
if usernum > 10 or usernum < 1:
print("That number is bigger than 10 or smaller than 1. Try again: ")
usernum = int(input("pick a number betwen 1 and 10: "))
if usernum > 10 or usernum < 1:
print("You failed... again. wow thats sad just restart the program: ")
print("okay now i will find what your number is...: ")
while not compnum == usernum:
usernum = int(input("pick a number betwen 1 and 10: "))
guesses = guesses +1
if not compnum == usernum:
continue
You cannot use return outside of a function.
If you want to stop a loop, you need to use break or you make the whole a function. But in fact there is no need to use that if statement, the while loop will stop anyway. The following version of the code does what you want.
import random
def guess(number):
guesses = 1
compnum = random.randint(1, 10)
while not compnum == usernum:
compnum = random.randint(1, 10)
guesses = guesses + 1
return f"number: {compnum}", f"guesses: {guesses}"
usernum = int(input("pick a number betwen 1 and 10"))
if usernum > 10 or usernum < 1:
print("That number is bigger than 10 or smaller than 1. Try again")
usernum = int(input("pick a number betwen 1 and 10"))
if usernum > 10 or usernum < 1:
print("You failed... again. wow thats sad just restart the program")
print("okay now i will find what your number is...")
print(guess(usernum))
import random
import math
low = int(input("Enter Lower number:- "))
up = int(input("Enter Upper number:- "))
# generating random number between the given numbers
x = random.randint(low, up)
print("\n\tYou've only ", round(math.log(up - low + 1, 2)),
" chances to guess the integer!\n")
# Initializing the numberof times
count = 0
# for calculation of minimum guess
while count < math.log(up - low + 1, 2):
count += 1
# taking guessing number as input
guess = int(input("Guess a number:- "))
# testing
if x == guess:
print("Congratulations you did it in ", count, " try")
# Once guessed, loop will break
break
elif x > guess:
print("You guessed too small!")
elif x < guess:
print("You Guessed too high!")
# If Guessing is more than required guesses
if count >= math.log(up - low + 1, 2):
print("\nThe number is %d" % x)
print("\tBetter Luck Next time!")
can any one explain this line math.log(up - low + 1, 2)) , why is this log function and comma 2
The idea behind is that you can find the solution using binary search https://en.m.wikipedia.org/wiki/Binary_search_algorithm
The 2 in the logarithm argument is the logarithm base.
I'm very new to programming and I've encountered a problem with a basic guessing game I've been writing.
x is a random number generated by the computer. The program is supposed to compare the absolute value of (previous_guess - x) and the new guess minus x and tell the user if their new guess is closer or further away.
But the variable previous_guess isn't updating with the new value.
Any help would be appreciated.
Here is the code so far:
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
while True:
previous_guess = 0 # Should update with old guess to be compared with new guess
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Your previous guess is being reinitialized every time you loop. This is a very common error in programming so it's not just you!
Change it to:
previous_guess = 0
while True:
#Rest of code follows
Things you should be thinking about when stuff like this shows up.
Where is your variable declared?
Where is your variable initialized?
Where is your variable being used?
If you are unfamiliar with those terms it's okay! Look em up! As a programmer you HAVE to get good at googling or searching documentation (or asking things on stack overflow, which it would appear you have figured out).
Something else that is critical to coding things that work is learning how to debug.
Google "python debug tutorial", find one that makes sense (make sure that you can actually follow the tutorial) and off you go.
You're resetting previous_guess to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want:
previous_guess = 0
while True:
guess = ....
You need to initialize previous guess before while loop. Otherwise it will be initialized again and again.
You have updated previous guess in multiple places. You can make it simpler:
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = 0 # Should update with old guess to be compared with new guess
while True:
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
print("Getting warmer...")
else:
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
previous_guess = guess #####
You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this:
Add before while { previous_guess = x }
Add After While { previous_guess += x }
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = x
while True:
# Should update with old guess to be compared with new guess
previous_guess += x
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Picture When u win
Picture When u loose
I was wondering if anyone could help point me in the right direction! I'm a beginner and I'm totally lost. I'm trying to make a Sentinel controlled loop that asks the user to "enter the amount of check" and then ask "how many patrons for this check". After it asks the user then enters it until they type -1.
once user is done inputting it is suppose to calculate the total,tip,tax of each check with an 18% tip for anything under 8 patrons and 20%tip for anything over 9 and a tax rate of 8%.
and then it should add up the Grand totals.
ex: check 1 = 100$
check 2 = 300
check 3 = 20
Total checks = $420
I'm not asking for someone to do it for me but just if you could point me in the right direction, this is all i have so far and im stuck.
As of right now the code is horrible and doesn't really work.
I completed it in Raptor and it worked perfectly I just don't know how to convert it to python
sum1 = 0
sum2 = 0
sum3 = 0
sum4 = 0
sum5 = 0
check = 0
print ("Enter -1 when you are done")
check = int(input('Enter the amount of the check:'))
while check !=(-1):
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
tip = 0
tax = 0
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
total = check + tax + tip
sum1 = sum1 + check
sum2 = sum2 + tip
sum3 = sum3 + patron
sum4 = sum4 + tax
sum5 = sum5 + total
print ("Grand totals:")
print ("Total input check = $" + str(sum1))
print ("Total number of patrons = " + str(sum3))
print ("Total Tip = $" +str(sum2))
print ("Total Tax = $" +str(sum4))
print ("Total Bill = $" +str(sum5))
Your code runs fine, but you have some logic problems.
It appears you're planning to deal with multiple checks at the same time. You'll probably want to use a list for that, and append checks and patrons to it until check is -1 (and don't append the last set of values!).
I think the real issue you're having is that to leave the loop, check must be equal to -1.
If you follow that a bit further down, you continue to work with check, which we now know is -1, regardless of what happened previously in the loop (check is overwritten every time).
When you get to these lines, then you have a real problem:
if patron <= 8:
tip = (check * .18)
elif patron >= 9:
tip = (check * .20)
# This is the same, we know check == -1
if patron <= 8:
tip = (-1 * .18)
elif patron >= 9:
tip = (-1 * .20)
At this point you probably won't be able to do anything interesting with your program.
EDIT: A bit more help
Here's an example of what I'm talking about with appending to a list:
checks = []
while True:
patron = int(input('Enter the amount of patrons for this check.'))
check = int(input('Enter the amount of the check:'))
# here's our sentinal
if check == -1:
break
checks.append((patron, check))
print(checks)
# do something interesting with checks...
EDIT: Dealing with cents
Right now you're parsing input as int's. That's OK, except that an input of "3.10" will be truncated to 3. Probably not what you want.
Float's could be a solution, but can bring in other problems. I'd suggest dealing with cents internally. You might assume the input string is in $ (or € or whatever). To get cents, just multiply by 100 ($3.00 == 300¢). Then internally you can continue to work with ints.
This program should get you started. If you need help, definitely use the comments below the answer.
def main():
amounts, patrons = [], []
print('Enter a negative number when you are done.')
while True:
amount = get_int('Enter the amount of the check: ')
if amount < 0:
break
amounts.append(amount)
patrons.append(get_int('Enter the number of patrons: '))
tips, taxs = [], []
for count, (amount, patron) in enumerate(zip(amounts, patrons), 1):
tips.append(amount * (.20 if patron > 8 else .18))
taxs.append(amount * .08)
print('Event', count)
print('=' * 40)
print(' Amount:', amount)
print(' Patron:', patron)
print(' Tip: ', tips[-1])
print(' Tax: ', taxs[-1])
print()
print('Grand Totals:')
print(' Total amount:', sum(amounts))
print(' Total patron:', sum(patrons))
print(' Total tip: ', sum(tips))
print(' Total tax: ', sum(taxs))
print(' Total bill: ', sum(amounts + tips + taxs))
def get_int(prompt):
while True:
try:
return int(input(prompt))
except (ValueError, EOFError):
print('Please enter a number.')
if __name__ == '__main__':
main()