Continue or quit - python

I am teaching myself Python. For practice I made a little mad lib game for my daughter. The problem, I want to add a "to continue press enter or type quit to exit" after line 3. I know I'm obviously doing it wrong, but I've tried conditional, flags and breaks with no luck.
#Prompt
greeting = input("Hello what is your name? ")
greeting += input(f" OK {greeting} lets wright a story together. Lets get started" )
#listing of directions
while True:
q_1 =input("please type a plural noun : ")
q_2 = input("please type an adjective: ")
q_3 =input ("please type plural noun, animal: ")
q_4 =input("Please enter an plural noun: ")
q_5 = input("Please enter an adjective: ")
q_6 = input("Please enter a color: ")
q_7 = input("Please enter an adjective: ")
q_8 = input("Please enter noun: ")
q_9 = input("Please enter plural noun: ")
q_10 =input("Please enter an adjective ")
q_11 = input("Please enter a verb: ")
q_12 = input("Please enter plural noun ")
q_13 = input("Please enter a verb-ed: ")
q_14 = input("Please enter a verb: ")
q_15 = input("Please enter noun: ")
q_16 = input("Please enter a adjective: ")
break
print("Ok here's your story")
# output with data from input
story = f"""
Unicorns aren't like other {q_1}; they're {q_2}. They look like
{q_3}, with {q_4} for feet and a {q_5} mane of hair. But Unicorns
are {q_6} and have a {q_7} {q_8} on their heads. Some {q_9} don't
believe Unicorns are {q_10} but I believe in them. I would love to
{q_11} a Unicorn faraway {q_12}. One thing I've always {q_13} about
is whether Unicorns {q_14} rainbows, or is their {q_15} {q_16}
like any other animals?
"""
print(story)

To answer your question, I've suggest something simple like this.
#Prompt
greeting = input("Hello what is your name?\n")
print(f"OK {greeting} lets wright a story together. Lets get started")
play = input('to continue press enter or type quit to exit\n')
if play == 'quit':
quit()
# Rest of your code stays the same
I'll mention also, because you said you are doing this for practice, that the way you are asking for inputs is a little bit rough.
In my example above I added a \n character. This will stop you needing to use all those spaces by putting the input response on a new line.

Related

Check for correct user input without exiting loop

I'm trying to write a travel itinerary program using base Python functionality. In step 1, the program should ask for primary customer (making the booking) details viz name and phone number. I've written code to also handle errors like non-alphabet name entry, errors in phone number input (ie phone number not numeric, not 10 digits etc) to keep asking for valid user input, as below, which seems to work fine:
while True:
cust_name = input("Please enter primary customer name: ")
if cust_name.isalpha():
break
else:
print("Please enter valid name")
continue
while True:
cust_phone = input("Please enter phone number: ")
if cust_phone.isnumeric() and len(cust_phone) == 10:
break
else:
print("Error! Please enter correct phone number")
continue
while True:
num_travellers = input("How many people are travelling? ")
if int(num_travellers) >= 2:
break
else:
print("Please enter at least two passengers")
continue
Output:
Please enter primary customer name: sm
Please enter phone number: 1010101010
How many people are travelling? 2
For the next step, the program should ask for details of all passenger ie name, age and phone numbers and store them. I want to implement similar checks as above but my code below simply exits the loop once the number of travellers (num_travellers, 2 in this case) condition is met, even if there are errors in input:
for i in range(int(num_travellers)):
travellers = []
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
else:
print("Please enter valid name")
continue
for j in range(int(num_travellers)):
travel_age = []
age = input("Please enter passenger age: ")
if age.isnumeric():
travel_age.append(age)
else:
print("Please enter valid age")
continue
Output:
Please enter passenger name: 23
Please enter valid name
Please enter passenger name: 34
Please enter valid name
Please enter passenger age: sm
Please enter valid age
Please enter passenger age: sk
Please enter valid age
Please enter passenger age: sk
I've tried using a while loop like mentioned in this thread but doesn't seem to work. Where am I going wrong? Thanks
You have missed while True: loop when asking for passenger data. Try something like below:
travellers = []
for i in range(int(num_travellers)):
while True:
travel_name = input("Please enter passenger name: ")
if travel_name.isalpha():
travellers.append(travel_name)
break
else:
print("Please enter valid name")
continue
BTW I moved travellers variable out of the loop, otherwise it is going to be cleared on every iteration.

append object instance to a list with a if statement and print it in another branch

I create a few class about pet, the following code was part of my main() function, First, ask the user to select one thing they want to do. that is if use input '1' they will add some pet instance. At the same time, I want to append part of the pet instance's information to a list. Then if the user chooses to read this information. I want to print it in another if statement branch. that is when the user input '2'. the problem occurs when I input 2 after already generating some pet instance. the list called l_weight always be void. How could I fix it? I already try to use the global list but is not work
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
return main()
elif a==2:
for i in l_weight:
print(i)
return main()
The reason l_weight() isn't appending is because in your code, you named the list l_weight and then in the rest of your code it's written as l_weigh
It should be:
def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1:
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
elif a==2:
for i in l_weight:
print(i)

Python Repeated Actions

I have a list that contains strings
animalList=['ASLAN', 'KAPLAN', 'KOPEK', 'KEDI']
descLion = ( 'it is called lion....')
descTiger = (' it is called tiger....')
I ask user to enter one of them and check for typos
questOne = input("Enter the name of the animal: ")
questOne = questOne.upper()
while questOne not in animalList:
questOne = input("Whatch out for typos Try again: ")
questOne = questOne.upper()
else:
print(questOne + ' IT IS')
What I couldn't figure out is that I want my code to keep ask for a name of the animal, check for typos and print the related description and repeat this action. I have tried something like that;
while questOne == animalList[0]:
print (descLion)
questOne = input("Enter the name of the animal: ")
questOne = questOne .upper()
while questOne == animalList[1]:
print (descTiger)
questOne = input("Enter the name of the animal: ")
questOne = questOne.upper()
This code kind of works only if the user inputs are in the order of the list. I would like user to be able to enter the input randomly.
You want to use "while True". Example:
while True:
name = input("Enter your name: ")
print("Hi, {}!".format(name))
print("What about now?")

While loop not repeating once information in entered

Making a program which has a list of the different star signs, then asks the user to enter what star sign they are and then for the program to check that is contained in the list before moving on.
The problem is that it does check that it is in the list, but it does not repeat.
play = True
while play:
print("Welcome to my Pseudo_Sammy program, please enter your name, star sign and then your question by typing it in and pressing the enter key, and I will give you the answer to your question")
name = input("What do they call you? ")
starsigns = ("leo", "virgo", "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces", "aries", "taurus", "gemini", "cancer")
starsign = str(input("What star do you come from? ")).lower()
while True:
try:
if starsign in starsigns:
break
else:
raise
except:
print("Please enter a valid star sign")
question = input("What bothers you dear? ")
if you want to repeat an input until you get a valid answer and THEN ask the next question, you need to place the 1st input inside while loop and the 2nd input outside the loop, like this:
starsigns = ("leo", "virgo", ...)
starsign = None
while starsign not in starsigns:
if starsign:
print("Please enter a valid star sign: {}.".format(", ".join(starsigns)))
starsign = input("What start do you come from? ").lower().strip()
question = input("What bothers you dear? ")

How to create a dictionary that I can access throughout the program?

I'm creating a address book program, and need to have a dictionary that I can add too, edit, and delete, as well as pickle. What would be the best way to create it so it is accessible by all the functions? I currently have the dictionary in the addon function but wouldn't it reset if I were to call the dictionary to another function?
My code so far (not including the menuModule)
def addPerson():
personLastName = input("Enter the last name of "
"the person you want to add: ").lower()
personFirstName = input("Please enter the first name of "
"the person you want to add: ")
localPart = input("Please enter the local part of the email address")
while not localPart.isalnum():
localPart = input("Please enter a valid input, a-z and numbers 0-9: ")
domain = input("Please enter the domain of the email addres: ")
while not domain.isalnum():
domain = input("Please enter a valid input, a-z and numbers 0-9: ")
topLevelDomain = input("Please enter the top level domain, examples: com, net, org: ")
while not topLevelDomain.isalnum() or len(topLevelDomain) > 3:
topLevelDomain = input("Please enter only letters, a-z and not more then 3 characters: ")
personEmail = localPart + "#" + domain + "." + topLevelDomain
personStreetAddress = input("Please enter house number and street of the person you want to add: ")
personCityState = input("Please enter the city, state abbreviation and zipcode of the person you want to add: ")
personPhone = input("Please enter the phone number of the person you want to add: ")
personPhoneStr = personPhone.strip("-")
while not personPhoneStr.isdigit() and not len(personPhoneStr) == 10:
personPhone = input("Error. That is not a valid phone number. Try again: ")
personPhoneStr = personPhone.strip("-")
return personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone
def appendDictionary():
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
listX = [personFirstName, personEmail, personStreetAddress, personCityState, personPhone]
addressBook = {personLastName: listX}
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
Try using lists. One list for each of the variables because if you try to store them as a tuple and then add them into a master list you will not be able to or it will be hard to charge them and edit them. Here is an example of storing the data:
nameList.extend(john)
emailList.extend(john#gmail.com.uk)
john_index = len(nameList)
Give each person an index to help you file their information so if our list looked like [jane#live.com, sam#wenston.com, john#gmail.com.uk] johns data is going to be the last in the list because we just entered it in position 3 on the list and the length function returns 3 so you know where johns data is stored and if you were to add more data it would stack up accourdingly.
here is an example of getting it back out of the list and editing it:
print nameList[john_index]
print emailList[john_index]
emailList[john_index] = new_value
I hope you understand :)

Categories