Wack A Mole With Python Syntax/Punctuation - python

Alright, so I've been playing with this piece of code for a while. What I want it to do is:
a) if yes, continue to the next part of the program.
b) if no, return back to the questioniare to re-enter the proper data.
c) if neither, request a y/n answer again.
So right now this is what I have so far. I'm working out of Python 3.4.1, and at this point it is telling me "invalid syntax" on the last variable "answer" after the "else" statement. If I try to adjust this statement then it will go on to tell me that a colon is out of place, that the "elif" is "invalid syntax," and that the first "break" in the "if" statement is "out of the loop" due to indentation. So here's my question: where do I start debugging it since all of it seems to be confused?
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
answer = input('If this is correct please type: yes or no: ')
if answer == ('no'):
print('You said no! Darn, let me get those numbers again...')
break
elif answer == ('yes'):
print ('Great! Let us continue...')
continue
else answer != ('yes', 'no'):
print ('You did not answer correctly! Please try again: ')
break
Any and all answers will be greatly appreciated! :)

You can't specify a condition for an else (and in this context, it isn't logically needed anyway). Just do:
else:
print ('You did not answer correctly! Please try again: ')
Also, break isn't proper syntax for an if block, so remove all the breaks from your code. You're probably thinking of switch statements, which Python doesn't support.

First, your else is invalid for at least reasons: if you want to test a condition, you need elif; if you want to test whether answer is equal to neither of two values you need not in, not !=; etc. But you really have no reason to test anything here anyway. If you didn't do the if or the elif, you want to do the else.
Second, you're missing a while True: to go with those break and continue statements.
Also, you've got break and continue backward. A break breaks out of a loop, and moves on with the rest of the program; a continue continues to the next time through the loop.
So:
while True:
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
answer = input('If this is correct please type: yes or no: ')
if answer == ('no'):
print('You said no! Darn, let me get those numbers again...')
continue
elif answer == ('yes'):
print ('Great! Let us continue...')
break
else:
print ('You did not answer correctly! Please try again: ')
continue
There's still one problem left: You want the third choice to go back to just ask the last question again, not the whole thing. This means you need a loop inside a loop… and you can only break or continue one loop at a time. This is one of many reasons it's probably worth refactoring this into smaller functions, so you can just return when you're done. For example:
def yesno(prompt):
while True:
answer = input(prompt)
if answer == "no":
return False
elif answer == "yes":
return True
else:
print('You did not answer correctly! Please try again:')
def questionnaire():
while True:
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
if yesno('If this is correct please type: yes or no:'):
print('Great! Let us continue...')
return b, i, m
else:
print('You said no! Darn, let me get those numbers again...')
Notice I didn't need break or continue anywhere.

Unlike switch statements, if-elif-else statements are mutually exclusive so you don't need to break once you enter the block of code corresponding to that conditional branch. Also, else statements can not take conditions since they mean (if none of the above is true). The behaviour you describe is a loop, where a block of code is repeated until a certain condition is met. Using a flag (a boolean variable) and a while loop, you can run that block of code an arbitrary number of times until any of the conditions in the if-elif-else statements are met, at which point you change the value of the flag, which in turn terminates the loop. Here is an example using your code:
EDIT: I reread your specs and modified the code to make it re-ask for yes/no answer only instead of getting the first three inputs again.
move_on= False
while (!move_on):
b = input ('Enter outstanding balance: ')
i = input ('Enter annual interest rate as a decimal: ')
m = input ('Enter monthly minimum payment as a decimal: ')
print ('Your oustanding balance is: ' + b)
print ('Your annual interest rate in decimal form is: ' + i)
print ('Your monthly minimum payment as a decimal is: ' + m)
answer = input('If this is correct please type: yes or no: ')
ask_again= True
while (ask_again):
if answer == 'no':
print('You said no! Darn, let me get those numbers again...')
ask_again= False
elif answer == 'yes':
print ('Great! Let us continue...')
ask_again= False
move_on=True
else:
print ('You did not answer correctly! Please try again: ')

Related

I want to make a nested loop that makes user enter a number that does not make the input variable have a negative output. How with changing variable?

This is Python in Visual Studio Code. I'm making a program for school that essentially is an robotic restaurant waitress. I have to do it the way the assignment outline says which is why it might be a little weird. Then I have to personalize it and make it creative. It asks how much the price of an adult meal and a child meal. Then it asks how many children and adults there are. Then it asks what the sales tax rate is. The assignment only needs me to be able to calculate all that and get the subtotal and total and then give change. I've already done that and I'm making it fancy. I made a loop that asks if they have a lucky draw coupon that generates a random monetary value between $1.00-$5.00. Then If they say yes it will bring them to the first part of the loop that gives them the total with the coupon and then asks for payment. If they say no, then it just asks them for the payment.
I want to go the extra mile and put a loop in a loop, which I think is called a nested loop (This is my first week of Python.) I want it to recognize if the amount they pay is less then the total, then ask for the user to try again until they put an amount more than the total. Pretty much I just want it to know that the payment isn't enough.
My problem is I've never used nested loops and this is the first time I've even used a loop period. I also don't know how to make a loop based on a variable that's not constant because it's based on what the user inputs when prompted. I could do it if I could put the parameters in a fixed range, but the range will always be different based on what they enter in the beginning.
How do I make a nested loop recognize a variable that is never the same?
How do I make it recognize the payment is not enough to cover the total?
This is the loop I have. And I want to put two nested loops in the loop. One for if and one for elif so that it works for both "options".
Here is my snippet:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
payment = float(input("Please enter your payment amount: "))
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")
Any suggestions? I've searched all over Stackoverflow and google and cannot find anything specific to my situation.
Your approach is good for implementing this. Looping while asking for payment and validating that it is correct before allowing the loop to break will do the job. For your first if block, this is how that would look:
while True:
coup = input("Do you have a lucky draw coupon? 1 for YES 2 for NO: ")
if coup =="1":
#calling the random function and also rounding it so that it comes out as two decimal places
coupon = round(random.uniform(1.00,5.00),2)
print()
print("---------------------")
#tells the user how much they save and the :.2f is making sure it has two decimal places
print(f"You will save ${coupon:.2f}!")
print("---------------------")
print()
newtotal = total - coupon
print(f"Your new total is: ${newtotal:.2f}")
print()
#Ask for the payment inside of the new loop
while True:
payment = float(input("Please enter your payment amount: "))
if payment - total + coupon > 0:
print("That's not enough money to pay your bill. Try again")
else:
break
change2 = payment - total + coupon
change2 = round(change2, 2)
print(f"Change: ${change2:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
#break stops the loop from looping again
break
elif coup == "2":
print()
print("That's ok! Maybe next time!")
print()
payment = float(input("Please enter your payment amount: "))
change = payment - total
change = round(change, 2)
print(f"Change: ${change:.2f}")
print()
print("---------------------------------------------------------------------")
print("Thank you party of", capitalized_string, "for choosing Erin's Cafe! Have a great day!")
print("---------------------------------------------------------------------")
print()
break
else:
print()
print("Invalid response. Please type 1 for YES and 2 for NO: ")

What is causing the syntax error in this loop?

I am trying to create a loop if a negative number is entered to prompt the user to re-enter a valid rating, but I keep receiving a syntax error can someone help point out which part does not look right. I am new to this so it's going over my head. Thanks in advance.
def detailLoop():
global numOfStars
if (rating >4):
print ("Out of range. ")
rating = float(input("Enter a star rating or a negative number to quit: ")
elif (numOfStars >= lowestRating) and (numOfStars <= maxRating):
rating=rating+numOfStars
count=count+1
# If Negative Value Is Entered
else: (numOfStars<0):
print("End of Program")
return
Ignoring your indentation, your problem is probably with your else statement. You don't have to specify a condition after the else statement. So it should either be
else:
print("End of Program")
or
elif numOfStars < 0:
print("End of Program")
and as #Klaus has pointed out you're also missing a ) at the end of your input line
rating = float(input("Enter a star rating or a negative number to quit: "))

If input is not the specific type, print.. (Python) [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I would like to add an "if" statement to my code. If "guess" is not an integer, print ("You did not enter a number, please re-enter") and then repeat the code from the input area instead of the starting point. The following is my attempt, however when I enter a non-int at guess input, ValueError appears. Thanks in advance!
#This is a guess the number game.
import random
print ("Hello, what is your name?")
name = input()
print ("Well, " + name + " I am thinking of a number between 1 and 20, please take a guess.")
secretNumber = random.randint(1,20)
#Establish that they get 6 tries without specifically telling them
for guessesTaken in range(1, 7):
guess = int(input())
if type(guess) != int:
print ("You did not enter a number, please re-enter")
continue
if guess < secretNumber:
print ("The number you guessed was too low")
elif guess > secretNumber:
print ("The number you guessed was too high")
else:
break
if guess == secretNumber:
print ("Oh yeah, you got it")
else:
print ("Bad luck, try again next time, the number I am thinking is " + str(secretNumber))
print ("You took " + str(guessesTaken) + " guesses.")
Use a try and except:
for guessesTaken in range(1, 7):
try:
guess = int(input())
except ValueError:
print ("You did not enter a number, please re-enter")
continue
So you try to convert the input into an integer. If this does not work, Python will throw an ValueError. You catch this error and ask the user try again.
You can try a simple while loop that waits until the user has entered a digit. For example,
guess = input("Enter a number: ") # type(guess) gives "str"
while(not guess.isdigit()): # Checks if the string is not a numeric digit
guess = input("You did not enter a number. Please re-enter: ")
That way, if the string they entered is not a digit, they will receive a prompt as many times as necessary until they enter an integer (as a string, of course).
You can then convert the digit to an integer as before:
guess = int(guess)
For example, consider the following cases:
"a string".isdigit() # returns False
"3.14159".isdigit() # returns False
"3".isdigit() # returns True, can use int("3") to get 3 as an integer

Number Guessing Game in Python

I was trying to create a simple random number guessing game. The problem is even if I type the correct number it replies with a 'The number is less than'. Can somebody provide me a solution for this one ?
Thanks in advance
import random
import sys
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
user = raw_input('Guess The Number\n Pick between 1 - 10\n >>> ')
try:
int(user)
except:
print "Numbers Only !"
sys.exit(0)
number = random.choice(numbers)
int(number)
for i in range(0, 4):
if number == user:
print 'You Won!'
if user > number:
print 'The number is less than', user
user = raw_input('>>> ')
try:
int(user)
except:
print "Numbers Only !"
if user < number:
print 'The number is bigger than', user
user = raw_input('>>> ')
int(user)
print "The Number was", number
The biggest problem is that you're not saving the conversion to int so you're using the guess as the string the user entered. You need to save it by doing user = int(raw_input('>>>'))
There are other ways you can improve this code, however. You repeat yourself a bit, and you don't need random.choice, you can use random.randrange(1, 10)
You shouldn't just say except:. You wanna only catch the exceptions you are looking for. The particular exception you are looking for is a ValueError
Additionally, I suggest you let the user try again when they enter something that's not a number. You can wrap up the whole thing in it's own function.
import random
def get_user_num(msg='>>> '):
"""Print the msg parameter as a prompt for the user to enter a number. If
they enter an invalid string, reprompt them until they enter a number.
"""
while True:
try:
return int(raw_input(msg)) # save the conversion to int
except ValueError: # only except the error you're actually looking for
print 'Numbers Only!'
# 'from 1-9' is probably better than 'between 1-10'
user = get_user_num('Guess The Number\n Pick from 1-9\n>>> ')
number = random.randrange(1, 10) # <- numbers list is unnecessary
#int(number) # this conversion was never needed, it was already a number
for _ in range(4): # you don't need (0, 4), 0 is assumed
if number == user:
print 'You Won!' # the correct number has been guessed
break # exit the loop once the number has been correctly guessed
elif user > number:
print 'The number is less than', user
elif user < number:
print 'The number is bigger than', user
# Don't repeat yourself, put this outside the `if`s
user = get_user_num()
else:
#only print the answer when it wasn't guessed correctly
print "The Number was", number
When you convert to int(user), you aren't saving a new int to user. So user still remains a string.
What you need to do is
user = int(user)
By the way, this is for all of the places where you use int(user)
This could be done with a much simpler implementation:
import random
number = random.randrange(10)
for i in xrange(4):
try:
user = int(raw_input('guess: '))
except ValueError:
print 'must be int'
continue
if user == number:
print 'bravo'
break
elif user < number:
print 'greater'
else:
print 'lesser'
print 'it was: %d' % number

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories