Closing program with while loop - python-3.x

I'm new to Python v3 and am using a while loop at the end of my program to determine if the user wants to restart/retry the program or finish.
If I select yes and I repeat the program more than once and then select no, I keep returning the "Would you like to search again: (Y/N) > " option for the number of times I re-tried the program e.g. 3 attempts and I have to enter n three times before break takes effect.
Code used is below.
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == ("y"):
my_project()#restarts the program from the start
continue
elif finish_input.lower() == "n":
print()
print("Thank you for using this service.")
break
else:
print()
print("Invalid entry. Please enter Y or N")
I want the option to restart but only have to input n once to close/break the program and exit. Help would be really appreciated.

What you want is:
def my_project():
#Your other code here
my_project()
#The code that you posted
But you are doing:
def my_project():
#Your other code here
#The code that you posted
The difference is that in the last one, you are looping inside the program: each y is another call to the whole function that later and for each one of those you'll have to put n.
The code would look like this:
def my_project():
#Your other code here
my_project()
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == "y": my_project()
elif finish_input.lower() == "n":
print("\nThank you for using this service.")
break
else: print("\nInvalid entry. Please enter Y or N")

I think its a bad way to implement this. How about doing something like this.
#program starts
run_prog = True
while run_prog:
#Your original code
finish_input = "a"
while True:
finish_input = input("Would you like to search again: (Y/N) > ")
if finish_input.lower() == ("y"):
run_prog = True
break
elif finish_input.lower() == "n":
run_prog = False
print()
print("Thank you for using this service.")
break
else:
print()
print("Invalid entry. Please enter Y or N")

Related

How do I print a new line in the program for the user to type in their answer on?

I am coding a Python dice game. I want the game to start when the user lets it.
So far I have this code:
number = random.randint(1, 6)
print("Do you want to roll the die?")
answer = input("Please type 'yes' or 'no': ")
dic = {"yes"}
while(True):
answer = input()
if answer in dic:
print("You have rolled: ", (number))
break
else:
print("oh.")
But when the program runs, the user has to type "yes" in twice, for it to register it.
How do I skip the user having to type on the "Please type 'yes' or 'no': " line, so that they answer only once, on the line after it?
I have tried using print(), but I'm not sure where to put it so that it doesn't cause errors.
Thank you
The user is prompted twice because you're calling the input function twice. You only need to call it inside the loop.
number = random.randint(1, 6)
print("Do you want to roll the die?")
dic = {"yes"}
while(True):
answer = input("Please type 'yes' or 'no': ")
if answer in dic:
print("You have rolled: ", (number))
break
else:
print("oh.")

python simple help (NameError: name is not defined)

Whenever I run this is get:
Traceback (most recent call last):
File "main.py", line 130, in <module>
while is_playing_cg:
NameError: name 'is_playing_cg' is not defined
I want the user to be able to press 1 or 2 to select which game mode to use and then once pressed it starts. I don't know why it's doing this. Whenever it's fixed it should run through just fine.
New edit
Now it just loops and says 1 or 2 over and over again.
import random
is_playing_cg = False
is_playing_hg = False
def game_select_screen():
#Game Select Screen
print("""
._________________________________.
| |
| ~ Welcome To Guess-A-Number ~ |
| ~~~ |
| ~ Press 1 OR Press 2 ~ |
| You ^ Guess | PC ^ Guess |
|_________________________________|""")
selecting = True
while selecting:
print()
game_mode = input("1 OR 2: ")
try:
int(game_mode)
except ValueError:
print("This is not a Number.")
else:
game_mode = int(game_mode)
if game_mode == 1:
is_playing_hg = True
elif game_mode == 2:
is_playing_cg = True
#Defining Random Number for human guess
def play_human_guess():
num = random.randint (1,10)
print()
print("Im Thinking of a Number 1 Through 10.")
print("You Have 3 Chances.")
chances = 3
game_fisnished = False
#Game is playing (Human Guesses)
while not game_fisnished:
guess = input("> Take A Guess: ")
#Accept only numbers
try:
int(guess)
except ValueError:
print("This is not a Number.")
else:
guess = int(guess)
if guess < num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too Low. ("+str(chances)+") Chance(s) Remaining.")
elif guess > num:
chances -=1
if chances == 0:
print()
print("Sorry You Guessed Too Many Times.")
game_fisnished = True
elif chances !=0:
print()
print("You Guessed Too High. ("+str(chances)+") Chance(s) Remaining.")
else:
print()
print("Congradulations, You Won!")
game_fisnished = True
#Game Ended
def end():
print()
print("Thanks For Playing!")
#Setting up for computer guess
def play_computer_guess():
print()
print("Pick a Number 1 Through 10")
print("I Have 3 Chances to Guess Your Number.")
chances = 3
game_fisnished = False
#Game is playing (Computer Guess)
while not game_fisnished:
guess1 = input("Is your number 5?")
#Show Game Select Screen
game_select_screen()
while is_playing_cg:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while is_playing_hg:
#Start Game
selecting = False
play_human_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_hg = False
end()
The variable is_playing_cg is only available in the "block" that creates it.
Block is function / loop / if statement / etc.
In your program you need to initialize the variable globally so you can call them in multiple functions.
Good luck!
You are defining is_playing_cg inside of a conditional statement at the top of your code. So if that option is not selected, then when you get to the latter conditional statement, it has never heard of that variable.... and it is not defined in the namespace. So you could either define it at the top and give it a default (False) or more better, because you only have 2 options, just use one variable to control the computer / human.
Here is a toy example:
selection = int(input('enter 1 for human, 2 for computer: '))
if selection == 1:
human_play = True
elif selection == 2:
human_play = False
else:
# make some loop that asks for input again or such...
pass
# later on...
if human_play:
# ask human for input...
else:
# have AI make turn
#if needed, you can also handle special cases like this:
if not human_play:
# do something unique to computer turn ...
Additional info...
So you got bit by the scope of the variables in your update. You are defining these variables inside of a function and when you put the defaults outside of the function, they are not in the same scope, so whatever you do inside the function is lost. So, you need to change your function into something that returns the mode you want, and catch that in the function call like such:
def ... :
# input ...
if game_mode == 1:
human_playing = True
selecting = False
elif game_mode == 2:
human_playing = False
selecting = False
return human_playing # this will return T/F back to the function call
And then later:
#Show Game Select Screen
human_playing = game_select_screen()
while not human_playing:
#Start Game
selecting = False
play_computer_guess()
answer = input("""
Do You Want to Play Again? (y/n) : """)
if answer == "n":
is_playing_cg = False
while human_playing:
#Start Game
This (above) works for me, but there are still other logic errors popping up! :) Have fun
This particular error is probably there because you have not defined is_playing_cg as global before using it in your function game_select_screen. Simply put global is_playing_cg at the start of your game_select_screen function to tell python you want to use the global variable instead of creating a scoped variable.

Giving user chance to select new option in same program instance

For my program, I want to give the person using my program the chance to select a different option without having to restart the program itself. I've tried a few different things and I've had no luck successfully doing it. Below is the main part of my code where I attempted to implement a "redo" option.
restart = input("Would you like to look at other car insurance companies? y/n: ").lower()
while restart == "y":
def ins_option():
while True:
try:
ins_num = int(input('Please select the car insurance you want information on:\n1 for {}\n2 for {}\n3 for {}\n4 for {}\n5 for {}\nChoice:'.format(astate, pro, sfarm, lmut, gei)))
except ValueError:
print("Your input is not a number, please try again.\n")
else:
if 0 >= ins_num or ins_num > len(ins):
print("Invalid value, please try again.\n")
else:
return ins_num
if restart == "n":
break
option = ins_option()
ins_name = insurance[option - 1]
print("\n Ok, here is information about {}:\n\n {}".format(ins_name,ins[ins_name][0]))
You should not define a function inside a loop as you are doing.
A way to do it could be the follow. First define the function:
def ins_option():
while True:
try:
ins_num = int(input('Please select the car insurance you want information on:\n1 for {}\n2 for {}\n3 for {}\n4 for {}\n5 for {}\nChoice:'.format(astate, pro, sfarm, lmut, gei)))
except ValueError:
print("Your input is not a number, please try again.\n")
else:
if 0 >= ins_num or ins_num > len(ins):
print("Invalid value, please try again.\n")
else:
return ins_num
Then you call the function until the input is "n":
restart="y"
while restart == "y":
option = ins_option()
print("\n Ok, here is information about option:", option)
restart = input("Do you want information about a different car insurance company? y/n: ").lower()

How to access the variable delcared inside a function outside the function in Python 3?

I am trying to make a simple guess the number program in python. When I run this code,an error generates saying that,"local variable 'chance' referenced before assignment". I looked up for a solution on internet but I could not rectify my error. Please help with this problem. How can I use the variable globally which is declared inside a function?
I am beginner in programming, so plese explain in simple words.
Here is the code..
Since I am a beginner,I will be pleased if my code can be rectified
import random
def Random():
chance = 3
number = random.randint(0,20)
return chance
return number
def main():
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print(f'You have {chance} chances left!')
Random()
main()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
main()
else:
print('Thanks for playing!')
You can return a list or a tuple to the outside word:
import random
def example():
chance = 3
number = random.randint(0,20)
return (chance, number) # return both numbers as a tuple
chance, randNr = example() # decomposes the returned tuple
print(chance, randNr)
prints:
3, 17
There are more bugs in your program, f.e.:
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
is always True and you'll never be able to leave the game. Better would be
if playAgain.lower() in {'yes', 'yeah'}:
etc.
Here is a working example for your programs purpose:
import random
while True:
chances = 3
number = random.randint(0,20)
while chances > 0:
guess = int(input("Guess number: "))
if guess == number:
print("Correct")
break
else:
chances -= 1
print("Wrong, ", chances, " more tries to get it right.")
if chances == 0:
print ("You failed")
if not input("Play again? ")[:1].lower() == "y":
break
print("Bye.")
Read about tuples
Output:
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong, 2 more tries to get it right.
Guess number: 2
Wrong, 1 more tries to get it right.
Guess number: 3
Wrong, 0 more tries to get it right.
You failed
Play again? n
Bye.
import random
def Random():
chance = 3
number = random.randint(0,20)
main(chance,number)
def main(chance,number):
while chance > 0:
UserInput = int(input('Guess the number: '))
if UserInput == number:
print('You have guesses the secret number!')
elif UserInput > 20 and UserInput < 0:
print('Your guess is out of range!\n Try again!')
else:
chance -= 1
if chance == 1:
print('You are out of chances!')
print('Wrong Guess!\nTry again!')
print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
Random()
else:
print('Thanks for playing!')

How do I clear the screen in Python 3?

Here is my code (for hangman game):
import random, os
def main():
print("******THIS IS HANGMAN******")
print("1. Play Game ")
print("2. Quit Game ")
choice = input("Please enter option 1 or 2")
if choice == "1":
words = ["school", "holiday", "computer", "books"]
word = random.choice(words)
guess = ['_'] * len(word)
guesses = 7
while '_' in guess and guesses > 0:
print(' '.join(guess))
character = input('Enter character: ')
if len(character) > 1:
print('Only enter one character.')
continue
if character not in word:
guesses -= 1
for i, x in enumerate(word):
if x == character:
guess[i] = character
if guesses == 0:
print('You LOST!')
break
else:
print('You have only', guesses, 'chances left to win.')
else:
print('You won')
elif choice == "2":
os.system("cls")
main()
else:
print("that is not a valid option")
main()
I have tried os.system("clear") but it doesn't clear the screen, I want it to clear the entire screen but instead (cls) makes it print my menu again and (clear) does nothing except clear the 2. If I'm missing something obvious it's probably because I'm new to python.
It prints the menu again because you call main() again instead of just stopping there. :-)
elif choice == "2":
os.system("cls")
main() # <--- this is the line that causes issues
Now for the clearing itself, os.system("cls") works on Windows and os.system("clear") works on Linux / OS X as answered here.
Also, your program currently tells the user if their choice is not supported but does not offer a second chance. You could have something like this:
def main():
...
while True:
choice = input("Please enter option 1 or 2")
if choice not in ("1", "2"):
print("that is not a valid option")
else:
break
if choice == "1":
...
elif choice == "2":
...
main()

Resources