Program exits too early - python

My code is working properly the only thing I want to change in my program is after congratulations message the program should ask user again to input a number until user input zero as quit.
Til now if I run my code after congratulations message program exits.
import random
import datetime
e = datetime.datetime.now()
print(e.strftime("%B %d,%Y # %H:%M:%S"))
number = random.randint(1, 100)
print(number)
name = input("\nEnter your name: ")
def main():
print(f"Hi, {name}, Welcome to the Guessing Number Game ")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
if x == 0:
print("You quit? Goodbye!")
else:
playGuessingGame(x)
def playGuessingGame(x):
times = 1
while number != x:
times += 1
if x < number:
print("Too low, try again")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
elif x > number:
print("Too high, try again")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
print(f"Congratulations {name}!, you guessed the right number with {times} tries!")
main()
After congratulations message the program should ask user again to input a number until user input zero as quit.

since you have not added break inside while loop in playGuessingGame(). so program continuously asking to enter number even though you have entered zero
def playGuessingGame(x):
times = 1
while number != x:
times += 1
if x < number:
print("Too low, try again")
x = eval(input("Enter a number between 1 and 100, or 0 to quit: "))
break #since this was missing, program doesn't break the while loop
elif x > number:
print("Too high, try again")
x = int(input("Enter a number between 1 and 100, or 0 to quit: "))
break #since this was missing, program doesn't break the while loop

Related

Display the number of times each output was displayed in 'X's

while True:
try:
wins = int(input("enter number of wins: "))
draws = int(input("enter number of draws: "))
losses = int(input("enter number of losses: "))
except ValueError:
print('try again')
continue
if wins>3:
print('qualify')
elif losses>3:
print('disqualify')
elif draws>3:
print('try again')
restart = str(input('enter "restart" to restart or "quit" to quit'))
if restart == 'restart':
continue
elif restart == 'quit':
#quit and display number of occurrences of qualify, disqualify and try again in 'X's
First you need to track the count of each result. You could do this with three different variables, but I think it's a little easier to use a dictionary, or better yet a Counter:
from collections import Counter
counts = Counter()
Make sure to initialize this outside your loop, since you want to keep the same Counter through multiple iterations of the loop; if you reset it inside the loop, it won't keep track of anything!
Then track the results as you see them:
if wins > 3:
result = "qualify"
elif losses > 3:
result = "disqualify"
elif draws > 3:
result = "try again"
else:
print("Not enough of anything to produce a result!")
continue
print(result)
counts[result] += 1
and then at the end, you can convert the counts into "X" marks by string multiplication:
for result in counts:
print(f"{result}: {'X' * counts[result]}")
All together it looks like:
from collections import Counter
counts = Counter()
while True:
try:
wins = int(input("enter number of wins: "))
draws = int(input("enter number of draws: "))
losses = int(input("enter number of losses: "))
except ValueError:
print("try again")
continue
if wins > 3:
result = "qualify"
elif losses > 3:
result = "disqualify"
elif draws > 3:
result = "try again"
else:
print("Not enough of anything to produce a result!")
continue
print(result)
counts[result] += 1
if str(input('enter "restart" to restart or "quit" to quit')) == "quit":
break
for result in counts:
print(f"{result}: {'X' * counts[result]}")
I didn't understand your question but based on what I understood I constructed a solution. This will show you the result of occurrence of qualify and disqualify
qualifycount=0
disqualifycount=0
while True:
try:
wins = int(input("enter number of wins: "))
draws = int(input("enter number of draws: "))
losses = int(input("enter number of losses: "))
except ValueError:
print('try again')
continue
if wins>3:
print('qualify')
qualifycount+=1
elif losses>3:
print('disqualify')
disqualifycount+=1
elif draws>3:
print('try again')
restart = str(input('enter "restart" to restart or "quit" to quit'))
if restart == 'restart':
continue
elif restart == 'quit':
#quit and display number of occurrences of qualify, disqualify and try again in 'X's
print("Number of qualify:"+str(qualifycount))
print("Number of disqualify:"+str(disqualifycount))
restart= str(input('press X to run again or press enter to quit'))
if restart=='X':
continue
else:
break

How to make random.randit get new number, every time the game starts again

i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)

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)

How to end the program (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'.

Python Nested Loop Enter Value and Confirm Answer

I'm trying to write a simple block of code that has a user enter an interest rate. The number must be 0 or greater, any other value will be rejected, the user must be polled until a valid number is input. If the number is greater than 10%, the user must be asked if he/she really expects an interest rate that high, if the user replies in the affirmative, the number is to be used, otherwise the user will be asked to input the value again and the above checks will be made. I'm having trouble understanding the nested loop aspect of this. Any help is greatly appreciated!
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
except ValueErrror:
print("Entered value is not a number! ")
except KeyboardInterrupt:
print("Command Error!")
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
main()
do it all in the try, if inp > 10, ask if the user is happy and break if they are, elif user input is within threshold just break the loop:
def main():
while True:
try:
interest_rate = int(input("Please enter an interest rate: "))
if interest_rate > 10:
confirm = input("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
if confirm =="y":
break
elif 0 <= interest_rate < 10:
break
except ValueError:
print("Entered value is not a number! ")
return interest_rate
main()
Three things jump out:
1) ValueErrror should be ValueError
2) You don't handle the user input on the final test
3) You probably want to change the < 10 to be <= 10
else:
if 0 <= interest_rate < 10:
break
elif interest_rate > 10:
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
can be:
if 0 <= interest_rate <= 10:
break
print("Entered interest rate is greater than 10%. Are you sure? (y/n): ")
except the last line must take the response and process it.
Your else was not related to an if
Your elif was unnecessary after break
Make the print("Entered interest rate is greater than 10%. Are you sure? (y/n): ") an input
answer = int(input("Are you sure?"))
if answer == "y":
break
I usually prefer to break down the solution and validation into different modules. Please check the below code to see how I break them down. So it is easy when it comes to debugging and testing.
def validating_user_input(num):
"""
"""
return num > 0
def getting_user_input():
"""
"""
user_input = int(raw_input("Enter the number that is greater than 0: "))
return user_input
def confirming_choose():
"""
"""
try:
user_choose = int(raw_input("Can you confirm your input? [0|1]? "))
except ValueError:
return False
return user_choose == 1
def main():
"""
"""
initial_cond = True
while initial_cond:
user_input = getting_user_input()
if validating_user_input(user_input):
if user_input > 10:
confirmation = confirming_choose()
while not confirmation:
getting_user_input()
#do you operating here
initial_cond = False
else:
print "It is not valid input."
if __name__ == "__main__":
main()

Categories

Resources