This code saves a number of key and value pair from the user but I want to go further and enter keys to be searched in phone book .Can someone tell me what's wrong with my code
phonebook = {}
n = int(input())
for x in range (n):
name , phoneno = input().split()
phonebook[ name ] = int(phoneno)
for y in phonebook:
name = input().split()
if name in phonebook:
print("Found")
else:
print('Not Found')
phonebook = {}
n = int(input())
for x in range (n):
name , phoneno = input().split()
phonebook[ name ] = int(phoneno)
name = input().split()
out = phonebook.get(name,None)
if out == None:
print('Not found')
else:
print('found')
You don't need a loop to check for a key in a dictionary
In name , phoneno = input().split() the .split() needs an argument on what to split it on, so lets say you did thisGuy 69420, if you did .split(' ') space being the argument name & phoneno would both be a list, which at index [0] would be thisGuy and at index[1] would be 69420
Hopefully, that helps :)
Related
condition = True
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
for item in range(0, len(classes)):
print(item+1, ".", classes[item])
while condition:
if(len(classes) < 5):
course = str(input("What course(s) would you like to take?: \n"))
course = course.title()
course = str(course)
print(course)
print(len(classes))
classes = course.split(",")
for i in range(len(classes)):
classes[i] = classes[i].strip()
print(len(classes))
print(classes)
printClasses()
elif (len(classes) > 5):
removeClass = input("Please select a class to remove: \n")
removeClass = removeClass.title()
removeClass = str(removeClass)
removeClass = removeClass.strip()
classGone = []
classGone = removeClass.split(",")
for i in range(len(classGone)):
classGone[i] = classGone[i].strip()
for item in classGone:
removeClass = []
inputCheck = classGone.count(removeClass)
if inputCheck > 0:
classes.remove(item)
else:
print("Please select a class that exists...")
printClasses()
else:
print("Done!")
break
Im having trouble with my inputCheck statement. I need to be able to remove things from the list but they have to be on there.
Thank you!
I tried to make a iputCheck variable that checks the list for the input to make sure it matches something in the list, but it all went downhill.
There were numerous mistakes in your code. Instead of pointing then all out I have fixed them and will allow you to figure it out on your own.
global classes
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
count = 1
for item in classes:
print('{}. {}'.format(count, item))
count += 1
while True:
if(len(classes) < 5):
course = str(input("What course(s) would you like to take?: \n"))
classes += course.split(",")
for i in range(len(classes)):
classes[i] = classes[i].strip().title()
printClasses()
elif (len(classes) > 5):
removeClass = str(input("Please select a class to remove: \n"))
classGone = removeClass.split(",")
for item in classGone:
i = str(item)
if i.strip().title() in classes:
classes.remove(i)
else:
print("Please select a class that exists...")
printClasses()
else:
print("Done!")
break
Had a pretty hard time understanding what you meant but I think I got it. You want to check if the selected class for removal is in the list? If that's the case you can use the following code:
#The list
classes=["English","Math","Coding"]
##Asking what classes to remove
Class_To_Remove=input("What class do you want to remove?")
#Removing the classes and checking if they are
for x in classes:
if Class_To_Remove.capitalize() in x:
classes.remove(Class_To_Remove.capitalize())
print("Class removed")
else:
print("Class isn't added")
If I understand everything correctly this will replace your:
removeClass = input("Please select a class to remove: \n")
removeClass = removeClass.title()
removeClass = str(removeClass)
removeClass = removeClass.strip()
classGone = []
classGone = removeClass.split(",")
for i in range(len(classGone)):
classGone[i] = classGone[i].strip()
for item in classGone:
removeClass = []
inputCheck = classGone.count(removeClass)
if inputCheck > 0:
classes.remove(item)
else:
print("Please select a class that exists...")
For future reference try to only use the few lines you are having trouble with and explaining the problem more clear.
I've been trying to understand this for some time. For the next one please be more clear.
Since there's several mistakes on your code, I tried to make a solution that could work for you. Here it is!
global classes
classes = []
print("Welcome to class registration!")
def printClasses():
print("You are currently taking these courses: ")
for i in range(0, len(classes)):
print(i+1, ".", classes[i])
control = True
while control:
if(len(classes) < 5):
course = str(input("What course(s) would you like to take?: \n"))
classes += course.split(",")
for i in range(len(classes)):
classes[i] = classes[i].strip().title()
printClasses()
elif (len(classes) >= 5):
option = input("Do you want to remove a class?\n 1.Yes\n 2.No\n")
if option == "1":
classGone = []
for i in range(1):
removeClass = input("Please select a class to remove: \n")
if (removeClass == classes[0] or
removeClass == classes[1] or
removeClass == classes[2] or
removeClass == classes[3] or
removeClass == classes[4]):
classes.remove(removeClass)
classGone.append(removeClass)
print("Classes removed are: ", classGone)
printClasses()
i += 1
break
else:
print("Please select a valid class")
elif option == "2":
print("Done!")
break
Hope it works!
i'm trying to convert user input into only alphabets, and convert each alphabet into a number(ex. a=1, b=2), then the numbers together. I've been able to complete the first part, but not sure how to do the second part.
import re
name = input("Name: ")
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
for al in range(len(cleaned_name)):
print(numbers,sep='+')
#if input is jay1joe2, cleaned name will be jayjoe
#after the 'numerology', will print the following below
#10+1+25+10+15+5 = 66
Something like this should work for what you're trying to do.
Note: I'm hardcoding the name here rather than using the user input, so it's easier to test it out if needed.
import string
# name = input("Name: ")
name = 'jay1joe2'
cleaned_name = filter(str.isalpha, name)
cleaned_name = "".join(cleaned_name)
print("Your 'cleaned up' name is: ", cleaned_name)
numbers = {char: i for i, char in enumerate(string.ascii_lowercase, start=1)}
result = list(map(numbers.get, cleaned_name))
print(*result, sep='+', end=' ')
print('=', sum(result))
Where the second part (after numbers) could also be written alternatively as follows, using f-strings in 3.6+:
result = [numbers[c] for c in cleaned_name]
print(f"{'+'.join(map(str, result))} = {sum(result)}")
Result:
Your 'cleaned up' name is: jayjoe
10+1+25+10+15+5 = 66
name = input("Name: ")
name = name.lower()
name1 = list(name)
Addition: int = 0
for k in name1:
if ord(k)-96 < 1 or ord(k)-96 > 26:
pass
else:
Addition = Addition + ord(k) - 96
print(Addition)
We can use ascii codes for Numbers and Characters :)
I'm having trouble entering data I keep getting the error "invalid literal for int() with base 10"
def strings_to_ints(linelist):
outputlist = []
for item in linelist:
outputlist.append(int(item))
return outputlist
def process_line(line):
global box_count, ship_class
linestrings = line.split()
name = linestrings[0]
linevalues = strings_to_ints(linestrings[:1])
quantity = linevalues [0]
ship_class = linevalues [1]
box_count = box_count + quantity
order_price = compute_price(quantity)
discounted_price = compute_discounted_price()
tax = compute_tax(discounted_price)
ship_cost = compute_ship_cost(quantity)
billed_amount = discounted_price + tax + ship_cost
outlist = [quantity, order_price, compute_discount(), tax, ship_cost, billed_amount]
return name, outlist
def enter_data():
global order_count
line = input('Enter Name, Quantity, and Ship Class: >>> ')
name, outlist = process_line(line)
order_count = order_count + 1
print(name, outlist))
I know I that the name should somehow be separate from the numbers but I can't figure out where to do this.
I added the most of code, all of the relevant parts I think. Hopefully, it's easier to understand
linevalues = strings_to_ints(linestrings[:1])
should be:
linevalues = strings_to_ints(linestrings[1:])
Assuming that both Quantity and ship class are integers, and are space separated
i.e.
Test 1 2
Whithout understanding all of your code, I think that the problem is that linestrings[:1] is an array containing at most the first element of linestrings. If you want all but the first, use linestrings[1:] instead.
I want to make a program that adds a name in the dictionary if it doesn't exist already and count the times it is given as input. My code works, however, it doesn't add 1 when it iterates.
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] += 1
# else wasn't properly indented earlier
else:
namelist[word] = 1
print(namen())
print(namelist)
You can use the dict.get method instead to provide a default value to a new entry to the dict:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
for name in namelist:
if word == name:
namelist[word] = namelist.get(word, 0) + 1
Your check is incorrect, you need if rather than for to see if the key exists, then you can remove the inner if statement
if name in namelist:
namelist[word] += 1
else:
namelist[word] = 1
No one said anything about the has_key method of dictionaries, which is in my opinion the standard way to to this:
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
if namelist.has_key(word):
namelist[word] += 1
else:
namelist[word] = 1
print(namen())
print(namelist)
try this
namelist = {}
def namen():
while True:
word = input('Vul een naam in: ')
if word == '':
break
else:
try:
namelist[word] += 1
except:
namelist[word] = 1
print(namen())
print(namelist)
I am trying to print the results from all 3 names that are input, in a dictionary format. Current code below only prints out the last name. The 2 lines commented out (#) are what I was trying to change around to get it to work, clearly not doing it correctly.
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
#d['first name'].append(v)
#d['last name'].append(v)
count += 1
print(d)
name()
A few things that I'd change:
append each record (dictionary) to a list of entries.
(optional) Use a for-loop rather than a while as less lines of code.
return the entries list, rather than print it as it is a function so I like to have outputs.
So here's the corrected code:
def name():
entries = []
for count in range(5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k, v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
entries.append(d)
return entries
print(name())
For testing purpose, I modified it to just except 2 entries, but we can still see that it works:
Please enter your last name: fish
Please enter your first name: bowl
Please enter your last name: cat
Please enter your first name: mat
[{'Lname': 'fish', 'Fname': 'bowl'}, {'Lname': 'cat', 'Fname': 'mat'}]
Hope! you got it right from Martijin Comments, For reference to other adding this code:
def name():
count = 0
listOfDict = [] #creating empty list
for count in range(3):
dict = {}
qs = dict(Fname = 'first name', Lname = 'last name' )
for k,v in qs.items():
d[k] = input('please enter your {}: '.format(v))
listOfDict.append(d) # adding each item to the list.
count += 1
print listOfDict
name()
This should work:
def name():
count = 0
while (count < 5):
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
a = input('Please enter your {}: '.format(v))
d[v] = a
count += 1
print(d['first name'],d['last name'])
name()
You can use defaultdict to automatically create lists to store each entered value. The main idea is that you want to append each entered value to a collection of some type (e.g. list).
from collections import defaultdict
number_of_entries = 3
dd = defaultdict(list)
for _ in range(number_of_entries):
for key in ('first name', 'last_name'):
dd[key].append(input('please enter you {}: '.format(key)))
>>> print(dict(dd))
{'first name': ['Adam', 'Milton', 'Irving'],
'last_name': ['Smith', 'Friedman', 'Fisher']}