Giving user chance to select new option in same program instance - python-3.x

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()

Related

Is there a way to automatically input the value “1” when the user decides to press 'enter' without giving a value?

How do I pre-set the system to give the display the value '1' if they do not enter any value (i.e., user just press enter). I kept having the error whereby the system forces me to have a number.
def get_variance():
while True:
variance = input("Please enter variance which must be greater than 0! ")
try:
value = int(variance)
if value > 0:
print(f"Variance inserted is: {value}.")
break
else:
print("You have entered a value less than 0, try again!")
except ValueError:
print("Amount must be a number, try again")
get_variance()
You first :
pip install pynput
Then you can use the following code:
from pynput.keyboard import Key, Controller
def get_variance():
while True:
variance = input("Please enter variance which must be greater than 0! ")
keyboard = Controller()
keyss = "enter"
if keyss =='enter':
print('You must enter the number one')
else:
try:
value = int(variance)
if value > 0:
print(f"Variance inserted is: {value}.")
break
else:
print("You have entered a value less than 0, try again!")
except ValueError:
print("Amount must be a number, try again")
get_variance()
Yes. Using the EAFP strategy of "easier to ask forgiveness than permission".
while True:
try:
value = int(input("Enter something >>"))
if value > 0:
break
else:
continue
except EOFError:
value = 1
except ValueError:
continue

How do I get back to the top of a while loop?

so I am trying to make a guessing game on my own and when the game ends I hope it will prompt the player if he wants to play again by typing yes or no like this:
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) y
Guess a number between 1 to 10: 7
YOU WON!!!!
Do you want to continue playing? (y/n) n
Thank you for playing!
I managed to get the game working but I can't play the game again. I am stuck here:
guess = int(input("Guess a number between 1 and 10: "))
while True:
if guess > num:
print("Too high, try again!")
guess = int(input("Guess a number between 1 and 10: "))
elif guess < num:
print("Too low, try again!")
guess = int(input("Guess a number between 1 and 10: "))
else:
print("You guessed it! You won!")
replay = input("Do you want to continue playing? (y/n) ")
if replay == "y":
**what to insert here???**
else:
break
I don't know what to type inside the if statement that will return my code to the top of the loop if the user press "y" and allows me to restart the game.
Any help will be appreciated! Please do not give me the entire solution but try to give me hints so I can solve this by myself! Thank you!
you can use the continue statement as it returns the control to the beginning of the while loop, in python.
You have to use two while loops. The first one to decide whether the player wants to play again or not and the second one is to get guess from the user until the user does the correct guess.
while True:
guess = int(input("Guess a number between 1 and 10: "))
wantToPlay = False
while True:
if guess > num:
print("Too high, try again!")
guess = int(input("Guess a number between 1 and 10: "))
elif guess < num:
print("Too low, try again!")
guess = int(input("Guess a number between 1 and 10: "))
else:
print("You guessed it! You won!")
replay = input("Do you want to continue playing? (y/n) ")
if replay == "y":
wantToPlay = True
else:
break
if wantToPlay == False:
break

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 add exception handling in my Python 3 code?

I am writing this code for class I have and I need some help adding exception handling. Basically what I need help with is fitting the exception handling around my user inputs so if the user inputs anything other than what is specified it'll loop back and ask the user to input the correct answer. I also need to have an exception handling with one of my functions. This is my code so far.
symbol_list = ['AAPL', 'AXP', 'BA', 'CAT', 'CVX', 'DIS', 'GS', 'HD', 'IBM', 'INTC']
price_list = [150.75, 98.65, 340.53, 129.77, 111.77, 111.42, 175.37, 177.89, 119.83, 47.74]
invest_dict = {'AAPL': 150.75, 'AXP': 98.65, 'BA':340.53, 'CAT' :129.77, 'CVX' :117.77, 'DIS' :111.42, 'GS':175.37, 'HD':177.89, 'IBM': 119.83, 'INTC':47.74}
print("...............................Lab 8.........................")
def Greeting():
print("The purpose of this project is to provide Stock Analysis.")
def Conversions(investment_amount):
investment_amount = float(investment_amount)
Euro = float(round(investment_amount / 1.113195,2) )
Pound = float(round(investment_amount / 1.262304,2) )
Rupee = float(round(investment_amount / 0.014316,2) )
print("The amount you invest in euro is: {:.2f}" .format(Euro) )
print("The amount you invest in pounds is: {:.2f}" .format(Pound) )
print("The amount you invested in Rupees is: {:.2f}" .format(Rupee) )
def minimum_stock():
key_min = min(invest_dict.keys(), key = (lambda k: invest_dict[k]))
print("The lowest stock you can buy is: ",invest_dict[key_min])
def maximum_stock():
key_max = max(invest_dict.keys(), key = (lambda k: invest_dict[k]))
print("The highest stock you may purchase is: ",invest_dict[key_max])
def invest_range(investment_amount):
new_list = []
new_list = [i for i in price_list if i>=50 and i <=200]
return(sorted(new_list))
answer = 'yes'
while answer:
print(Greeting())
investment_amount = float(input("Please enter the amount you want to invest:$ "))
if investment_amount!='':
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
print(Conversions(investment_amount))
for i in invest_dict:
i = investment_amount
if i <25:
print("Not enough funds to purchase stock")
break
elif i>25 and i <=250:
print(minimum_stock())
break
elif i >= 250 and i <= 1000:
print(maximum_stock())
break
print("This is the range of stocks you may purchase: ", invest_range(investment_amount))
answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
print("Thank you for investing.")
break
The archetypical way of doing this is something along the lines of
while True:
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
break
except ValueError:
print("Please enter a dollar amount (a floating-point number)")
print("Thank you for investing: ${:,.2f}".format(investment_amount))
Alternatively, if you're willing to import stuff, the click module has a method to do something like this:
investment_amount = click.prompt('Please enter the amount you want to invest: $', type=float)
which will keep asking the user until the input is of the correct type. For your later prompt, asking for yes/no, click.confirm() can do that for you as well.
You can try this error handling where input is taken:
while answer:
print(Greeting())
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
except:
print("Please enter a valid amount...")
continue
print(Conversions(investment_amount))
Hope this will help.

Closing program with while loop

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")

Resources