How can I add an exit for users with int inputs - python

I need users to be able to type x to exit if they get a question wrong.
I've tried changing the input to a string and then if the answer isn't x then convert the string to an integer with int(user_ans) and even making another value and with ans_string == int(user_ans). Is there any way to add a break to the end if they type x?
if level == 1:
solution = number_one + number_two
print("What is", number_one, "plus", number_two)
user_ans = int(input())
if user_ans == solution:
print("Correct")
number_one = random.randrange(1,10)
number_two = random.randrange(1,10)
rounds = rounds + 1
else:
print("Try again")
I expect the program to still function but also be for the user to quit.

Just use a try block to see whether the input is a number and change what you do. Something like this:
is_int = false
user_ans = input()
try:
ans_int = int(user_ans)
is_int = true
except:
is_int = false
if is_int:
# Do what you need with the integer
if ans_int == 1:
solution = number_one + number_two
print("What is", number_one, "plus", number_two)
user_ans = int(input())
elif user_ans == solution:
print("Correct")
number_one = random.randrange(1,10)
number_two = random.randrange(1,10)
rounds = rounds + 1
elif user_ans == "x":
# Do what you need to do if it is an "x"
else:
print("Try again")

You can first get the user's input into a variable, like with inStr = input('Enter input: '). Then, you can check it to see if it's 'x'; if it is, you can use sys.exit() (or some other function), and if it's not, you can then cast it to a number and use it. inNum = int(inStr)
By checking the variable first and then casting it, you don't have to worry about what happens if your code tries to run int('x').
If you really want to cast your input to int right away, though, you can use try and except to catch a ValueError, which is what int() will throw if you give it a non-number input. This won't specifically check for 'x' - just for some invalid input.

Related

How to loop a simple game to continue until user stops it not using a break?

def set_number():
import random
return random.randint(1,500)
#This function plays the game
def number_guessing_game(number):
guess_counter = 0
guess = int(input("Enter a number between 1 and 500."))
while guess != number:
guess_counter += 1
if guess > number:
print(f"You guessed too high. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
elif guess < number:
print(f"You guessed too low. Try Again!")
guess = int(input("Enter a number between 1 and 500."))
if guess == number:
print(f"You guessed the number! Good Job.!")
again = str(input("would you like to play again? Enter 'y' for yes or 'n' to close the game."))
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
number = set_number()
guess_count = number_guessing_game(number)
main()
I am working on a simple game project for my coding class. I am not good at coding at all. I came up with this part of the program, I just cannot figure out how to loop the entire number_guessing_game function until the user enters 'n' to stop it, I can't use a break because we did not learn it in the class and I will receive a 0 if I use a break.
I tried nesting a while loop inside of the function but I know I did it wrong.
Instead of using break use return.
def main():
print(f"Welcome to the Number Guessing Game!\n" +
f"You will have unlimited guesses. The number is between 1 and 500.\n" +
f"Good Luck!")
while True:
number = set_number()
number_guessing_game(number)
again = input("would you like to play again? Enter 'y' for yes or 'n' to close the game.")
if again == 'n':
return
main()
You will probably want to remove the last line of the number_guessing_game function if you use this approach
First, your code is assuming the return of input is an integer that can be converted with int(). If you were to give it 'n' your program will crash.
Instead you could use the string class method isdigit() to see if the input was an integer value and then make a logical decision about it. Also note you do not need to convert the return from input to a str() as it is already a str type. You can confirm this with a print(type(input("give me something")))
guess = input("Enter a number between 1 and 500. 'n' to quit"))
if guess.isdigit():
[your code to check the value]
elif ('n' == guess):
return
else:
print(f"You entered an invalid entry: {guess}. Please re-enter a valid value")
If you dont like the idea of using 'return' you could change your while loop to look something like:
while(('n' != guess) or (guess != number)):
If you want the function body looping continuously you could have some code like:
def number_guessing_game(number):
exit_game = False
guess_counter = 0
while(exit_game != True):
guess = input("Enter a number between 1 and 500.))
guess_counter += 1
if guess.isdigit():
if int(guess) > number:
print("You guessed too high. Try Again!")
elif int(guess) < number:
print("You guessed too low. Try Again!")
elif int(guess) == number:
print("You guessed the number! Good Job.!")
again = input("would you like to play again? Enter 'y' for yes or 'n' to close)
if ('n' == again):
exit_game = True
else:
print("Error, please enter a valid value")

This calculator program does not give an answer it just repeats. How do I fix it?

I wrote this simple calculator program to ask for two numbers and then perform a certain action on them like dividing the first by the second etc. I implemented it in a big while loop that is repeated if the user chooses to repeat it after a calculation. However, after the user enters the operation they want to perform the program does not give the answer but asks the user if they want to repeat. What did I do wrong?
import random, time
valid_operations = ("/", "*", "+", "-")
valid = 3
repeat = "y"
while repeat == "y":
number_1 = input('Enter first number \n')
if number_1.isdigit() == True:
num_1 = number_1
else:
print("that is not a valid integer")
exit()
number_2 = input('Enter second number \n')
if number_2.isdigit() == True:
num_2 = number_2
else:
print("that is not a valid integer")
exit()
operation = input("what operation would you like? \nvalid operations include:\n/ - divide\n* - multiply\n+ - add\n- - subtract\n")
while valid > 0:
if operation in valid_operations:
if operation == "/":
print(f"Answer = {int(num_1) / int(num_2)}")
valid -= 3
elif operation == "*":
print(f"Answer = {int(num_1) * int(num_2)}")
valid -= 3
elif operation == "+":
print(f"Answer = {int(num_1) + int(num_2)}")
valid -= 3
elif operation == "-":
print(f"Answer = {int(num_1) - int(num_2)}")
valid -= 3
else:
print(f"that is not a valid operation you have {valid} more attmepts to type a valid operation")
valid -= 1
time.sleep(2)
want_rep = input("would you like to do another calculation? y/n\n")
if want_rep == "y":
repeat = "y"
elif want_rep == "n":
repeat = "n"
else:
print("that is not a valid response, please choose either yes - y or no - n")
exit()
Problem lies in the valid variable.
You define it as 3 before the first iteration.
Then, inside the second while loop, it is reduced to 0 by
valid -= 3
And you never restore the starting value. So, the program comes back to the operation input, reads the loop condition:
while valid > 0:
And omits it, as valid equals 0.

If statement is not working in my program

import time
name=input("Enter your name:")
currentTime = int(time.strftime('%H'))
if currentTime < 12 :
print('Good morning,'+name)
elif currentTime > 12 :
print('Good afternoon,'+name)
else :
print('Good evening,'+name)
def main():
import random
guess: int = input('Enter a number the between 1 and 2 :')
if guess <= "2":
num: int = random.randint(1, 2)
print("the number is ", num)
if num == guess: #### this if statement is not working
print('you won'
'your promote to level 2')
else:
print("You lost", ",Lets try again")
repeat = input('Do you want to try again:')
if repeat == "yes":
main()
else:
print("Good bye")
exit()
else:
print("the number you entered is grater than 5,Please enter a number between 1 and 2")
main()
main()
The if statement in this code not working (I have highlighted that if statement in code) But else statement is working to both conditions.
In your code guess is of type str, read the docs of input:
The function then reads a line from input, converts it to a string
(stripping a trailing newline), and returns that
When you do guess: int you are using a type hint. The docs say:
The Python runtime does not enforce function and variable type
annotations. They can be used by third party tools such as type
checkers, IDEs, linters, etc.
In your if you are trying to compare a int to a str. Run this in the Python console to see:
print(1 == '1') # --> False
print(1 == 1) # --> True
So what you need to do is explicitly convert it to int:
guess = int(input('Enter a number the between 1 and 2 :'))
And change the first if to:
if guess <= 2:
...
(removing the quotes in "2").
With these changes, your if statements will work.

Syntax for else statement in Python

I am very new to python and my else statement keeps on getting a syntax error.
I'll comment the else where the syntax is.
print("""
(A)ddition
(S)subtraction
(D)ivision
(M)multiplication
""")
operation = input("select an operation from above (initials) = ")
if(operation == "A","S","D","M"):
#this is where i am getting syntax
else:
print("select valid operation.")
number1 = int(input("first number = "))
number2 = int(input("second number = "))
if(operation == "A","M","D","S"):
if operation == "A":
print("this is the result = ", number1+number2)
elif operation == "S":
print("this is the final result", number1 - number2)
elif operation == "M":
print("this is the final result", number1 * number2)
elif operation == "D":
print("this is the final result", number1/number2, ".And this is the remainder = ",number1&number2)
you do not have to indent the else sentece.
if:
else:
You need to put something in the if statement above and the else statement should be at the same indentation.
As others have pointed out, you can't have a blank space after an if or an else.
Since you only want the else part, you have to negate the if criteria, so it becomes the if part.
So:
if(operation == "A","S","D","M"):
do_nothing = True
else:
print("select valid operation.")
becomes:
if operation not in ("A","S","D","M"):
print("select valid operation.")
(And yes, your == isn't going to work either on a list like that, you need in)

Why does one of my functions just loop back when not meant to?

I am trying to create a simple code guessing game where the user can choose the minimum and maximum number the randomly generated code can be. The user has to try and guess the code to win. When I run my code, the get_range() function works and then it proceeds to the get_guess() function as it should. But when the user enters his/her input for their guess, the code loops back to the start of the get_range() function. Please can anyone help? Thanks in advance. Code:
import random
import string
print("Welcome to Code Crunchers!")
def get_range():
Min = str(input("Enter the minimum number that the code can be: "))
Max = str(input("Enter the maximum number that the code can be: "))
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min != True or Check_Max != True:
print("Input must only contain integers!")
get_range()
elif Min == Max:
print("Minimum and maximum number must not be equivalent!")
get_range()
elif Min > Max:
print("Maximum number must be greater than minimum number!")
get_range()
else:
Random_Number = random.randrange(int(Min), int(Max))
get_guess()
return Random_Number
def get_guess():
Guess = str(input("Enter your guess: "))
Check_Guess = Guess.isdigit()
if Check_Guess != True:
print("Input must only contain integers!")
get_guess()
else:
validate()
return Guess
def validate():
Random_Number = get_range()
Tries = locals()
Guess = get_guess()
Length = len(str(Random_Number))
Digits_Correct = 0
if Guess == Random_Number:
print("Well done! You guessed the number in", Tries, " tries!")
else:
Digits = ["?"] * Length
Tries += 1
for i in range(0, int(Length)):
if Guess[i] == Random_Number[i]:
Digits[i] = Guess[i]
Digits_Correct += 1
else:
continue
if int(Length) > Digits_Correct > 0:
print("Not quite! You got", Digits_Correct, " digits correct.")
print(Digits)
get_guess()
elif Digits_Correct == 0:
print("None of your digits match!")
get_guess()
def play_again():
Choice = input("Do you want to play again (y/n)?")
if Choice != "y" or Choice != "n" or Choice != "Y" or Choice != "N":
print("Please choose a valid option!")
play_again()
elif Choice == "y" or Choice == "Y":
get_range()
elif Choice == "n" or Choice == "N":
exit()
get_range()
Because you're re-calling get_range() in validate():
def validate():
Random_Number = get_range() # <-- Here
...
You might be able to solve this with:
def validate():
Random_Number = random.randrange(int(Min), int(Max))
...
But overall, that will depend on the direction of your code. Hope that helps!
Take a look at this code:
def get_range():
...
else:
...
get_guess()
return Random_Number
def get_guess():
...
else:
validate()
return Guess
def validate():
Random_Number = get_range()
Tries = locals()
Guess = get_guess()
...
Suppose you're in get_guess and get to the else close, so you call validate. Here's what happens:
get_guess calls validate
validate immediately calls get_range
get_range calls get_guess
now we're back in get_guess, see (1)
So your code enters infinite indirect recursion.
Notice how it'll never get past Random_Number = get_range() in validate, and you're calling get_guess in both get_range and validate.
So, before returning the random number to Random_Number = get_range(), get_range will try to get_guess and immediately discard its return value (that's what get_guess() does). Suppose that get_range eventually returns. Now you'll call Guess = get_guess() again, thus asking the user to guess twice. I think there's a logic flaw here.

Categories

Resources