Trying to display initials in Python - python

I'm trying to make this so that when a person types their name just the initials display capitalized and separated by a period. I can't figure out what is wrong with this code I wrote... help pls!
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
print(name_list)
first = name[0][0]
second = name[1][0]
last = name[2][0]
print(first,'.', second,'.')
main()

If you are on Python 2.x you should exchange input for raw_input. Here's a quicker way to achieve what you're aiming for assuming you're on Python 2.x:
def main():
full_name = raw_input('Type your name and press ENTER. ')
initials = '.'.join(name[0].upper() for name in full_name.split())
print(initials)

def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
print(name_list)
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]
print(first.upper(),'.', second.upper(),'.', last.upper())
main()

Here's a version similar to the one you have.
Note that you were using name instead of name_list, and some hard-coded indexes.
def main():
name = input('Type your name and press ENTER. ')
name_list = name.split()
for part in name_list:
print(part[0].upper() + ". ", end="")
print()
main()
It loops over the list you created with split(), and prints the first letter (in upper case) of each part of the name.
The loop only makes sense if you want every part to be included of course.

I'll try to explain why it occurred rather than just giving you the solution.
You're using name instead of name_list when name_list is what you're intending to use.
name for 'Amanda Leigh Blount' = 'Amanda Leigh Blount'
but name_list = name.split() = ['Amanda', 'Leigh', 'Blount']
So you get a difference in the two only on the middle/last name.
The first name is equivalent for both:
name[0][0] == name_list[0][0]
The left side matches the first letter of the first letter:
'Amanda Leigh Blount'[0][0] = 'A'[0] = 'A'
The right side matches the first letter of the first word.
['Amanda', 'Leigh', 'Blount'][0][0] = 'Amanda'[0] = 'A'
But for the second:
name[1][0] != name_list[1][0]
because the first & second are:
'Amanda Leigh Blount'[1][0] = 'm'[0] = 'm'
['Amanda', 'Leigh', 'Blount'][0][0] = 'Leigh'[0] = 'L'
So just use name_list instead of name:
first = name_list[0][0]
second = name_list[1][0]
last = name_list[2][0]

Related

Search Array In Python, Return Position

This Is Quite Simple but I cant get the hang of it. I'm writing a short program where you enter the name, it will compare to each item in the array, then if it is found print what number it is in the array. if it isnt found, then enter a new name
Names = ['alice', 'bob', 'carol', 'david']
name = input("Enter Name ").lower()
c = 0
while name != Names[c]:
c = c + 1
if c == (len(Names)):
name = input("Name Not Found \n \nEnter Name ").lower()
c = 0
if name == Names[c]:
print ("name found, in position ", c)
It Always Comes Up With Name Not Found
name.lower without the () at the end will return the whole lower function and it will mess with the variable
So just replace that with name.lower() and it should work
Alternatively, you could use Name.index(name) and create a recursive function to search for names, like so:
Names = ['alice', 'bob', 'carol', 'david']
def findName():
name = input("Enter Name: ").lower()
if name in Names:
print(f'Name at position {Names.index(name)}')
else:
print('Name not found; try again')
findName()
findName()
Or the same code but in a loop:
while True:
name = input("Enter Name: ").lower()
if name in Names:
print(f'Name at position {Names.index(name)}')
break
else:
print('Name not found; try again')
Use name = input("Enter Name ").lower() instead of name = input("Enter Name ").lower.
name = input("Enter Name ").lower would assign name to the function lower, while name = input("Enter Name ").lower() runs the function lower and assigns name its return value

Is there a way I could pair up the contents of an array that can delete itself later? (Secret Santa Program)

I'm trying to make a Secret Santa program. Ideally the program should ask for at least three names, and afterwards the program asks if there are more names. If yes, open up another text field and add it to the list of names. If no, break the loop, create a separate list with the names inside it, shuffle the second list of names, and pair them up with a name from the original list.
For example, if John, Elliot, Sarah and Jenny put in their names and the program shuffled their names, it should output something like this:
[('John', 'Sarah'), ('Elliot', 'John'), ('Sarah', 'Jenny'), ('Jenny', 'Elliot')]
But instead I get something like:
[('John', 'John'), ('Elliot', 'John'), ('Sarah', 'Elliot'), ('Jenny', 'Jenny')]
Here's the code:
import sys
import random
names = []
class Santa:
#The class that takes the values, shuffles them, pairs and then displays them
def __init__(self, name):
self.turns = name
self.people = names
self.final = []
def sort_names(self):
random.shuffle(self.people)
for name in self.turns:
pair = (name, random.choice(self.people))
if pair[0] == [1]:
pair = (name, random.choice(self.people))
else:
self.final.append(pair)
def print_name(self):
input("\nNames are ready! Press Enter to show the names.")
print(self.final)
def main():
# The function asking for user input
name = input("\nType in your name. ")
names.append(name)
name = input("\nType in the next name. ")
names.append(name)
name = input("\nType in the next name. ")
names.append(name)
while True:
next = input("\nIs this everyone? Y/N ")
if next.upper() == "Y":
break
elif next.upper() == "N":
name = input("\nType in the next name. ")
names.insert(0, name)
else:
print("\nInvalid response, please try again.")
print(names)
start = Santa(names)
start.sort_names()
start.print_name()
input("\nRecord these, and press enter to quit.")
sys.exit()
main()
You shouldn't need an entire class to set this up, and I have tried to clean up a little of reading input.
import random
names = []
for _ in range(3):
name = input("\nType in your name. ")
names.append(name)
while True:
next = input("\nIs this everyone? Y/N ")
if next.upper() == "Y":
break
elif next.upper() == "N":
name = input("\nType in the next name. ")
names.insert(0, name)
else:
print("\nInvalid response, please try again.")
print(names)
random.shuffle(names)
pairs = [(first_person, second_person) for first_person, second_person in zip(names, names[1:] + [names[0]])]
print(pairs)
Your problem is the comparison so you do not draw yourself:
for name in self.turns:
pair = (name, random.choice(self.people))
# you compare against [1] ? That is a list containing a 1 as only thing
# and it will never be True unless if you compare string vs. name
if pair[0] == [1]:
pair = (name, random.choice(self.people))
else:
self.final.append(pair)
You can streamline your loop and you have to handle odd/even number of names when pairing people up. Using list slicing and zipping makes it easier to pair up people.
Example:
import sys
import random
class Santa:
def __init__(self, names):
self.people = names
def shuffle(self):
random.shuffle(self.people)
self.final = []
if len(self.people) < 2:
print("Sorry, not enough people to gift stuff around")
return
# taken from the comment, because superior to what I had originally
# see edit history for my solution ;o) - this one suggested by #Matthias
self.final = [(n1, n2) for n1, n2 in zip(names, names[1:] + [names[0]])]
def print_name(self):
print(self.final)
name = "dummy"
names = []
while name:
name = input(f"Whats the {len(names)+1}. name? (Empty to end) ").strip()
if not name:
break
names.append(name)
print(names)
santa = Santa(names)
santa.shuffle()
santa.print_name()
Output (omitted input outputs):
# odd inputs
['Tim', 'John', 'Luise', 'Maria', 'Wasja']
[('Wasja', 'Maria'), ('Maria', 'John'), ('Luise', 'Tim')]
['Tim', 'John', 'Luise', 'Maria', 'Wasja']
[('Maria', 'Wasja'), ('Wasja', 'Tim'), ('John', 'Luise')]
# even inputs
['Tim', 'John', 'Luise', 'Maria']
[('John', 'Tim'), ('Maria', 'Luise')]
['Tim', 'John', 'Luise', 'Maria']
[('Luise', 'Tim'), ('John', 'Maria')]
You can read more about zip and list slicing here:
Zip lists in Python
Understanding slice notation

Adding in "else" makes my for loop not work

I am new to coding and have a list of lists that I need to search.
I want to see what lists contained in the larger list have the variable full_choice as the 3rd item in the sequence.
All lists that contain third_choice i need to print to a txt file.
the code below works and adds exactly what I need it to to the file, however I need the function to start again if there is no match for the variable full_choice.
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I have tried inserting an else: at the end of the code however while that has ends up creating the file it doesn't write anything to it.
Tried to fix your indentation. I'm guessing you wanted something like this:
def display_instructor_txt():
file_name = input('type in the name of the file you want to create do not include .txt')
file_name_full = file_name + '.txt'
new_file = open(file_name_full,'w')
first_choice = input('type in the first name of the instructor you want to filter by ')
last_choice = input('type in the last name of the instructor you want to filter by ')
full_choice = first_choice[0].upper() + first_choice[1:].lower() + last_choice[0].upper() + last_choice[1:].lower()
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()
I just moved the else block forward to align with the if block you had a few lines before.
As #Haken Lid suspected, please fix indentation:
for course in all_courses_list:
if course[2].replace(" ","").replace(",","") == full_choice:
course_st = ''.join(course)
new_file.write(course_st.replace('[','').replace(']','').
replace("'",'').replace('\\n','').replace(" ", ", "))
else:
print('please try again')
display_instructor_txt()

Adding items to a list until keypress

I have got it to work, except the list doesn't save the inputs properly; it just lists them as three periods. This is the code:
names = []
i=0
while 1:
i+=1
name=input("Please enter the name")
if name==" ":
break
names.append(names)
print(names)
Change names.append(names) to names.append(name), since you want to append name to the list names (just a typo I guess).
Also if name == " " must be changed to if name == "", since if the user presses enter without providing any name, the input is an empty string, not a white space.
Correct code here:
names = []
i = 0
while True:
i += 1
name = input("Please enter the name ")
if name == "":
break
names.append(name)
print(names)

How to write in new line in a file?

I need to create a program that saves people's information e.g. their name in a text file depending on the first letter of their surname so if their surname starts with a K it goes into MyFile1.
I need it to loop like I have done because it's an unknown number of people however I want each person to be written in a different line in the text file is there a way to do this.
The code at the bottom puts each separate information into a new line and I don't want that I want each different person to be in a new line.
MyFile1 = open("AL.txt", "wt")
MyFile2 = open("MZ.txt", "wt")
myListAL = ([])
myListMZ = ([])
while 1:
SurName = input("Enter your surname name.")
if SurName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
Title = input("Enter your title.")
myListAL.append(Title);
FirstName = input("Enter your first name.")
myListAL.append(FirstName);
myListAL.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListAL.append(Birthday);
Email = input("Enter your email.")
myListAL.append(Email);
PhoneNumber = input("Enter your phone number.")
myListAL.append(PhoneNumber);
for item in myListAL:
MyFile1.write(item+"\n")
elif SurName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
Title = input("Enter your title.")
myListMZ.insert(Title);
FirstName = input("Enter your first name.")
myListMZ.append(FirstName);
myListMZ.append(SurName);
Birthday = input("Enter birthdate in mm/dd/yyyy format:")
myListMZ.append(Birthday);
Email = input("Enter your email.")
myListMZ.append(Email);
PhoneNumber = input("Enter your phone number.")
myListMZ.append(PhoneNumber);
line.write("\n")
for item in myListMZ:
MyFile2.write(line)
elif SurName == "1":
break
MyFile1.close()
MyFile2.close()
You are looking for join.
When you have a list of items you can join them in a single string with.
l = ['a', 'b', 'c']
print(''.join(l))
produces
abc
You can not only use the empty string but also another string which will be used as separator
l = ['a', 'b', 'c']
print(', '.join(l))
which now produces
a, b, c
In your examples (for example the first write)
MyFile1.write(','.join(MyListAL) + '\n')
If you happen to have something in the list which is not a string:
MyFile1.write(','.join(str(x) for x in MyListAL) + '\n')
(you can also use map, but a generator expression suffices)
Edit: adding the map:
MyFile1.write(','.join(map(str, MyListAL)) + '\n')
In your case I would rather use a list of dictionaries, where a person with all its infos is a dictionary. Then you can convert it to a JSON string, which is a standard format for representing data. (Otherwise you need to define your own format, with delimiters between the items.)
So something like this:
import json # at the top of your script
# I would create a function to get the information from a person:
def get_person_input():
person = {}
person["surname"] = input("Surname: ")
person["title"] = input("Title: ")
person["email"] = input("Email: ")
# TODO: do whatever you still want
return person
# Later in the script when you want to write it to a file:
new_line = json.dumps( person )
myfile.write( new_line + "\n" )
Parsing a json is also very easy after all:
person = json.loads(current_line) # you can handle exception if you want to make sure, that it is a JSON format
You can use in your code for the decision in which array it should be written something like this:
SurName = input("Enter your surname name.")
if SurName[0] <= 'L':
...
else:
...
This will make your script more clear and robust.

Categories

Resources