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: "))
Related
I'm trying to complete this assignment asking user for a number and if it's not -1 then it should loop. if it's -1 then to calculate the average of the other numbers.
I'm getting stuck with the actual loop - it endlessly keeps printing the message to user to enter a different number - as in the picture - and doesn't give user a chance to enter a different number. Please help, I've been through so many videos and blogs and can't figure out what's actually wrong.
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num =int(input("number:"))
#looping
while num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
break
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
print("Nope, guess again:")
You need to include the input function in the loop if you want it to work. I corrected the rest of your code as well, you don't need the if condition. More generally you should avoid to use break, it often means you are doing something wrong with your loop condition. Here it is redondant and the code after break is never executed.
wrong = []
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
num = int(input("Number: "))
while num != -1 :
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
You are just breaking the loop before printing the results, first print the results, then break the loop.
And a while loop isn't necessary for your program, use if condition wrapped in a function instead:
#creating a list for later calculations:
wrong = []
#asking for input:
input("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\nIf not correct you'll have to guess again ^-^")
#looping
def go():
num =int(input("number:"))
if num != -abs(1):
wrong.append(num)
print("Nope, guess again:")
if num == -abs(1):
av = sum(wrong) / len(wrong)
print ("You got it! The average of your wrong answers is: ")
print(av)
print("The End")
break
print("Nope, guess again:")
go()
There are lots of issues in the code.
If you want to get inputs in while looping, you should include getting input code inside the while loop like below,
while num != -1:
......
num =int(input("number:"))
......
Also you don't have to include 'break' inside the while loop because, when num != 1, the loop will stop.
You should ask for input inside your loop, but you just print "Nope, guess again:".
wrong = []
print("Hi, We're gonna play a guessing game. When asked enter a number between -10 and 10.\n"
"If not correct you'll have to guess again ^-^")
num = int(input("number: "))
# looping
while num != -1:
wrong.append(num)
num = int(input("Nope, guess again: "))
av = sum(wrong) / len(wrong)
print(f"You got it! The average of your wrong answers is: {av}\nThe End")
I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.
I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.
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: ')
New to Python and trying to figure out what went wrong here. Making a simple game in which I have to guess the number that was randomly generated by the computer. Thanks for your help.
Here's what I have:
guessed == random.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while entered != guessed
entered = raw_input("Enter your suggestion:")
entered = int(guessed_number)
if entered > guessed
print('Try less')
else
print('Try more')
print('You win!')
You're missing colons at the end of your conditionals and loops, aka while entered != guessed:. Add them to the end of the if and else lines as well. Also you are using the comparison (==) operator when assigning guessed instead of the assignment operator (=).
Also you will notice it prints "Try more" even when they guess the correct number, and then it will print "You win!". I'll leave this as an exercise to the new developer to fix.
entered = int(guessed_number)
makes no sense because you don't have a guessed_number variable. I think you meant to do
entered = int(raw_input("Enter your suggestion:")
Also, you're missing colons after your block starts at while, if, and else.
Welcome to Python 3.x! Here's the fixed code for you.
#Import Random
import random as r
#Create a random Number!
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
#Initiate variable --entered--
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
#Fixed your if/else tree with correct indents and an elif.
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
To add to the list:
guessed == random.randint(1,100)
should be
guessed = random.randint(1,100)
I'm sure you'd rather assign to guessed than compare it random.randint(1,100) and then throw the result of that comparison away.
entered = int(guessed_number)
It doesn't make any sense. There is no variable for 'guessed_number'.
I have edited your code to make it work:
import random
guessed = r.randint(1,100)
print("I guessed a number between 1 and 100. Try to find it!")
entered = 0
while (entered != guessed):
entered = int(input("Enter your suggestion:"))
if (entered > guessed):
print('Try less')
elif (entered <guessed):
print('Try more')
else:
print('You win!')
Hope that helps!
~Edward