How do I stop the loop from going past 12 months? - python

I need the loop to stop at 12 months and not count all the way up to how many months it takes to reach the goal. I just need it to print how many months it takes to reach the goal but not count all the way to it. I only need it to go up to 12 months. For example if I input an original deposit for 1000, 4.5 interest rate, 12 months, and 1200 goal amount then I want it to only show it counting to 12 months not 49. I still need it to print out how many months it takes to reach the goal at the end but I do not need it to show it counting all the way up to 49. I am sorry if this sounds confusing.
#Keep asking until the user puts in a positive numeric value using loops
fDeposit = 0
while fDeposit <= 0:
try:
fDeposit = float(input('What is the original deposit (positive value): '))
if fDeposit <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
fInterest = 0
while fInterest <= 0:
try:
fInterest = float(input('What is the Interest Rate (positive value): '))
if fInterest <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
iMonths = 0
while iMonths <= 0:
try:
iMonths = int(input('What is the number of months (positive value): '))
if iMonths <= 0:
print("Input must be a positive numerical value: ")
except ValueError:
print("Input must be a numeric value")
fGoal = None
while fGoal == None:
try:
fGoal = float(input('What is the goal amount (Can enter 0 but not negative): '))
if fGoal < 0:
print("Input must be a positive numerical value: ")
fGoal = None
except ValueError:
print("Input must be a numeric value")
# Calculate Interest. First convert the variable to a decimal by dividing by 100 then divide
that by 12
fMonthlyInterest= (fInterest/100/12)
#Output the number of months the user has supplied and get account balance
i = 1
fAccountBalance = fDeposit
while i <= fAccountBalance:
if fAccountBalance >= fGoal:
break
fInterestForMonth = (fAccountBalance * fMonthlyInterest)
#Add the interest for the month to the deposit to get the new Account Balance
fAccountBalance += fInterestForMonth
print('Month: ',i, 'Account Balance is: $',format(fAccountBalance, ",.2f"))
i += 1
# Calculate how many months it will take of compounding to reach the goal amount
GoalFormatted = "{:.2f}".format(fGoal)
CompoundedSavingsAccountBalance = fMonthlyInterest + fAccountBalance
while CompoundedSavingsAccountBalance < fGoal:
iMonths += 1
print('It will take: ',i-1, 'months to reach the goal of $', GoalFormatted)

to solve your problem, add "if i < 12:" after line 52, and indent the next line where you printing the month & the account balance. The completed section is below.
i = 1
fAccountBalance = fDeposit
while i <= fAccountBalance:
if fAccountBalance >= fGoal:
break
fInterestForMonth = (fAccountBalance * fMonthlyInterest)
#Add the interest for the month to the deposit to get the new Account Balance
fAccountBalance += fInterestForMonth
if i <= 12:
print('Month: ',i, 'Account Balance is: $',format(fAccountBalance, ",.2f"))
i += 1

Related

I get a syntaxt error when I try to run the program

I get a syntax error on the last else statement. This is supposed to be a grade calculator. If someone enters anything that isn't between 0 and 100, then the program should send a message, and then loop until a valid number is entered. Also I am new to programming, so if there is something else wrong with my code, please let me know!
number = int(input("Enter the numeric grade: "))
if number > 89:
letter = 'A'
elif number > 79:
letter = 'B'
elif number > 69:
letter = 'C'
else:
letter = 'F'
print("The letter grade is", letter)
number = int(input("Enter the numeric grade: "))
if number > 100:
print("Error: grade must be between 100 and O")
elif number < 0:
print("Error: grade must be between 100 and O")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number > 100 or number < 0:
print("Error: grade must be between 100 and 0")
else:
# The code to compute and print the result goes here
number = int(input("Enter the numeric grade: "))
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
Your issue is at the bottom, where you've got an empty if statement followed by an else statement, as well as incorrect indenting. From your code, I believe you are trying to use not.
I would suggest doing one of two things:
1.
if not (number >= 0 and number <= 100):
2.
if number < 0 or number > 100:
These two pieces of code will both produce the same result.
Also, it seems as though you are repeating the same code several times to try to ensure that the user inputs a number between 0 and 100. If so, this can be achieved with a while loop. I've put an example of this below:
number = int(input("Enter the numeric grade: "))
while number < 0 or number > 100:
print("Error: grade must be between 100 and O")
number = int(input("Enter the numeric grade: "))
In the last line.
if number >= 0 and number <= 100:
else:
print("Error: grade must be between 100 and O")
you didn't write anything after the if statement.
This code will run
if number >= 0 and number <= 100:
print('Write something here')
else:
print("Error: grade must be between 100 and O")
or you can just remove the last if statement its really of no use like try doing something else because there are a lot of if and else statements which don't look nice.
try this:
n = int(input())
first = 0
last = 100
while n < first or n > last:
print(n,'is not a valid input')
n = int(input())
From what I've understood, you're trying loop indefinitely until the user input is between 0 and 100.
My solution would be this:
Define a function that starts by requesting an input from the user.
Use a while loop that will check if the input is 'correct'. In case the input is not correct, the loop will print the error and call back the function again indefinitely till the user's input is between 0 and 100.
if the input is between that range, it will then evaluate the grade and return it.
def yfunc():
n = int(input('Enter the numeric grade: '))
while n < 0 or n > 100:
print("Error: grade must be between 100 and O")
return yfunc()
if n > 89:
letter = 'A'
elif n > 79:
letter = 'B'
elif n > 69:
letter = 'C'
else:
letter = 'F'
return letter
yfunc()
If you have any questions, feel free to ask.

I want to return the number of top-level elements in a "duo" lists

Trying to do a Boolean test loop where the user needs to enter a number between 10 and 1000 including 10 and 1000, they need to stay in this loop until they enter the correct number once they do then I will finish the else statement.
I tried this:
while (num_years < 10) and (num_years > 1000): # boolean test , note == (= will give you an error!)
print("Your input must be 10 and 1000")
input("Enter number of years to simulate (currently " + str(num_years) + "): ")
else:
print()
AND this:
while (num_years == range(10, 1000)): # boolean test , note == (= will give you an error!)
print("Your input must be 10 and 1000")
input("Enter number of years to simulate (currently " + str(num_years) + "): ")
else:
print()
You could try something like this as it also checks if the user inputs a valid number:
while True:
number = input("Enter number of years to simulate (10-1000): ")
try:
years = int(number)
if years >= 10 and years <= 1000:
break
else:
print("Your input must be between 10 and 1000 inclusive")
except ValueError:
print("That's not an int!")
print("Simulating %d years..." % years)
Example Usage:
Enter number of years to simulate (10-1000): asd
That's not an int!
Enter number of years to simulate (10-1000): 5
Your input must be between 10 and 1000 inclusive
Enter number of years to simulate (10-1000): 245
Simulating 245 years...
Try it here!
You are never changing the value of num_years so the condition will never change. Fixing your boolean logic:
num_years = 0
while (num_years < 10) or (num_years > 1000):
print("Your input must be 10 and 1000")
num_years = int(input("Enter number of years to simulate (currently {}): ".format(num_years)))
else:
print()
However, this assumes someone is entering a number if you need to cover a non-numeric value then use a try: except: pass block:
try:
num_years = int(input("Enter number of years to simulate (currently {}): ".format(num_years)))
except ValueError:
pass
Note: = is assignment not an equality test. Use in to test if a value is in a list or range.
Okay, first of all:
(num_years < 10) and (num_years > 1000)
this is always False since one number cannot be less than 10 and more than 1000 at the same time.
Second of all
num_years == range(10, 1000)
will never work since you have (probably) integer on the left and generator on the right.
However you might try something like that:
possible_years = range(10,101)
num_years = 50
while num_years in possible_years: # or 9 < num_years < 100
print("Your input must be 10 and 1000")
entered_years = input("Enter number of years to simulate (currently " + str(num_years) + "): ")
num_years = int(entered_years) # remeber to check if entered_years is int before this line!
else:
print()
However there is still a catch, you need to check if user entered an integer.
What you need to do is a while loop to check whether the input is valid. If it's not, it will loop again. Also you never assign the input to a variable.
n = None
while n is None or not 10 <= n <= 1000:
if n is not None: # Only happens if it's not the first input
print('Invalid number, please try again')
try:
n = int( input('Enter number of years to simulate (10-1000): ') ) # Convert the
# string to an int
except:
pass
print( 'Simulating {} years...'.format(n) )
It will continue and say simulating once a valid number is input because
not 10 <= n <= 1000
will evaluate to false.
You can try it at this link: https://repl.it/FftK/0
n = None
while n is None or not 10 <= n <= 1000:
if n is not None: # Only happens if it's not the first input
print('Invalid number, please try again')
try:
n = int( input('Enter number of years to simulate (10-1000): ') ) # Convert the
# string to an int
except:
pass
print( 'Simulating {} years...'.format(n) )

Using the while loop to give the user 3 attempts for a valid input value

counter = 0
miles = float(input('How many miles do you want converted into kilometers? '))
while miles < 0:
print('You cannot enter a negative value!')
miles = float(input('Enter the correct number of miles: '))
counter = counter + 1
if counter > 2:
break
if counter <= 2:
milesToKm = (miles*1.6)
print(miles, 'miles is', round(milesToKm,2), 'kilometers')
else:
print('Error: cannot exceed three attempts')
exit()
Hi everybody. This is my fifth week of learning to code. I'm supposed to create a program that will give the user three attempts to enter a valid value. If the value on the third attempt is invalid (a negative number), then it will prompt an error message and terminate.
The problem is that I can enter two invalid values followed by a valid value, and it still gives the error message and terminates. The program should calculate the third valid value and do the mathematics then print the conversion.
For example:
How many miles do you want converted into kilometers? -1
You cannot enter a negative value!
Enter the correct number of miles: -1
You cannot enter a negative value!
Enter the correct number of miles: 5
Error: cannot exceed three attempts
Can you guys help?
It's just a small confusion in managing both exit conditions. Check both of them in the while statement, and you'll be fine. I tested this with sequences (-1, -1, -1), (-1, -1, 5), and (-1, 5). It worked fine each time.
counter = 0
miles = float(input('How many miles do you want converted into kilometers? '))
while miles < 0 and counter <= 2:
print('You cannot enter a negative value!')
miles = float(input('Enter the correct number of miles: '))
counter = counter + 1
if counter <= 2:
milesToKm = (miles*1.6)
print(miles, 'miles is', round(milesToKm,2), 'kilometers')
else:
print('Error: cannot exceed three attempts')
exit()
Another way to handle this is with the else clause of a loop. If you exit the loop normally, its else clause gets executed; if you break out of the loop, the else gets skipped. This lets you handle your logic with a for loop:
for counter in range(3):
miles = float(input('How many miles do you want converted into kilometers? '))
if miles >= 0:
break
print('You cannot enter a negative value!')
else:
print('Error: cannot exceed three attempts')
exit()
milesToKm = (miles*1.6)
print(miles, 'miles is', round(milesToKm,2), 'kilometers')
Your problem is that after you go through the while loop at the top, your counter will be greater than 2. That is, 3. Now, your print function is inside an if counter <= 2 statement. 3 is not less than or equal to 2. That is your problem.
counter = 0
while miles < 0:
# ...
if counter > 2:
print('Error: cannot exceed three attempts')
break
print(miles, 'miles is', round(milesToKm,2), 'kilometers')

Creating a List from User input {with Unlimited User Input}

I'm trying to create a function definition that asks the user to enter a int or float value to be added to an empty list, but continues to ask the user for input until the user types in -1 or so (<0).
This is what I have so far, but all it does is take the user's input and replicates it 5 times [range(5)] in the new list, and doesn't allow the user to enter anymore values....
I'm very stuck even though I feel it should be pretty easy:
def main():
salesList = []
salesValue = float(input('Please enter total sales in your department: '))
while salesValue < 0:
salesValue = float(input('Please enter a value greater than or equal to zero: '))
if salesValue == -1:
break
else:
for values in range(5):
salesList.append(salesValue)
print(salesList)
main()
Any guidance will be greatly appreciated, as I am new to programming.
:::The easy solution:::
def makeList():
salesList = []
while True:
salesValue = float(input('Please enter total sales in your department: '))
if salesValue == -1:
break
salesList.append(salesValue)
return salesList
You want
while salesValue > 0:
instead of
while salesValue < 0:
As you have it written now, the user inputs a value greater than 0, which automatically kicks it into the else block. You will be able to remove the
if salesValue == -1:
break
as well.
# here you are saying, for 5 iterations do the following
for values in range(5):
# append the single float value salesValue to salesList
# naturally this will happen 5 times
salesList.append(salesValue)
So it makes total sense that you end up with a list containing
the salesValue five times over.
Think about this:
while True: # will loop until a break
salesValue = float(input('Please enter a value greater than or equal to zero (-1 to end): '))
if salesValue < 0:
break
else:
salesList.append(salesValue)
Your current code has a mistake. Basically, when the flow finally reaches the for statement, the value of salesValue does not change, so the program appends the same value 5 times. Try this instead:
def main():
salesList = []
salesValue = float(input())
while salesValue < 0:
salesvalue = float(input())
if salesValue == -1:
break
for values in range (5):
salesList.append(salesValue)
salesValue = float(input("yourmessage"))
print salesList
main()

Python: (Count positive and negative numbers and compute the average of numbers)

Problem statement: Write a program that reads an unspecified number of integers, determines how many positive and negative values have been read, and computes the total and average of the input values (not counting zeros). Your program ends with the input 0. Display the average as a floating-point number.
Sample output (ignore bullets, didn't know how to format text into console output):
Enter an integer, the input ends if it is 0: 1
Enter an integer, the input ends if it is 0: 2
Enter an integer, the input ends if it is 0: -1
Enter an integer, the input ends if it is 0: 3
Enter an integer, the input ends if it is 0: 0
You didn't enter any number
The number of positives is 3
The number of negatives is 1
The total is 5
The average is 1.25
Attempted solution:
def main():
i = int( input ("Enter an interger, the input ends if it is 0: "))
count_pos = 0
count_neg = 0
total = 0
if (i != 0):
while (i != 0):
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
total += i
i = int( input ("Enter an interger, the input ends if it is 0: "))
count = count_pos + count_neg
average = total / count
print ("The number of positives is", count_pos)
print ("The number of negatives is", count_neg)
print ("The total is", total)
print ("The average is", float(average))
else:
print ("You didn't enter any number.")
main()
You do not need this line (which is why your error is happening):
main(i)
To continuously get user input, use an infinite loop, and test for the condition to break the loop.
while (true):
i = input("Enter an integer (0 to stop): ")
if(i == 0)
break
sum1 += i
if (i > 0):
count_pos += 1
elif (i < 0):
count_neg += 1
Then calculate and return average.
You are calling the main function with the parameter 'i', which does not exist. You can't use variables declared in a function outside of that function
Check out: Python Scopes

Categories

Resources