Loop statement with two variables - python

I need to do a program where it will ask first name and then last name. the code should detect if the input is in lowercase letters, if not it will repeat to ask first name and last name.
here is what i did but it does not detect if the input is in lowercase
firstName = input(“Enter your First Name: “)
lastName = input(“Enter your Last Name: “)
fn = (firstName.islower())
ln = (lastName.islower())
while firstName != fn and lastName != lastName != ln:
print (“Your First and Last name should be typed in lowercase letter”)
firstName = input(“Enter your First Name: “)
lastName = input(“Enter your Last Name: “)
print (“yey!”)

Aside from some the silly logical error in the loop condition, your code is good. Here's a corrected version:
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
while not firstName.islower() or not lastName.islower():
print("Your first and last name should be typed in lowercase letters")
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
print ("yey!")

In this code we check if both first and last name are in lowercase if not the user need to try again.
I hope is what you intend to.
first_name = ""
last_name = ""
while True:
# Receive the first name and the last name from the user
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
# check if the first name and the last name are in lower case if yes it exit otherwise print try again
if first_name.islower() and last_name.islower():
break
print("Your first name and last name need to be in lowercase please try again")
print("yay!")
Actually in your first try you was really close to it.
I have made those changes:
No need to do input out of the loop. is just duplicate the code, and make the input in one place make it easier :) .
Need to check if the string is a lowercase inside the loop. and check it for every input you receive until you find a good one.

Related

While != "specific string" loop mishap

I'm trying to make a task a little more efficient. I'm going to continue to research/edit while moving forward.
What the code currently does is ask for your first/last name it then outputs a username & password. Up to this point it works fine if there is a more efficient way to rewrite this also appreciated.
The only thing I still need to fix is looping entries(First_name and Last_name) so I can have multiple users added with a \n\n for easy reading/separation of each user. preferably with a exit command such such as "done"
I'm also going to be looking into how to create a new file that this information is stored in but this is the section I'm going to try to figure out.
First_name = input("Enter your First name: ")
Last_name= input("Enter your last name: ")
Username = str(First_name) + str(Last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
In terms of trying to solve the issue.
I did try to create something in the ball park of..
First_name = input("Enter your First name: ")
Last_name= input("Enter your last name: ")
while First_name != "done":
Last_name= input("Enter your last name: ")
First_name = input("Enter your First name: ")
Last_name= input("Enter your last name: ")
Username = str(First_name) + str(Last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
this just repeated the first two lines without printing the Username/password. It also appeared to acknowledge when I typed done but slightly off from desired. Below I included how the code ran
Enter your First name: first
Enter your last name: last
Enter your last name: last
Enter your First name: done
Enter your last name: last
Username: DONELAST
Password: donelast1!
I get why its first, last, last, first last. I dont get how to make the while loop using "while Fist_name !='done': " without putting lines 1 and 2 before the loop. I tried removing the inputs at line 5 and 6 but then it just looped the username and password.
You can use a while loop and break it when the first name is done.
while True:
first_name = input("Enter your first name (done to exit): ")
if first_name.lower() == "done":
print("Done!")
break
last_name = input("Enter your last name: ")
Username = str(first_name) + str(last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)
print("\n")
Output:
Enter your first name (done to exit): John
Enter your last name: Doe
Username: JOHNDOE
Password: JohnDoe1!
Enter your first name (done to exit): Alice
Enter your last name: Court
Username: ALICECOURT
Password: AliceCourt1!
Enter your first name (done to exit): done
Done!
Just set your variables to an empty string before the loop starts. Since an empty string is not equal to done your code will enter the loop and prompt the user:
First_Name = ''
Last_Name = ''
while First_name != "done":
Last_name= input("Enter your last name: ")
First_name = input("Enter your First name: ")
Username = str(First_name) + str(Last_name)
Password = Username + str('1!')
print("Username: ", Username.upper())
print("Password: ", Password)

Error catching integers in a string

strFName = ""
while strFName != strFName.isalpha():
if strFName != strFName.isalpha():
strFName = input("What is your first name? ")
else:
print("Your name cannot contain numbers")
break
I want the user to enter their name, but if they enter any letters the program will throw up an error. So far I am trying to do this with a try and except but whenever I enter a number it just goes straight on to the next part of the program.
You mean the first name cannot contain digits?
If so, you can do something like this:
import string
has_digits = lambda x: any([i.isdigit() for i in x])
first_name = "0"
while has_digits(first_name):
first_name = input("Enter first name (cannot contain digits): ")
print('Your name is {}'.format(first_name))

How to add a space in between the output when reversing the string on python?

This is what I have to do:
Write a Python program which accept the user's first and last name and print them in reverse order with a space between them. THE LETTERS OF THE FIRST AND LAST NAMES SHOULD ALSO BE IN REVERSE ORDER!!!!! For example if a person enters first name is Sam and last name is Murrow then the output should be maS worruM...
-
I can't figure out how to add the space in between firstname & lastname. This is what I have so far:
firstname = input("What is your last name?:")
lastname = input("What's your last?: ")
print (lastname) + (firstname)[::-1]
In your solution you are only reversing the firstname string. What you can do instead is build your full string including both firstname, lastname and a space between them, and then reverse the entire string.
For example:
firstname = input("What is your last name?:")
lastname = input("What is your last?")
print(firstname[::-1] + " " + lastname[::-1])
Try this:
firstname = input("What is your first name?:")
lastname = input("What's your last name?: ")
fn = firstname[::-1]
ln = lastname[::-1]
print (fn,"",ln)
Do this:
first_name = input("Enter your First Name: ")
last_name = input("Enter your Last Name: ")
print(f"{first_name[::-1].strip()} {last_name[::-1].strip()}")
This code will prompt the user to input their First and Last names separately and then store those values in first_name and last_name variables respectively so that they can be used in the print statement (or for other purposes). Also it will remove extra space from input while it will print output
Here's a different approach to solve this problem
print("Enter the name: ")
name = str(input()).split(' ')
namez = name.reverse()
for i in range(len(name)):
print(name[i][::-1], end=" ")
print("{last} {first}".format(last=lastname[::-1], first=firstname[::-1]))
first_name = input("Input your First Name : ")
last_name = input("Input your Last Name : ")
print ("Hello " + last_name + " " + first_name)

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

Python 2.7.5, list basics, displaying list input properly

Just started venturing into arrays using python 2.7.5. My objective is to ask the user for input and store the input in multiple arrays.
So far this is what I have, as far as storing multiple arrays with input. I run into an error when trying to print the input at the end.
Here is the code I have so far.
# want user to enter a list of employee names, error occurs when trying to recall user entry
emp_name = [0]
emp_name = raw_input("please enter employee name")
while emp_name !="neg":
emp_name = raw_input("please enter employee name,enter neg to exit")
print "employee 2 is:", emp_name[1] #I want the 2nd name entered to appear
Then you are going to want to:
Change the names of your variables so that you don't have the list be the same name as the input.
Append each name you get to the list.
This should be what you want:
employees = []
name = raw_input("Please enter an employee name: ")
while name != "neg":
# Append the previous name.
employees.append(name)
# Get a new name.
name = raw_input("Please enter an employee name or 'neg' to exit: ")
# You need a try/except here in case there is no second employee.
# This can happen if the user types in "neg" to begin with or only 1 name.
try:
print "Employee 2 is: ", employees[1]
except IndexError:
print None
Also, I slightly changed your input prompts to make them cleaner and more user-friendly.
Below is a sample of the script in action:
Please enter an employee name: Bob
Please enter an employee name or 'neg' to exit: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: Joe
And here is one without a second employee:
Please enter an employee name: Joe
Please enter an employee name or 'neg' to exit: neg
Employee 2 is: None
Your first line declares emp_name as an array.
Your second line raw_input("please enter employee name") re-assigns it as a string.
So when you tell it to print emp_name[1], it has no idea what emp_name[1] is because it sees a string at that point.
If you write, instead:
emp_name[0] = raw_input("please enter employee name")
That means you're assigning that employee name to element 0 of array emp_name.
Then you want to add index entries inside the while, rather than re-assigning them (you see, it doesn't automatically accumulate entries, you have to tell it to).
Happy Coding!
You can add to a list with list.append(), but you need to capture user input into a separate variable:
employees = []
emp_name = raw_input("Please enter employee name, enter neg to exit")
while emp_name != "neg":
emp_name = raw_input("Please enter employee name, enter neg to exit")
employees.append(emp_name)
print "employee 2 is:", employees[1]
Apart from using separate variables for the list of names and for the name the user has just entered, I also started the list entirely empty.
You can avoid using two raw_input() calls by changing the while loop to an infinite loop and instead break out of the loop when 'neg' has been entered:
employees = []
while True:
emp_name = raw_input("Please enter employee name, enter neg to exit")
if emp_name == 'neg':
break
employees.append(emp_name)
You may also need to test if there are enough employees entered before you print the second employee:
if len(employees) > 1:
print "Employee 2 is:", employees[1]
else:
print "You didn't enter enough employees!"

Categories