Grouping string input by count - python

I'm trying to do a question out of my book and it asks:
Implement function names that takes no input and repeatedly asks the
user to enter a student's first name. When the user enters a blank
string, the function should print for every name, the number of
students with that name.
Example usage:
Usage:
names()
Enter next name: Valerie
Enter next name: Bob
Enter next name: Valerie
Enter next name: John
Enter next name: Amelia
Enter next name: Bob
Enter next name:
There is 1 student named Amelia
There are 2 students named Bob
There is 1 student named John
There are 2 students named Valerie
So far I have this code:
def names():
names = []
namecount = {a:name.count(a) for a in names}
while input != (''):
name = input('Enter next name: ')
names = name
if input == ('')
for x in names.split():
print ('There is', x ,'named', names[x])
I'm really lost here and any input would help out tons. Also if possible please explain how to fix my code

There are a lot of issues with namings in your function, you are using such variables like 'names' that is used for function name as well as 'input' that is a python function name for reading user input - so you have to avoid using this. Also you defining a namecount variable as a dict and trying to initialize it before fill. So try to check solution below:
def myFunc():
names = []
name = ''
while True: #bad stuff you can think on your own condition
name = raw_input('press space(or Q) to exit or enter next name: ')
if name.strip() in ('', 'q', 'Q'):
for x in set(names):
print '{0} is mentioned {1} times'.format(x, names.count(x))
break
else:
names.append(name)
myFunc()
OR:
from collections import defaultdict
def myFunc():
names = defaultdict(int)
name = ''
while True: #bad stuff you can think on your own condition
name = raw_input('press space(or Q) to exit or enter next name: ')
if name.strip() in ('', 'q', 'Q'):
for x in set(names):
print '{0} is mentioned {1} times'.format(x, names[x])
break
else:
names[name] += 1

I rewrote your function for you:
def names():
names = {} # Creates an empty dictionary called names
name = 'cabbage' # Creates a variable, name, so when we do our while loop,
# it won't immediately break
# It can be anything really. I just like to use cabbage
while name != '': # While name is not an empty string
name = input('Enter a name! ') # We get an input
if name in names: # Checks to see if the name is already in the dictionary
names[name] += 1 # Adds one to the value
else: # Otherwise
names[name] = 1 # We add a new key/value to the dictionary
del names[''] # Deleted the key '' from the dictionary
for i in names: # For every key in the dictionary
if names[i] > 1: # Checks to see if the value is greater for 1. Just for the grammar :D
print("There are", names[i], "students named", i) # Prints your expected output
else: # This runs if the value is 1
print("There is", names[i], "student named", i) # Prints your expected output
When doing names():
Enter a name! bob
Enter a name! bill
Enter a name! ben
Enter a name! bob
Enter a name! bill
Enter a name! bob
Enter a name!
There are 3 students named bob
There are 2 students named bill
There is 1 student named ben

Let's analyse your code:
def names():
names = []
namecount = {a:name.count(a) for a in names}
while input != (''):
name = input('Enter next name: ')
names = name
if input == ('')
for x in names.split():
print ('There is', x ,'named', names[x])
There seem to be a few problems, let's list them
The while loop's conditional
What you want to do check if input from user is '' (nothing)..
input is a built-in function for getting input from user, so it never will be ('').
The names = name statement
What you want to do is add name to the list names.
Here you are changing names to a string, which isn't what you want.
The if's conditional
same as 1.
The for loop
let's ignore.. just not valid.. here..
We fix these problems as follows(solution has same numbering as problem above that it solves)
Change the conditional to something like name != ''.
Also, before the loop begins, you need to get input once for this to work, which in this case has a bonus, the first input can have a different prompt.
Use names.append(name) to add name to names.
Same as 1.
Just look at the for loop below...
Try this
def names():
names = []
name = input('Enter a name: ').strip() # get first name
while name != '':
names.append(name)
name = raw_input('Enter next name: ').strip() # get next name
for n in set(names): # in a set, no values are repeated
print '%s is mentioned %s times' % (n, names.count(n)) # print output

def names():
counters = {}
while True:
name = input('Enter next name:')
if name == ' ':
break
if name in counters:
counters[name] += 1
else:
counters[name] = 1
for name in counters:
if counters[name] == 1:
print('There is {} student named {}'.format(counters[name],name))
else:
print('There are {} student named {}'.format(counters[name],name))
names()

Related

Another question: Phone dictionary problem 'while-loop' using Error

Simply question making phone dictionary
What I want to do is putting person's name and number and finding them in dictionary!
Examples what I want to do
Enter command (a, f, d, or q).: a
Enter new name................: Perry
Enter new phone number........: 229-449-9683
Enter command (a, f, d, or q).: f
Enter name to look up...:
I would like to find full name and number when I type
Phone dictionary code what I wrote so far:
phone_dict = {}
command = input('Enter command (a, f, d, or q).: ')
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
while True:
if command == 'a':
newname
newphone
phone_dict[newname] = newphone
print(phone_dict)
# In here, 'while-loop' does not work.
In there, if I enter 'a' command, and type the name
The dictionary is supposed to be { Perry: 229-449-9683}
Thanks, The question might be little confused, but if you can help this out, I am very happy!
To find the result from the dictionary, you can loop through the items and check if the key contains the string you want to find. If you want to get all values which satisfy your query, you can create another list or dictionary and store the items you find:
phone_dict = {
"Han Perry": "1234",
"Harry Gildong": "2345",
"Hanny Test": "123",
}
find_str = "Han"
result = {}
for key, value in phone_dict.items():
# Converting it to lower makes it case insensitive
if find_str.lower().strip() in key.lower():
result[key] = value
print(result)
# {'Han Perry': '1234', 'Hanny Test': '123'}
Take note that this will run through all of the values of the dictionary: O(n)
To find the number using the first o last name of the person you could do:
a = 'Add a new phone number'
d = 'Delete a phone number'
f = 'Find a phone number'
q = 'Quit'
phone_dict = {}
while True:
# Gets the user command every loop
command = input('Enter command (a, f, d, or q).: ')
# Add a new registry to the directory
if command == 'a':
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
phone_dict[newname] = newphone
print(phone_dict)
# Find a registry on the directory
elif command == "f"
query = input("Enter name to look up...: ")
match = None
for key in phone_dict.keys():
if query.strip() in key:
match = phone_dict[key]
break
if match is None:
print(f"The name {query} could not be found on the directory")
else:
print(f"The phone number of {query} is {match}")
elif command == "d":
# Delete registry
elif command == "q":
# Quits program
else:
print(f"The command {command} was not found, please try again!")
In this case, I am using query.strip() to remove any extra start/end spaces that could cause to not find the person.

Error while getting input added into list

I am attempting to create a program that asks for the user to enter his/her name and records the input into a list (Was working towards dictionary but seems like I made a boo boo!) but it is returning with "TypeError: can only concatenate list (not "str") to list". The following is the code.Thanks in advance.
namedic = []
while True:
print ("Please, enter your name:")
name = input()
if len(name) > 3:
print ("Welcome")
else:
print ("Ew, your name have less than 4 letters! Gross! Try a new one")
continue
namedic = namedic + name
print ("Ah, your name have at least 4 words, good name.")
for name in namedic:
print (name)
Your erroring line is namedic = namedic + name. What you're trying to do is add a list (namedic) to a string (name). You should do namedic.append(name) instead.
The + operator isn't used to append elements to a list, as the error shows. You can use the append method for that:
namedic.append(name)
#your code should rather be like this;
namedic = []
while True:
print ("Please, enter your name:")
name = input()
if len(name) > 3:
print ("Welcome")
else:
print ("Ew, your name have less than 4 letters! Gross! Try a new one")
continue
namedic.append(name)
print ("Ah, your name have at least 4 words, good name.")
for name in namedic:
print (name)

Python- Allow user to modify item name in list and then show list with new name?

the code for this part of the program is below. I'm trying to allow a user to edit the name of one of the items and then when he enters the show command in the program the updated name will be there. I'm stuck on what function to use to allow the user to edit the name. thanks
def edit(item_list):
number = int(input("Number: "))
list.insert(item)
item = input("Updated name: ")
print(item +"was updated")
def main():
# this is the item list
item_list = ["wooden staff","wizard hat","cloth shoes"]
so if I enter edit as my command and then I write hello for number 1 item I want it to replace wooden staff with hello.
You can modify a list item by simply reassigning that index:
def edit(item_list):
number = int(input("Number: "))
curr_item = item_list[number]
new_item = input("Updated name: ")
item_list[number] = new_item
print("{} was updated to {}".format(curr_item, new_item))
return item_list
item_list = edit(item_list)
I am assuming that your print statement is meant to indicate what was changed. If you just want to re-print what the user entered, you can change it.
You could try:
def edit(item_list):
pos = int(input("Number: "))
new_value = input("Updated name: ")
item_list[pos-1] = new_value
print"%s was updated" % (new_value)
I hope this help you

Custom python function is not running

names=["aaa","bbb","ccc","ddd","eee"]
itMarks=[90,98,87,98,78]
def printMainMenu():
print(" Main Menu")
print(" =========")
print(" (1)Add Student")
print(" (2)Search Student")
print(" (3)Delete Student")
print(" (4)List Student")
print(" (5)Exit")
choice = int(input("Enter Your choice[1-5]:"))
return choice
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(names)
print("Index is" + i)
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(names)
print("Successfully Deleted" + names)
def removeStudent(names):
name = input("Enter name to remove")
name.remove(name)
print("Successfully deleted" + names)
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(names)
itMarks = input("Enter IT Marks")
itMarks.append(itMarks)
def listStudent(names, itMarks):
for i in range(0, len(names)):
print(names[1], "", itMarks[i])
names = []
itMarks = []
choice = 1
while choice >= 1 and choice <= 4:
choice = printMainMenu()
if choice == 1:
addStudent(names, itMarks)
elif choice == 2:
searchStudent(names, itMarks)
elif choice == 3:
deleteStudent(names, itMarks)
elif choice == 4:
listStudent(names, itMarks)
elif choice == 5:
print("Exit from the program")
else:
print("invalid choice!")
choice = 1
I am new to the programming in Python. The following Python code is written to do some tasks with the array. There are two array named names and itMarks. And there are some functions :
addStudent() - To add students to the array
searchStudent() - To search a student with in the list.
deleteStudent() - To delete the given student from the list.
listStudent() - To list out the all the names of the students in the list.
When the program runs, it asks to select a choice. Then it do the task according to their choice. But when I run this coding it shows the errors.
Please help me. Thanks in advance.
ERROR :
When I select the choice 1 (Add student) and input name after the error is yield.
Traceback (most recent call last):
File "C:\Users\BAALANPC\Desktop\new 3.py", line 59, in <module>
addStudent(names, itMarks)
File "C:\Users\BAALANPC\Desktop\new 3.py", line 42, in addStudent
name = input("Enter Name")
File "<string>", line 1, in <module>
NameError: name 'rtrt' is not defined
Their so many mistakes in naming
In addStudent
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(name) # names cant appent it should be name
itMark = input("Enter IT Marks") # here itmark not itMarks
itMarks.append(itMark)
In searchStudent
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name) # try to find index of name not names
print("Index is" + i)
In deleteStudent
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name) # try to remove name not names
print("Successfully Deleted" + name)
after change above I run its running you have to also change the naming of the variable for all methods
Output
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:1
add student
Enter Name"aaa"
Enter IT Marks111
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:
I'm assuming this is the correct form:
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name)
print("Index is" + i)
note that I changed names to name.
also the same mistake again
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name)
print("Successfully Deleted" + names)
tl;dr revise your code
searchStudent(): You shouldn't need the itMarks argument if you're not using it inside your function at all. names refers to the list of names, but you are really trying to search name. i is an integer that is attempting to be concatenated with a string. Not allowed. It should be str(i).
deleteStudent(): Better to keep your arguments consistent and use names rather than student. Again, same problem as above, should be .remove(name) and you shouldn't need the itMarks argument. print statement should refer to name not names.
removeStudent(): This is the same code as deleteStudent(), but not used, so not sure why it's there.
addStudent(): Typo in the argument, .append(name). You have a global variable and a local variable named the same thing, which are conflicting to the program. Change the input set to itMark and .append(itMark).
listStudent(): print statement has a typo, 1 should be i. Not sure why the empty string is included as well.
Underneath your function def's, you restate your variables as empty lists. This can lead to ValueErrors from a lot of your functions as you're trying to look something up or modify something in an empty list. Simply delete this code.
Additionally, any error will break your while loop. I suggest adding more booleans or using a try except clause to catch these errors.
Good luck!

Restarting my program based on user input on Python?

I'm new to programming, fyi. I want my program to restart back to the top based on what the user inputs. It will proceed if the user inputs 2 names. If they input 1 name or more than 2 names, it should restart the program but I'm not sure of how to do this.
def main():
print("Hello, please type a name.")
first_name, last_name = str(input("")).split()
while input != first_name + last_name:
print("Please enter your first name and last name.")
main()
You should use a while loop and check the length of the split before assigning:
def main():
while True:
inp = input("Please enter your first name and last name.")
spl = inp.split()
if len(spl) == 2: # if len is 2, we have two names
first_name, last_name = spl
return first_name, last_name # return or break and then do whatever with the first and last name
Use try/except
Well, your program didn't work for me to begin with, so to parse the first and last names simply, I suggest:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
Also your while loop will just, like, break your life if you run it without good 'ol ctrl+c on hand. So, I suggest:
def main():
print “type your first & last name”
try:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
if f and l:
return f + ‘ ‘+ l
except:
main()
The except: main() will re-run the program for you on error.

Categories