How to end the program (Python)? - python

I'm a newbie in Python3 coding and I have a problem here.
In line 14, I intended to end this program by printing "Thank you! Goodbye" at the part where you answer "n" to "try again?". However, it turned out that I would start all over again even if I've inserted "break" under it. Now, the only solution I can come up is to end the whole program with sys.exit(0), but I don't consider it an ideal solution since it just closes the whole program down.
import sys
while True:
x=int(input("Enter the coins you expected="))
f=int(input("Enter first coin="))
while f!=1 and f!=5 and f!=10 and f!=25:
print("invalid number")
f=int(input("Enter first coin="))
if x>f:
while x>f:
n=input("Enter next coin=")
if not n:
print("Sorry-you only entered",f,"cents")
again=input("Try again (y/n)?=")
if again=="y":
True
elif again=="n":
print("Thank you, goodbye!")
sys.exit(0)
break
while int(n)!=1 and int(n)!=5 and int(n)!=10 and int(n)!=25:
print("invalid number")
n=input("Enter next coin=")
f=f+int(n)

Replace your whole code with this:
import sys
Stay = True
while Stay:
x = int(input("Enter the coins you expected = "))
f = int(input("Enter first coin = "))
while f != 1 and f != 5 and f != 10 and f != 25:
f = int(input("Invalid number entered./nEnter first coin = "))
while x > f and Stay:
n = input("Enter next coin = ")
if not n:
print("Sorry, you only entered " + str(f) + " cents")
again = input("Try again (y/n)?=")
if again == "n":
print("Thank you, goodbye!")
Stay = False
if Stay:
n = int(n)
while n != 1 and n != 5 and n != 10 and n != 25:
print("Invalid number entered.")
n = int(input("Enter next coin = "))
f += n
I made your code more readable and fixed your problem by using a Boolean flag (Stay). This basically means that the program runs while Stay is True, and Stay becomes False when the user enters 'n'.

Related

How do I make a program keep repeating until I input a specific data that stops it?

I'm trying to make a program in python so that when I input a number from 1 to 10, a specific set of program goes on and asks for another number from 1 to 10 and runs another program, until I enter 0(zero) and the program stops.
So my guess was using a while loop but it didn't quite work out.
user_input = input()
user_input = int(user_input)
while user_input != 0:
(program)
else:
quit()
Try this:
user_input = int(input())
while user_input != 0:
(program)
user_input = int(input())
quit()
With your current code you only ask for input once so the loop won't end. This way you can input a new number after every iteration.
Your current program only asks once and then the loop keeps repeating. You need to keep asking for input inside the loop.
def program():
print("Executing Task....")
user_input = int(input())
while user_input != 0:
program()
user_input = int(input())
printf("Program Terminated")
Here it is:
def program():
pass
user_input = int(input())
while user_input:
program()
user_input = int(input())
quit(0)
A different way using iter with a sentinel:
def program(number):
if number < 0 or number > 10:
print('Invalid number:', number)
else:
print('Valid number:', number)
def quit():
print('quitting')
def get_number():
return int(input('Enter a number from 1 to 10: '))
for number in iter(get_number, 0):
program(number)
else:
quit()
not_zero = True
while not_zero:
num = int(input("Enter a number: "))
if num == 0:
not_zero = False
you can stop your loop using a boolean value.

Why does the process just stop even though I have some command? [duplicate]

This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
Closed 2 years ago.
I am trying to make a code guessing game where the user can choose the range of the code. The user tries to guess the randomly generated code until he/she gets it right. The computer also shows which digits the user gets correct. The problem is that when the user does guess the code correctly, the process just stops even though my codes says to print a congratulations message and go to the play again function. Please can anyone help? Thanks. Code:
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
elif Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if Guess == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[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(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
Choice = input("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()
I think the problem here is that your Guess is a string and your Random is an integer. To fix this, you can try to convert the Guess to an integer or the Random to a string.
Try this:
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
I think your problem is with types str and int. First of all your Min and Max are strings, so your line:
elif Min > Max: print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
does not work correctly. The other problem is that your variables Guess and Random are of different types, so Guess == Random will return False all the time.
Here's correct version of your code.
I've also added a few if cases to be able to quit the program without closing it.
import random
import string
def get_range():
Min = input("ENTER THE MINIMUM NUMBER THE CODE CAN BE: ")
Max = input("ENTER THE MAXIMUM NUMBER THE CODE CAN BE: ")
if Min == 'q':
return
validate_range(Min, Max)
def validate_range(Min, Max):
Check_Min = Min.isdigit()
Check_Max = Max.isdigit()
if Check_Min is not True or Check_Max is not True:
print("INPUT MUST ONLY INCLUDE INTEGERS! ")
get_range()
Min = int(Min)
Max = int(Max)
if Min == Max:
print("MINIMUM AND MAXIMUM NUMBER MUST NOT BE EQUIVALENT! ")
get_range()
elif Min > Max:
print("MINIMUM NUMBER MUST NOT BE GREATER THAN MAXIMUM NUMBER!")
get_range()
else:
Random = random.randrange(int(Min), int(Max))
get_guess(Random)
def get_guess(Random):
Guess = str(input("ENTER YOUR GUESS: "))
Check_Guess = Guess.isdigit()
if not Check_Guess:
print("INPUT MUST ONLY CONTAIN INTEGERS! ")
get_guess(Random)
else:
validate_guess(Guess, Random)
def validate_guess(Guess, Random):
Length = len(str(Random))
Digits_Correct = 0
if int(Guess) == Random:
print("WELL DONE! YOU GUESSED THE NUMBER! ")
play_again()
else:
Digits = ["?"] * Length
for i in range(0, int(Length)):
if str(Guess)[i] == str(Random)[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(Random)
elif Digits_Correct == 0:
print("NONE OF YOUR DIGITS MATCH! ")
get_guess(Random)
def play_again():
print("\n DO YOU WISH TO PLAY AGAIN? (Y/N)")
Choice = input()
if Choice != "Y" or Choice != "N" or Choice != "y" or Choice != "n":
print("PLEASE ENTER A VALID INPUT! ")
play_again()
else:
get_range()
print("WELCOME TO CODE CRUNCHERS!\n ")
get_range()

About quitting the factorial program in an endless loop [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
My goal is creating a factorial program in python that asks infinite user input to find factorial of the number user type, until I would like to quit the program. But there is probably discrepancy between the lines of the code to works for exit the program and integer numbers below it.
1) I tried to solve this to not write int(input) I wrote just
input('Enter a number. Type exit to stop:> ')
both above or below the while True statement but it didn't work.
2) I also want to use lower() function to quit the program but when I use it, the discrepancy happens again because I ask user input for an integer but when I turn it to a normal input and type it the above while True statement, problem occurs.
3) Also I want to user input as a number with using that isdigit() function tried to use like this but it didn't work well:
factorial = 1
user_input = input('Enter a number: ')
while user_input.lower() != 'exit':
while not user_input.isdigit():
print('This is not a number. Please try again:> ')
user_input = int(input('Try again:> '))
user_input = int(input('Enter a new number: '))
.
.
.
and this, too didn't work
My actual code is this:
while True:
factorial = 1
user_input = int(input('Enter a number. Type exit to stop:> '))
if user_input == 'exit':
print('You are quitting the program')
break
elif user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
The program works like this:
Enter a number. Type exit to stop:> 4
The factorial of 4 is 24
Enter a number. Type exit to stop:> 5
The factorial of 5 is 120
Enter a number. Type exit to stop:> 6
The factorial of 6 is 720
and when I type 'exit' to quit from program I am receiving this kind of error:
Traceback (most recent call last):
File "E:/Kodlar/Python/Taslak projeler/taslak177.py", line 5, in <module>
user_input = int(input('Enter a number. Type exit to stop:> '))
ValueError: invalid literal for int() with base 10: 'exit'
As you can see, code blocks work instead of quitting the program with user input. How can I fix this?
Can anyone help? Thanks already!
Edit: I reorganized the code and it works perfectly fine. Thanks for your all responses!
while True:
user_input = input("Enter a number:> ")
if user_input == "exit":
print('You are quitting the program...')
break
else:
try:
factorial = 1
user_input = int(user_input)
if user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input == 0:
print("The factorial of 0 is 1")
else:
for i in range(1, user_input + 1):
factorial = factorial * i
print(f'The factorial of {user_input} is {factorial}')
except ValueError:
print("Please provide a valid number")
You should check if the input is exit before converting it to int and if so, break the loop.
Try this instead:
while True:
user_input = input("Enter a number:")
if user_input == "exit":
print('You are quitting the program')
break
else:
try:
user_number = int(user_input)
if user_number < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_number == 0:
print("The factorial of 0 is 1")
else:
# calc factorial here
except ValueError:
print("Please provide a valid number")
Your program get int inputs,
user_input = int(input('Enter a new number: '))
try this instead, get string input
user_input = input('Enter a new number: ')
and convert it into int later
user_input = int(user_input)
Because you are casting the user's response (a string) into an int in both cases.
user_input = int(input('Enter a new number: '))
and later
user_input = int(input('Enter a number. Type exit to stop:> '))
Perhaps try a little tweak:
while True:
factorial = 1
user_input = input('Enter a number. Type exit to stop:> ')
if user_input.lower().strip() == 'exit':
print('You are quitting the program')
break
elif user_input.isnumeric() and user_input < 0:
print("Sorry, factorial does not exist for negative numbers")
elif user_input.isnumeric() and user_input == 0:
print("The factorial of 0 is 1")
elif user_input.isnumeric():
for i in range(1, user_input + 1):
factorial = factorial * i
print("The factorial of", user_input, "is", factorial)
else:
print("Please enter an integer or 'exit'")
You could also wrap another if so you don't duplicate the isnumeric() tests

Using system.exit

I am trying to add a sys.exit to my code now, but I want it to display the print messages before quitting. Can I do this? Also, at the end of my code, I would like to give the user the option to quit or start again, but when they type quit after finishing the first game, it just uses quit as their name.
import random
import sys
def system_exit(exitCode):
sys.exit()
# uses randrange instead of randint for better results in Python 3.7
# randrange stops just before the upper range, use (1, 11) for 1-10
num = random.randrange(1, 11)
name = input("What is your name? Or if you would rather quit, type quit at
any time. " "\n")
i = name
while i != "quit":
print('Hello', name,'!')
while i.lower() == 'quit':
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.")
system_exit(4)
your_guess = input('Enter a number between 1 and 10.' '\n')
if (your_guess.lower() == "quit"):
print ("Sorry, you did not select a number in the range or
selected to quit. Good bye.") #this isn't showing up before closing
your_guess = int(your_guess)
# display the number guessed
print("Your number is", your_guess)
while num != your_guess:
if your_guess < num:
print("Your guess is too low.")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
elif your_guess > num:
print("Your guess is too high")
your_guess = int(input("Guess another number from
1 to 10: " '\n'))
else:
print ("Sorry, you did not select a number in the
range or selected to quit. Good bye.") #this isn't showing up before
closing
system_exit(4)
print("The correct number was", num)
print("***************************************************************")
name = input("What is your name? Or if you would rather quit, type
quit. ")
num = random.randrange(1, 11)
print("Thank you for playing!") #this isn't showing up before closing
system_exit(0)
Replace the following line of code:
your_guess = int(input('Enter a number between 1 and 10.'))
with the code below:
your_guess = input('Enter a number between 1 and 10.')
if (your_guess.lower() == 'quit'):
#print some break message
your_guess = int(your_guess)

User input Exit to break while loop

I'm doing an assignment for the computer to generate a random number and have the user input their guess. The problem is I'm supposed to give the user an option to input 'Exit' and it will break the While loop. What am I doing wrong? I'm running it and it says there's something wrong with the line guess = int(input("Guess a number from 1 to 9: "))
import random
num = random.randint(1,10)
tries = 1
guess = 0
guess = int(input("Guess a number from 1 to 9: "))
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess == str('Exit'):
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
The easiest solution is probably to create a function that gets the displayed message as an input and returns the user input after testing that it fulfils your criteria:
def guess_input(input_message):
flag = False
#endless loop until we are satisfied with the input
while True:
#asking for user input
guess = input(input_message)
#testing, if input was x or exit no matter if upper or lower case
if guess.lower() == "x" or guess.lower() == "exit":
#return string "x" as a sign that the user wants to quit
return "x"
#try to convert the input into a number
try:
guess = int(guess)
#it was a number, but not between 1 and 9
if guess > 9 or guess < 1:
#flag showing an illegal input
flag = True
else:
#yes input as expected a number, break out of while loop
break
except:
#input is not an integer number
flag = True
#not the input, we would like to see
if flag:
#give feedback
print("Sorry, I didn't get that.")
#and change the message displayed during the input routine
input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
continue
#give back the guessed number
return guess
You can call this from within your main program like
#the first guess
guess = guess_input("Guess a number from 1 to 9: ")
or
#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")
You are trying the parse the string 'Exit' to an integer.
You can add a try/except around the casting line and handle invalid input.
import random
num = random.randint(1,9)
tries = 1
guess = 0
guess = input("Guess a number from 1 to 9: ")
try:
guess = int(guess) // try to cast the guess to a int
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
except ValueError:
if guess == str('Exit'):
print("Good bye")
else:
print("Invalid input")

Categories

Resources