Python How to stop a loop with an user input - python

This is probably a simple answer but I thought I'd ask anyway.
My code below is asking the user for a number and depending on the answer provided will print the grade that corresponds with the numbers.
I want to stop the loop (terminate the program) by having the user type in (999). I know the problem is in my if userScore >= 90" print ('A'). So when the user enters the 999, the computer takes it as an A.
Is there a shortcut to fix this?
(PS I added the breaks to every line because when they were not there the outputs kept repeating endlessly.)
userScore = float(input('Enter the score or type "999" to quit: '))
while True:
try:
if userScore >= 90:
print ("You earned an A")
break
elif userScore >= 80:
print ("You earned a B")
break
elif userScore >= 70:
print ("You earned a C")
break
elif userScore >= 60:
print ("You earned a D")
break
elif userScore <= 59.9:
print ("You earned an F")
break
except:
if userScore == '999':
break
main()

Don't use try except. Try except is meant for error handling. This can be handled using a simple while loop.
userScore = float(input('Enter the score or type "999" to quit: '))
while userScore!=999:
if userScore >= 90:
print ("You earned an A")
break
elif userScore >= 80:
print ("You earned a B")
break
elif userScore >= 70:
print ("You earned a C")
break
elif userScore >= 60:
print ("You earned a D")
break
elif userScore <= 59.9:
print ("You earned an F")
break
main() # Why is this even required?

Here is what you are trying to accomplish. It is explained in the comments.
while True:
#This part gets the user input. It waits until the user enters a valid number input.
while True:
prelim = input('Enter the score or type "999" to quit: ')
try:
prelim = int(prelim)
except:
print("Please enter a valid input.")
else:
#if the input can be converted into a number, then this is our final input value
userScore = float(prelim)
break
#The first thing we should check is if the user wants to exit. This way it won't print out an answer then exit.
if userScore == 999:
break
if userScore >= 90:
print ("You earned an A")
elif userScore >= 80:
print ("You earned a B")
elif userScore >= 70:
print ("You earned a C")
elif userScore >= 60:
print ("You earned a D")
elif userScore <= 59.9:
print ("You earned an F")

Related

Guess Number with class and method

I am trying to create a guess game using class/methods, but got stuck. When trying the code does not show me any errors but it does not print any of the conditionals created under the method. Can you please tell me what am I doing wrong?
class GuessProcessor:
def __init__(self, my_secretNumber, user_numGuess):
self.my_secretNumber = my_secretNumber
self.user_numGuess = user_numGuess
def compareGuess(self, user_numGuess, my_secretNumber):
return compareGuess
if user_numGuess >10 or user_numGuess <= 0:
print("Invalid number. Try again!")
elif user_numGuess < my_secretNumber:
print("You guessed too low!")
elif user_numGuess > my_secretNumber:
print("You guessed too high")
my_secretNumber = int(6)
user_numGuess = int(input("Enter a number between 1 and 10: "))
The only thing that prints out is:
Enter a number between 1 and 10: 6
Process finished with exit code 0
There are some flaws in your code.
First, your if-else logic won't be checked because you have return compareGuess
Second, you do not use the correct initialization variables when doing the if-else checking
Third, you don't have the condition when the guessing number is correct.
Fourth, you didn't initiate that GuessProcessor class to run the compareGuess with your "my_secretNumber" and "user_numGuess"
Fifth, start to read the coding guideline, especially for the naming convention (https://google.github.io/styleguide/pyguide.html#3162-naming-conventions)
Probably, you would like the code something like this
class GuessProcessor:
def __init__(self, my_secret_number, user_num_guess):
self.my_secret_number = my_secret_number
self.user_num_guess = user_num_guess
def compare_guess(self):
if self.user_num_guess > 10 or self.user_num_guess <= 0:
print("Invalid number. Try again!")
elif self.user_num_guess < self.my_secret_number:
print("You guessed too low!")
elif self.user_num_guess > self.my_secret_number:
print("You guessed too high")
else:
print("You guessed correctly!")
my_secret_number = int(6)
user_num_guess = int(input("Enter a number between 1 and 10: "))
GuessProcessor(my_secret_number, user_num_guess).compare_guess()
You never thought about when the answer is right.
You need to add one more elif statement:
elif user_num_guess == my_secretNumber:
print("Your right!")
Then, you can compare, if you want an response back from Python.
test = GuessProcessor(my_secretNumber, user_num_guess)
test.compare_guess()
The full code will look like this:
class GuessProcessor:
def __init__(self, my_secretNumber, user_numGuess):
self.my_secretNumber = my_secretNumber
self.user_numGuess = user_numGuess
def compareGuess(self, user_numGuess, my_secretNumber):
return compareGuess
if user_numGuess >10 or user_numGuess <= 0:
print("Invalid number. Try again!")
elif user_numGuess < my_secretNumber:
print("You guessed too low!")
elif user_numGuess > my_secretNumber:
print("You guessed too high")
elif user_num_guess == my_secretNumber:
print("Your right!")
my_secretNumber = int(6)
user_numGuess = int(input("Enter a number between 1 and 10: "))
test = GuessProcessor(my_secretNumber, user_num_guess)
test.compare_guess()

How do I ask for an input from a user and check that value within a range to give me the correct response

So my professor for python assigned an exercise which was to create a program to accept a user input or "score" and create an if else loop with an if else nested loop inside the first loop to check if the score is greater than or equal to 80. If that's satisfied, print a statement saying "you passed." and if the score is equal to 90 or more, then it should say"you got an A." and if the score is below an 80, it should say "you failed."
so far, this is the code I was able to come up with. And it runs up until the score entered is anything equal to or more than 90.
userScore = int(input('enter score:\n'))
if userScore < 80:
userScore = int(input('you failed. Try again:\n'))
if userScore == 80 or userScore > 80:
print(f'good job, you got a B.')
elif userScore >= 90:
print('you got an A')
else:
print('enter a differnt score')
as per your question your code should be :
score = int(input("Please enter your score: "))
if score >= 80:
print("You passed.")
if score >= 90:
print("You got an A.")
else:
print("You failed.")
while(1):
score = int(input("Please enter your score: "))
if score >= 80:
print("You passed.")
if score >= 90:
print("You got an A.")
break
else:
print("You failed.")
while(1):
score = int(input("Please enter your score pal: "))
if score >= 80:
print("You passed the exam.")
if score >= 90:
print("You got an A in the exam.")
break
else:
print("You failed the exam.")

Why am I getting this syntax error? (Python)

Python noob here. Took a swing at the 'guess the number game' this afternoon.
It all looks fine to me but i keep getting a syntax error on line 26:
else player_number >= secret_number:
I've tried everything but I can't figure it out at all.
Thanks for your help.
import random, sys
secret_number = random.randint(1, 99)
countdown_timer = 7
print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")
while countdown_timer != 0:
player_number = int(input())
countdown_timer = (countdown_timer - 1)
if player_number == secret_number:
print("\n")
print("That's it!! The number was: " + secret_number)
print("\n")
print("Congratulations!")
print("Please try again.")
quit()
elif player_number <= secret_number:
print("Higher!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
else player_number >= secret_number:
print("Lower!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
print("You are out of guesses, sorry.")
print("The correct number was: " + secret_number)
print("Please try again.")
Change your else statement to elif. The else statement takes no expression. Therefore:
elif player_number >= secret_number:
print("Lower!")
print("You have " + int(countdown_timer) + "guesses left.")
print("Please enter your next guess: ")
After actually running the code, I see you are trying to concatenate integer and string, but that won't work. To make it work, use the f' print.
Here is the code:
import random
secret_number = random.randint(1, 99)
countdown_timer = 7
print("This is a number guessing game.")
print("You have to guess a number between 1 and 99!")
print("You have 7 attempts to guess the correct number")
print("Good luck!")
print("\n")
print("Your first guess is: ")
while countdown_timer != 0:
player_number = int(input())
countdown_timer = (countdown_timer - 1)
if player_number == secret_number:
print("\n")
print(f"That's it!! The number was: {secret_number}") # f' print here
print("\n")
print("Congratulations!")
print("Please try again.")
quit()
elif player_number <= secret_number:
print("Higher!")
print(f"You have {countdown_timer} guesses left.") # here
print("Please enter your next guess: ")
elif player_number >= secret_number:
print("Lower!")
print(f"You have {countdown_timer} guesses left.") #here
print("Please enter your next guess: ")
print("You are out of guesses, sorry.")
print(f"The correct number was: {secret_number}") # and here
print("Please try again.")
I would replace the whole line with just "else:" and add a comment:
if player_number == secret_number:
...
elif player_number <= secret_number:
...
else:
# player_number >= secret_number
...

Counting Game Try/Except and calculating the users attempts

I am creating a python random counting game. I'm having some difficulties with certain parts. Can anyone here review my code? I'm having difficulty with trying to implement a try/except and a tries function that counts the user's attempts. I also have to verify that the number is a legitimate input and not a variable. So far I've gotten this far and its coming along good. I just need alittle help ironing out a few things. Thanks guys you rock.
Here is the code below:
import random
def main():
start_game()
play_again()
tries()
print("Welcome to the number guessing game")
print("I'm thinking of a number between 1 and 50")
def start_game():
secret_number = random.randint(1,50)
user_attempt_number = 1
user_guess = 0
while user_guess != secret_number and user_attempt_number < 5:
print("---Attempt", user_attempt_number)
user_input_text = input("Guess what number I am thinking of: ")
user_guess = int(user_input_text)
if user_guess > secret_number:
print("Too high")
elif user_guess < secret_number:
print("Too low")
else:
print("Right")
user_attempt_number += 1
if user_guess != secret_number:
print("You ran out of attempts. The correct number was"
+str(secret_number)+ ".")
def play_again():
while True:
play_again = input("Do you want to play again?")
if play_again == 'yes':
main()
if play_again =='no':
print("Thanks for playing")
break
def tries():
found= False
max_attempts=50
secret_number = random.randint(1, 50)
while tries <= max_attempts and not found:
user_input_text = start_game()
user_guess_count=+1
if user_input_text == secret_number:
print("It took you {} tries.".format(user_guess_count))
found = True
main()
Try this method:
def play_game():
print("Enter the upper limit for the range of numbers: ")
limit = int(input())
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
count = 1 #new line
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
count = count+

Beginner question regarding if-elif-if-if chain

Very recently started to learn Python (2 weeks ago) and have been enjoying working through the Python Crash Course book. I've written some code for an exercise in the book. The code works as I expected it to but I don't quite understand why.
Exercise: Write a program for a cinema that asks the user for inputs of their age and then tells them what price their ticket will be, using a while loop.
Here is the code I first wrote:
print("Welcome to Cathrine's Cinema!\n")
no_tickets = 0
total_cost = 0
while True:
if no_tickets == 0:
ticket = input("Would you like to buy a ticket? (Yes/No) ")
if ticket.lower() == 'yes':
no_tickets += 1
age = input("Great! How old is the person that this ticket is "
"for? ")
age = int(age)
if age < 3:
print("The ticket is free, enjoy!")
continue
elif age <= 12:
print("That'll be £10 please.")
total_cost += 10
continue
elif age > 12:
print("That'll be £15 please.")
total_cost += 15
continue
elif ticket.lower() == 'no':
print("Ok, thanks for coming by!")
break
else:
print("Please answer 'Yes' or 'No'")
continue
if no_tickets > 0:
ticket = input("Would you like to buy another ticket? (Yes/No) ")
if ticket.lower() == 'yes':
no_tickets += 1
age = input("Great! How old is the person that this ticket is "
"for? ")
age = int(age)
if age < 3:
print("The ticket is free, enjoy!")
continue
elif age <= 12:
print("That'll be £10 please.")
total_cost += 10
continue
elif age > 12:
print("That'll be £15 please.")
total_cost += 15
continue
elif ticket.lower() == 'no':
print(f"Cool, you have purchased {no_tickets} tickets for a total"
f" cost of £{total_cost}.")
break
else:
print("Please answer 'Yes' or 'No'")
continue
I thought it was quite awkward having two big almost identical if statements just so the initial message (Would you like to buy a/another ...) and the goodbye message was right, so I wrote it again a bit differently.
print("Welcome to Cathrine's Cinema!\n")
no_tickets = 0
total_cost = 0
while True:
if no_tickets == 0:
message = "Would you like to buy a ticket? (Yes/No) "
bye_message = "Ok, thanks for coming by."
elif no_tickets > 0:
message = "Would you like to buy another ticket? (Yes/No) "
bye_message = (f"Cool, you have purchased {no_tickets} tickets for a "
f"total cost of £{total_cost}.")
ticket = input(message)
if ticket.lower() == 'yes':
no_tickets += 1
age = input("Great! How old is the person that this ticket is "
"for? ")
age = int(age)
if age < 3:
print("The ticket is free, enjoy!")
continue
elif age <= 12:
print("That'll be £10 please.")
total_cost += 10
continue
elif age > 12:
print("That'll be £15 please.")
total_cost += 15
continue
elif ticket.lower() == 'no':
print(bye_message)
break
else:
print("Please answer 'Yes' or 'No'")
continue
Now this seems to work exactly the same as the previous program, but I'm confused about the if-elif chain. I thought that python executes only one block in an if-elif chain. So if the customer orders 1 ticket, then no_tickets > 0 and so we enter the second elif statement. Why then don't we go back to the start of the while loop and loop infinitely? Why instead do we continue to the other if statements below (testing if ticket.lower() == 'yes' or 'no')?
Thanks for reading all of this! Sorry if this seems like a pointless question as my code is working as intended, I just want to properly understand everything that's going on.
This has to do with indentation. Languages like java enclose if/else statements in parenthesis {}, but python depends on indentation.
Notice that the testing if ticket.lower() == 'yes' or 'no' has the same indentation as if no_tickets == 0: and if no_tickets > 0: therefore it is considered to be outside of the first if/else block.
This might be helpful: https://www.w3schools.in/python-tutorial/concept-of-indentation-in-python/
if your if statement condition is fulfilled, say age<3 is true then statement for that condition are processed/executed and then your program will not see anything in if..elif..else code block, it will go for the next code block(part of code after if..elif..else statement).
why we continue to other if statement, because in your code there are two code section for if statement and they processed one by one unless no break/exit statement didn't occur which cause them to go out of the while loop or exit the program

Categories