Python Repeated Actions - python

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

Related

Creating a function where I can input first names and last names into a dictionary

I am kind of stuck, I am trying to make a function that allows me to append onto an empty dict, I want to add first name and surname, and also make it possible to have people with same last names but different first names. Any ideas? This is my first time asking a question on here, let me know if I need to find any other info thanks!
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
people[key] = input('Please enter your {}: '.format(value))
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
people()
First ask the user the input('Please enter your {}: '.format(value))
store it in a variable and then assign the people[key] to the variable
Example:
def people():
people = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people[key] = name
print(people)
prompt = input("Another person? (Y/N): ")
print(people)
return people
As mentioned in the comments that the people dicts gets reset
So with the approach of nested dicts you can use this:
def people():
people_ = {}
prompt = input("Would you like to add a person to the list? (Y/N): ")
while prompt.lower() == "y":
qs = dict(name='first name', surname='last name')
print(qs)
index = f"person_{len(people_) + 1}"
people_[index] = {}
for key, value in qs.items():
name = input('Please enter your {}: '.format(value))
people_[index][key] = name
print(people_)
prompt = input("Another person? (Y/N): ")
print(people_)
return people_
def people():
people = {}
add_person_msg = "Add person to list? (Y/N): "
first_name_msg = "First name: "
last_name_msg = "Last name: "
while input(add_person_msg).lower() == 'y': #.lower()
people[input(first_name_msg)] = input(last_name_msg)
return people
print(people())
if you wanted to work with the names before storing in dictionary, for example capitalize them:
def people_dict():
fn_msg = "First name: "
ln_msg = "Last name: "
people = {}
while input("Add person? y/n: ").lower() == 'y':
fn, ln = input(fn_msg).title(), input(ln_msg).title()
people[fn] = ln
return people
Also instead of using .format() method,
input('Please enter your {}: '.format(value)
if you are using Python 3.5 and above you can use f-strings:
input(f'Please enter your {value}:')

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)

Passing a dictionary to a new function in python?

If I create a dictionary that I need to access in multiple functions what would be the best way to pass it?
What I currently am doing keeps reseting the dictionary to empty. If I print in the addDictionary() I get the result I want. However, when I go to look up a element using the key in lookUpEntry(), I can't find it. When I print I get an empty dictionary. I also have to eventually pickle and unpickle so if anyone has any feedback on that, that would also help.
import pickle
def dictionary():
addressBook = {}
return addressBook
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 addDictionary():
addressBook = dictionary()
personLastName, personFirstName, personEmail, personStreetAddress, personCityState, personPhone = addPerson()
addressBook[personLastName] = personFirstName, personEmail, personStreetAddress, personCityState, personPhone
print(personFirstName,personLastName, "has been added to the address book!")
print(addressBook)
return addressBook
def lookUpEntry():
addressBook = dictionary()
keyName = input("Enter the last name of the person you are trying to find.")
while not keyName in addressBook:
keyName = input("That name is not in the address book. Please try again.").lower()
x = input("Enter '1' if you want to look up a email. Enter '2' if you want to look "
"up a persons address. Enter '3' to look up a persons phone number: ")
if x == "1":
print("The email of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[1]])
elif x == "2":
print("The address of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[2]], addressBook[keyName[3]])
elif x == "3":
print("The phone number of", addressBook[keyName[0]], keyName, "is:", addressBook[keyName[4]])
else:
print("Sorry that item is not stored in this address book.")
def main():
addDictionary()
lookUpEntry()
main()
Currently you define dictionary as
def dictionary():
addressBook = {}
return addressBook
Here you create a new dictionary every time it is called. Try replacing this with
# a global dictionary
_addressBook = {}
def dictionary():
return _addressBook

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

How would I disallow numbers as input?

Alright, so I defined a function where the user can input his/her name. I want to make it so that the user is not allowed to input a number like "69" for his/her name. How would I go about doing this? Here is the code I used:
def name():
while True:
name = input("What is your name? "))
try:
return str(name)
break
except TypeError:
print("Make sure to enter your actual name.")
You can use isalpha() to check name:
Return true if all characters in the string are alphabetic and there
is at least one character, false otherwise.
>>> "69".isalpha()
False
>>> "test".isalpha()
True
Here's your code with modifications:
while True:
name = input("What is your name? ")
if name.isalpha():
break
else:
print("Make sure to enter your actual name.")
continue
Or:
name = input("What is your name? ")
while not name.isalpha():
print("Make sure to enter your actual name.")
name = input("What is your name? ")
You can use str.isdigit() method to check if the string contains just digits:
name = input("What is your name? ")
while name.isdigit():
print("Make sure to enter your actual name.")
name = input("What is your name? ")
Note that this will allow names like - "Rohit1234". If you just want to allow alphabetic characters, then you can use str.isalpha() method instead.
Invert your logic:
while True:
name = ...
try:
int(name)
print "Name can't be a number."
except TypeError:
return str(name)
Mind you, this will accept any input that is not a valid integer, including 123abc or so.

Categories