The program is to accept a choice from the user.
Choice 1 to check the deposit
Choice 2 to make a deposit - when I entered choice two it should accept a deposit that is greater than 0 but less than 100,000, if this condition is not met then the program should prompt the user to enter the deposit until the condition is met.
If the condition is met, then the program should add the deposit entered to 30,000 and print the result.
My problem is even if the deposit is greater than 100,000 or less than 0, it is still printing the result and it should only prompt the user to enter the deposit until it is greater than 0 or less than 100,000.
What could be the error or problem in my code?
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
if choice == 2:
while True:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
if(deposit < 0 and deposit > 100000):
continue;
newbalance = deposit + balance
print("Your balance is $", newbalance)
Hey please see below for the code I think you want. From what I understand in terms of what you want, your problem was that your script was still going to print the deposit irrespective of invalid values.
In your code, after the first if statement you are telling python to just continue, even if the first if statement evaluates to true.
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
if choice == 2:
while True:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
#if(deposit < 0 and deposit > 100000):
#continue;
newbalance = deposit + balance
print("Your balance is $", newbalance)
break
The problem here is in the 2nd if condition of while loop. You shall use or logical operator instead of and as
if(deposit < 0 and deposit > 100000):
means that simultaneously deposit < 0 and greater than 100000 which is false always.
Secondly don't use ; after continue
The code should be as follows:
if (deposit < 0 or deposit > 100000):
Hope this helps you!
Fixing conditions in original code:
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
elif choice == 2:
while True:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
newbalance = deposit + balance
print("Your balance is $", newbalance)
But the above code will keep on adding, better code can be:
while True:
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
elif choice == 2:
deposit= float(input("Enter the deposit you would like to make:"))
if deposit < 0 or deposit > 100000:
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
newbalance = deposit + balance
print("Your balance is $", newbalance)
Always check user input. You need to offer the user some way of exiting the program (menu option)
You may find this pattern instructive:
balance = 30_000
MAX = 100_000
while True:
try:
option = int(input('Enter 1 to check balance\nEnter 2 to deposit\nEnter 3 to withdraw\nEnter 9 to exit\n: '))
if not option in {1, 2, 3, 9}:
raise ValueError('Invalid option')
if option == 9:
break
if option != 1:
amount = float(input('Enter amount: '))
if amount < 0 or amount > MAX:
raise ValueError(f'Amount cannot be negative of over {MAX}')
if option == 2:
balance += amount
else:
balance -= amount
print(f'Current balance = {balance:.2f}')
except ValueError as e:
print(e)
Firstly, You have the same condition in the two if statments on line 17 and 21. It can be replaced with one single IF statment.
So you're checking if the deposit is less than 0 or greater than 100000. If it fits that condition you want display an error message and re-prompt the user for the deposit withnin the stipulated range. When the user enters a number withnin the stipulated range the program should 'break' out of the while loop and print the balance.
If it fits the condition, display the error message and the use the 'continue' statment to restart the loop and prompt the user continously for a deposit until the user enters a number which fits the condition. if the user enters a deposit greater than 0 or less than 100000. You would want to break out of the loop using the 'break' statment and display the new deposit.
if(deposit < 0 or deposit > 100000):
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
else:
break
Also I think you intended to place the line 25 and 26 where you are calculating th new deposit and displaying the deposit outside the while loop. Lines 25 and 26 should only be exceuted once the the user has entered the correct deposit which is withnin the stipulated range. So it should be outside the while loop
Your full code should similar to this:
balance = 30000
choice = int(input("Enter 1 to Check Balance\nEnter 2 to deposit\nEnter 3 to withdrawl\n:"))
if choice == 1:
print("Your balance is $",balance)
if choice == 2:
while True:
deposit = float(input("Enter the deposit you would like to make:"))
if(deposit < 0 or deposit > 100000):
print("INVALID ENTRY! The deposit must not be less than 0 or greater than 100000.")
continue
else:
break
newbalance = deposit + balance
print("Your balance is $", newbalance)
List item
Related
I am a beginner, and I was working on a simple credit program. I want it to work so every time I add an input of a number it gets stored in a variable that shows my total balance. The problem right now is that the program is only a one use program so the input i enter does not get saved into a variable so that when I enter another value it gets added onto a previous input. Code is below:
Purchase = int(input("How much was your purchase? "))
credit_balance = 0
credit_limit = 2000
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total == credit_limit:
print("You have reached your credit limit!", Total)
You'll need to introduce a while loop to keep it going. Try this:
credit_limit = 2000
credit_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
Total = credit_balance + Purchase
print("Your account value right now: ", Total)
if Total >= credit_limit:
print("You have reached your credit limit!", Total)
Note that this will keep it going indefinitely. You'll need to add logic for the user to input a command to exit. You can use something like:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? Or type Exit to exit."))
Then:
if Purchase == 'Exit':
exit()
Edit:
Here's a version that retains the balance each time. The key difference is that a variable can equal its previous value plus a change. I rewrote a few things for clarity.
credit_limit = 2000
current_balance = 0
while True:
print('Welcome to the Credit Card Company')
Purchase = int(input("How much was your purchase? "))
current_balance = current_balance + Purchase
print("Your account value right now: ", current_balance)
if current_balance == credit_limit:
print("You have reached your credit limit!", current_balance)
You can get user input infinitely if you use a while loop:
credit_balance = 0
credit_limit = 2000
while True:
purchase = int(input("How much was your purchase? "))
credit_balance += purchase # add purchase to credit_balance
print("Your account value right now: ", credit_balance)
if credit_balance >= credit_limit:
print("You have reached/exceeded your credit limit!", Total)
A good exercise would be to add some logic to ensure purchases don't exceed the credit limit.
I am creating a coin return calculator. I have all the code wrote but I can't figure out how to only display the coins that are needed instead of getting the coins I don't need.
Enter change amount to convert: 3
0 quarter(s)
0 dime(s)
0 nickle(s)
3 penny(ies)
Want to calculate another amount? (y/n):
I want to not display the quarters, dimes or nickles.
while True:
change = input("Enter change amount to convert: ")
if str(change).isnumeric():
change = int(change)
if change < 100:
quarters, dimes, nickels, pennies = coinCalc(change)
print(quarters, "quarter(s)")
print(dimes, "dime(s)")
print(nickels, "nickle(s)")
print(pennies, "penny(ies)")
print("Want to calculate another amount? (y/n): ")
answer = input()
if answer == "n":
print("Bye!")
break
else:
print("Error! Invalid integer entered please try again.")
else:
print("Error! Invalid integer entered please try again.")
You could add an if-statement to check whether the coin's value is zero. If so, then don't print it.
if quarters != 0:
print(quarters, "quarter(s)")
if dimes != 0:
print(dimes, "dime(s)")
if nickels != 0:
print(nickels, "nickle(s)")
if pennies != 0:
print(pennies, "penny(ies)")
print("Want to calculate another amount? (y/n): ")
I decided to make a small project to test my skills as I continue to learn Python in my free time.
The game consists of the user guessing the right number that is randomly generated within a certain amount of tries. The user first enters the range of numbers they want to guess from. Then they get their first try at guessing the right number (I have the randomly generated number displayed on purpose to test my code as I continue). I cannot figure out why when I enter the same number as the randomly generated number, I get the error that would pop up when you guess the wrong number. But if I enter that same number after I am prompted to guess for the randomly generated number again, I get a success note prompted to me. I've been trying different variations all day.
import random
print("Guessing Game")
rangeAmount = int(input("From 1 to what number do you want to guess from (Maximum amount is 50)? "))
correctNum = random.randint(1, rangeAmount)
wrongCount = 0
userScore = 0
print("-" * 50)
while rangeAmount:
if 1 < rangeAmount < 10:
guesses = 3
print("Guesses allowed: 3")
break
if 1 < rangeAmount < 20:
guesses = 4
break
if 1 < rangeAmount < 30:
guesses = 5
break
if 1 < rangeAmount < 40:
guesses = 6
break
if 1 < rangeAmount < 50:
guesses = 7
break
print("Correct number: " + str(correctNum))
print("Guess amount: " + str(guesses))
print("-" * 50)
userGuess = input("Make a guessing attempt for the correct number: ")
while userScore != 3:
if wrongCount != guesses:
if userGuess is correctNum:
userScore += 1
print("You got the right answer")
break
else:
wrongCount += 1
print("Current guess count: {}".format(wrongCount))
userGuess = int(input("Wrong answer, try again: "))
if wrongCount == guesses:
print("Out of guesses, score is : {}".format(userScore))
userScore -= 1
break
if userScore == 3:
print("You won the game!")
Output:
Guessing Game
From 1 to what number do you want to guess from (Maximum amount is 50)? 23
--------------------------------------------------
Correct number: 5
Guess amount: 5
--------------------------------------------------
Make a guessing attempt for the correct number: 5
Current guess count: 1
Wrong answer, try again: 5
You got the right answer
Process finished with exit code 0
First, your maximum range is 50, but it is not included in your first while loop (ends at 49), change the last line to <= 50. You can remove the while loop, and change the if statements to if/elifs. Second, your indentation is off in the while userScore != 3: loop, but that could just be a copy/paste error.
And now for the most likely cause of the error,
userGuess = input("Make a guessing attempt for the correct number: ")
is a string, don't forget to make it an int before you compare it to another int.
so i'm writing a program that's supposed to take 2 inputs of data as int's for a user's debt. the variables are debt1 and debt2. it's supposed to add these two values together and then depending on the user's input, it's supposed to give out a specific response using the "if/else" loop i've created. the problem is that the program only prints out the response from the first "if" statement no matter what the input is, it always prints out "your debt is dangerously high". how do i correct this?
** Here is my code **
Name = input("Please enter your name: ")
debt1 = int(input("Please enter your first debt amount: "))
debt2 = int(input("Please enter your second debt amount: "))
totalDebt = debt1+debt2
print("Your total debt is ", totalDebt)
if (totalDebt > 900,000):
print("Your debt is dangerously high ", Name)
elif((totalDebt >= 450,000 and totalDebt < 900,000)):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
Don't use commas in numbers:
if totalDebt > 900000:
print("Your debt is dangerously high ", Name)
elif (totalDebt >= 450000 and totalDebt < 900000):
print("We can help you reduce your debt.")
else:
print("Congratulations, you know how to manage debt.")
As #rdas said, you can use _ for long numbers, in place of ,
This is a module in part of a larger "vending machine" I am working on. I have ran into some issues, though. If they do not pay enough ($1.75) they are asked to enter an additional amount of money. Part of my problem is that I don't know what operations I should do to change the deficit inside of a loop. All of the things I've tried has resulted in errors like "input expected at most 1 arguments, got 3" and so forth.
selection = 5
loopCount = 0
deposit = 0
cost = 1.75
print("It costs $",cost,".")
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n"))
deficit = cost - deposit
change = deposit - cost
if deposit < cost:
while deficit > 0 and loopCount < 1:
??? = float(input("Please enter an additional $",deficit,"."))
loopCount += 1
if deposit >= cost:
print("Thank you for purchasing item#",selection,". Your change is $",change,".")
This works for me. Do make sure to increase the loopCount, as right now, it will not loop more than once.
selection = 5
loopCount = 0
deposit = 0
cost = 1.75
print("It costs $",cost,".")
deposit = float(input("Enter your money amount (e.g. 1.5 for $1.50, .50 for $0.50, etc.):\n--\n"))
deficit = cost - deposit
change = deposit - cost
if deposit < cost:
while deficit > 0 and loopCount < 1:
deficit -= float(input("Please enter an additional ${}.".format(deficit)))
loopCount += 1
if deposit >= cost:
print("Thank you for purchasing item#",selection,". Your change is $",change,".")
Assuming you don't want to break from the loop until they pay enough money you could do this:
while abs(deficit) < cost:
added = float(input("Please enter an additional $",deficit,"."))
deficit = cost - deposit - added
The abs function will output the absolute value so you can compare it directly to cost.
Somethings to note though, you might want to do error checking on your inputs.
Also, if you do want to be able provide a mechanism for the user to break from the loop, you could add a boolean true or false (instead of loop count) that is attached to some other input like "Do you want to insert more money? y or n"