For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)
Related
I have a school assignment for Python in which I have a backpack of items and need to make code to ask the user if they want to: a) add an item to the backpack, b) check the items in the backpack, and c) quit the program.
For my code, I want to make it so that if the user at input for adding a new item just hits return and leaves the input blank, it will re-prompt to the input again rather than continuing the code if no item is actually added. Here's what I have so far:
import sys
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if (userChoice == "1"):
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
else:
itemsInBackpack.insert(0, itemAddNew)
print("Added to backpack.")
With my code here, even if I hit return in a test and leave the input blank, the code still continues onward and doesn't break to re-prompt input again. Is it because I'm using an if statement inside of an if statement already? I'm sure in general there's a better way to do this, but as a beginner I'm stumped and could use a shove in the right direction.
The break stops everything in your loop and causes your program to end.
If you want to prompt for input until the user gives you something, change this:
print("What item do you want to add to the backpack?")
itemAddNew = input()
if itemAddNew == "":
break
to this:
print("What item do you want to add to the backpack?")
itemAddNew = input()
while itemAddNew == "":
#Added some output text to tell the user what went wrong.
itemAddNew = input("You didn't enter anything. Try again.\n")
This will keep going WHILE the text is empty.
I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==NamesArray[position]):
print("Name is: " +position)
break
if position>5:
print("The account number not found!")
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
When the user enters "P" it is supposed to call to def PopulateAccounts() and it does, but the problem is that it doesn't stop and the user keeps having to input account name, account number, and account balance. It is supposed to stop after the 5th name. How do I fix this?
It's because after PopulateAccounts() finishes while loop keeps iterating because choice is still P. If you want to ask user for another action simply ask him again for input.
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
choice = input("Please enter another action: ")
Also I'd recommend you use infinite loop to keep asking user for inputs, and break out of it when user enters 'E', this way you could also track invalid inputs.
while True:
choice = input("Please enter your choice: ")
if choice == "P":
PopulateAccounts()
elif choice == "S":
SearchAccounts()
elif choice == "E":
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid action \"{}\", avaliable actions P, S, E".format(choice))
print()
Your code asks for the user's choice only once -- before the loop begins. Because it never changes, that loop will stick with the user's choice for an infinite number of iterations.
choice = input("Please enter your choice: ")
while (choice=="E") or (choice=="P") or (choice=="S"):
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
# here at the end of this loop, you should
# get the user to enter another choice for the next
# iteration.
Your while loop has no counter to make it stop at the 5th name, and position only exists during the execution of the function that it is in. Also, position will never be greater than 4. range(5) starts at 0 and ends at 4.
Your for loop is fine. The problem is that your while loop is repeating. So after PopulateAccounts() is called, it correctly finishes after running through the for loop 5 times, but since choice is still equal to "P" (this hasn't been changed after the user first enters it), you still remain in the while loop, which means PopulateAccounts() will be called again and again. You can verify this by sticking an additional statement like "print("Hey, we're at the top of the While loop!")" after the "while" line.
Try rewriting your while loop with an explicit break if the user selects "E":
while True:
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
quit()
choice = input("Please enter either P, S or E: ")
Note that this extra input at the bottom also conveniently appears if the user typed something else besides "P", "S", or "E". You may also want to consider adding .upper() to the choice checks to make it case insensitive.
Running on Python, this is an example of my code:
import random
comp = random.choice([1,2,3])
while True:
user = input("Please enter 1, 2, or 3: ")
if user == comp
print("Tie game!")
elif (user == "1") and (comp == "2")
print("You lose!")
break
else:
print("Your choice is not valid.")
So this part works. However, how do I exit out of this loop because after entering a correct input it keeps asking "Please input 1,2,3".
I also want to ask if the player wants to play again:
Psuedocode:
play_again = input("If you'd like to play again, please type 'yes'")
if play_again == "yes"
start loop again
else:
exit program
Is this related to a nested loop somehow?
Points for your code:
Code you have pasted don't have ':' after if,elif and else.
Whatever you want can be achived using Control Flow Statements like continue and break. Please check here for more detail.
You need to remove break from "YOU LOSE" since you want to ask user whether he wants to play.
Code you have written will never hit "Tie Game" since you are comparing string with integer. User input which is saved in variable will be string and comp which is output of random will be integer. You have convert user input to integer as int(user).
Checking user input is valid or not can be simply check using in operator.
Code:
import random
while True:
comp = random.choice([1,2,3])
user = raw_input("Please enter 1, 2, or 3: ")
if int(user) in [1,2,3]:
if int(user) == comp:
print("Tie game!")
else:
print("You lose!")
else:
print("Your choice is not valid.")
play_again = raw_input("If you'd like to play again, please type 'yes'")
if play_again == "yes":
continue
else:
break
If the user gets to the end of the program I want them to be prompted with a question asking if they wants to try again. If they answer yes I want to rerun the program.
import random
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
total = 0
final_coin = random.randint(1, 99)
print("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
total = total + user_input
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
while total != final_coin:
user_input = int(input("Enter next coin: "))
total = total + user_input
if total > final_coin:
print("Sorry - total amount exceeds", (final_coin))
if total < final_coin:
print("Sorry - you only entered",(total))
if total== final_coin:
print("correct")
You can enclose your entire program in another while loop that asks the user if they want to try again.
while True:
# your entire program goes here
try_again = int(input("Press 1 to try again, 0 to exit. "))
if try_again == 0:
break # break out of the outer while loop
This is an incremental improvement on the accepted answer:
Used as is, any invalid input from the user (such as an empty str, or the letter "g" or some such) will cause an exception at the point where the int() function is called.
A simple solution to such a problem is to use a try/except- try to perform a task/ code and if it works- great, but otherwise (except here is like an else:) do this other thing.
Of the three approaches one might try, I think the first one below is the easiest and will not crash your program.
Option 1: Just use the string value entered with one option to go again
while True:
# your entire program goes here
try_again = input("Press 1 to try again, any other key to exit. ")
if try_again != "1":
break # break out of the outer while loop
Option 2: if using int(), safeguard against bad user input
while True:
# your entire program goes here
try_again = input("Press 1 to try again, 0 to exit. ")
try:
try_again = int(try_again) # non-numeric input from user could otherwise crash at this point
if try_again == 0:
break # break out of this while loop
except:
print("Non number entered")
Option 3: Loop until the user enters one of two valid options
while True:
# your entire program goes here
try_again = ""
# Loop until users opts to go again or quit
while (try_again != "1") or (try_again != "0"):
try_again = input("Press 1 to try again, 0 to exit. ")
if try_again in ["1", "0"]:
continue # a valid entry found
else:
print("Invalid input- Press 1 to try again, 0 to exit.")
# at this point, try_again must be "0" or "1"
if try_again == "0":
break
Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q. here what i have..
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = q
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = 'q'
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
print('Game Over')
print('Press Q to Quit')
if run == False:
choice = input('Press Q to Quit')
if choice == 'q'
import sys
exit(0)
Getting Q as input
Quit = int(input('Press Q to Quit')
You're asking for Q as the input, but only accepting an int. So take off the int part:
Quit = input('Press Q to Quit')
Now Quit will be whatever the user typed in, so let's check for "Q" instead of True:
if Quit == "Q":
Instead of sys.exit(0), you can probably just end your while look with break or just return if you're in a function.
Also, I don't recommend the name "Quit" for a variable that just stores user input, since it will end up confusing.
And remember that indentation is important in Python, so it needs to be:
if run == False:
choice = input('Press Q to Quit')
if choice == "Q":
# break or return or..
import sys
sys.exit(0)
That may just be a copy/paste error though.
Indentation and Syntax
I fixed the indentation and removed some extraneous code (since you duplicate the outer loop and some of the print statements) and got this:
print('How old do you thing Fred the Chicken is?')
number = 17
run = True
while run:
guess = int(input('Enter What You Think His Age Is....t'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
if run == False:
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q'
break
This gave me a syntax error:
blong#ubuntu:~$ python3 chicken.py
File "chicken.py", line 23
if choice == 'q'
^
SyntaxError: invalid syntax
So Python is saying there's something wrong after the if statement. If you look at the other if statements, you'll notice that this one is missing the : at the end, so change it to:
if choice == 'q':
So with that change the program runs, and seems to do what you want.
Some suggestions
Your instructions say "Press Q to Quit", but you actually only accept "q" to quit. You may want to accept both. Python has an operator called or, which takes two truth values (True or False) and returns True if either of them is True (it actually does more than this with values besides True and False, see the documentation if you're interested).
Examples:
>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
So we can ask for Q or q with if choice == "Q" or choice == "q":.
Another option is to convert the string to lower case and only check for q, using if choice.lower() == "q":. If choice was Q, it would first convert it to q (with the .lower()), then do the comparison.
Your number is always 17. Python has a function called random.randint() that will give you a random number, which might make the game more fun. For example, this would make the chicken's age between 5 and 20 (inclusive):
number = random.randint(5, 20)
There are many ways to exit certain things. For loops, it is using break, and for functions you can use return. However, for programs, if you wish to exit your program before interpretation finishes (end of the script) there are two different types of exit() functions. There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. However, sys.exit() is intended for programs not in IDLE (python interactive), while the built-in exit() and quit() functions are intended for use in IDLE.
You can use the break statement to break out of a while loop:
while True:
guess = int(input("...")
# ...rest of your game's logic...
# Allow breaking out of the loop
choice = input("Enter Q to quit, or press return to continue")
if choice.lower() == "q":
break
That means the interpreter exits the while loop, continues looking for more commands to run, but reaches the end of the file! Python will then exit automatically - there's no need to call sys.exit
(as an aside, you should rarely use sys.exit, it's really just used to set non-zero exit-status, not for controlling how your program works, like escaping from a while loop)
Finally, the main problem with the code you posted is indentation - you need to put the appropriate number of spaces at the start of each line - where you have something like:
if run == False:
choice = input('Press Q to Quit')
It must be like this:
if run == False:
choice = input('Press Q to Quit')
Same with anything like while, for, if and so on.