Struggling with Python - python

I must answer this question in python but I'm not sure what i must do, this is the question:
Your program should read in multiple lines of input from the user, stopping when the user enters a blank line. Each line will be a command from the user to the phone. Each command consists of a space-separated sequence of words.
If the first word is Add, there will be two words following it: the name of the person and their phone number. If an Add command is encountered, your program should store this name to phone number mapping. Alternatively, if the first word is Call, there will be one word following it: the name of the person to call. In this case, if the phone knows the number for this person, your program should print out that it is calling that number, otherwise it should print out that it does not have a number for this person.
The program I have written is this:
contact = {}
**line = input('Command: ')
while line:
parts = line.split()
name = parts[0]
number = parts[1]
contact[name] = int(number)
line = input('Command: ')**
What more should I add or do to make this program work?

You need to distinguish the different commands.
contact = {}
line = input('Command: ')
while line:
parts = line.split()
command = parts[0]
if command == 'Add':
contact[parts[1]] = parts[2]
elif command == 'Call':
pass
# add the code to find the number and print it
line = input('Command: ')**

To start with you need to add a loop to keep asking the user for a command until they enter a blank line.
When writing an script which interacts with a user, it is also wise to think in terms of what the user could do wrong. The problem states a number of requirements, for example, if Add is entered, there should be two words following. If the user only entered one, what should you do?
Also what happens if the user enters a name that has not yet been entered? Python dictionaries provide a get() method which handles this. It allows you to specify what needs to be returned when the requested key is not present. In this case, you can return "Unknown name".
The following shows what I mean:
line = ' '
contacts = {}
while line:
line = input('Command: ')
if line:
words = line.split()
if words[0] == 'Add':
if len(words) == 3:
contacts[words[1].lower()] = words[2]
else:
print("Badly formatted Add")
if words[0] == 'Call':
if len(words) == 2:
print(contacts.get(words[1].lower(), "Unknown name"))
else:
print("Badly formatted Call")
By using the .lower() command on the entered name, it would then mean the user could do "Add Fred 1234 / Call fred" and it would still find a match.

Related

List as function parameter returning NameError: not defined

I am new to Python. Working with 2.7 for class.
The teacher set a project in which we are to code a program that takes a piece of a Monty Python script (input by user), stores it in a list of lists, replaces a specific name in the script with the user's name and prints the revised script out to console.
The issue I am running into is in my third function replace_name, the parameters are the list of lists, old name, new name.
However, I am getting
NameError:'word_list' is not defined
I understand that if a variable is not defined in the Main then it is local to its function.
I thought though, that by using return in the function that that information is stored to be used by subsequent functions.
Am I wrong?
def new_name(): #prompts for user's name. checks if input is valid
while True:
name = raw_input("Please enter your name.\n")
if len(name) < 1:
print "Invalid, please enter your name.\n"
else:
return name
def orig_script():#reads in script, splits into list of lists
word_list = []
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit. \n")
if len(script) < 1:
print "Empty text field. Please try again.\n"
while script != 'done':#splits string input,adds to list
words = script.split()
word_list.append(words)
script = raw_input("Please enter script, one line at a time. Enter 'done' to exit.\n ")
if len(script) < 1:
print "Empty text field. Please try again.\n"
return word_list
def replace_name(word_list,old_name,new_name):#replaces old name with new name in list. creates new list from changes.
new_list = []
for sentences in range(word_list):
sentence = word_list[sentences]
for words in range(sentece):
word = sentence[words]
if word == old_name:
sentence[words] == new_name
new_list.append(sentence)
print new_list#debugging-change to return
new_name()
orig_script()
replace_name(word_list, Robin, new_name)
If my indentation is a bit off here, I apologize.
I tried to correct it from the copy/paste.
There are no indentation errors given in repl.it.
Traceback (most recent call last):
File "python", line 45, in <module>
NameError: name 'word_list' is not defined
You did not assign any of the word_list, Robin, new_name variables. Returning a variable of a particular name does not bind it to any type of external variable on its own, especially not one of the same name.
For example, you need to assign the return value explicitly to its own variable.
word_list = orig_script()
name = new_name()
replace_name(word_list, "old name", name)
Also
for sentences in range(len(word_list)):
sentence = word_list[sentences]
Is the same as
for sentence in word_list:
Note: You do have a typo in sentece and this is a comparison, not an assignment sentence[words] == new_name
Bonus, I think you can rewrite replace_name as
def replace_name(word_list,old_name,new_name):
return [[new_name if w == old_name else old_name for w in sentence] for sentence in word_list]
Pass the parameter in you function argument.
Ex.
#take the o/p of variable in another one and pass in funcation
return_val = orig_script()
old_name = ["jack", "mike" , "josh"]
new_name= ["jen" , "ros" , "chan"]
#calling replace name funcation
replace_name(return_val,old_name,new_name)

Why am I getting a AttributeError: 'str' object has no attribute 'remove' when attempting to remove an element using a variable or a string?

The purpose of this program is to create a list of names for people attending a party. I would like to be able to grant the user the ability to continue adding names until they chose YES as an option to exit the loop. However, I have am stomped when it comes to having them enter a name they would like to remove in case they added someone by accident or if they would like to edit the list and remove or replace someone.
I am currently a newbie to programming, hence the lack of classes to this code. Any help would be greatly appreciated. Thank you all in advance!
#Initialize empty list
partyList = []
#Initilize empty entry
inviteeName = ''
endEntry = ''
#Run loop until YES is entered as a value
while endEntry != "Yes":
inviteeName = input("Please enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
# Verifies if a name was not entered.
while inviteeName == "":
inviteeName = input("\nPlease enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
endEntry = input("\tPress ENTER to continue or type Yes to finish: ")
endEntry = endEntry.title()
#Append every new name to the list
partyList.append(inviteeName)
#Adds the word "and" to finish sentence if there are more than one invitees. NOTE: Make a class please!
numOfInvitees = len(partyList)
if numOfInvitees > 1:
partyList.insert(-1, 'and')
#Remove brackets and quotes.
partyList = ', '.join(partyList)
#Print message
print("\nThis will be your final message:\n" + str(partyList) + "\nYou are invited to my party!\n")
I was trying to use this to assist the user with removing names entered by accident.
submit = input('Submit?: '.title())
submit = submit.title()
if submit == 'Yes':
print('Invite has been sent!')
elif submit == 'No':
remNameConfirmation = input('Would you like to remove a name from the list?: ')
remNameConfirmation = remNameConfirmation.title()
if remNameConfirmation == 'Yes':
uninviteName = (input('Who would you like to remove?: '))
uninviteName = uninviteName.title()
Here is the line that is giving some trouble
partyList.remove(uninviteName)
print(partyList)
When your code reaches
partyList = ', '.join(partyList)
it will set the variable partyList to a string. Since it is no longer a list it does not have the .remove method.

Matching user input to file records in Python

i'm making a program that will ask a user to enter their student ID and it will display the student information such as student ID and their student name . i does this first by asking the user to enter their id and it will then read a .txt file and check if the student id is a matched then it will print out the content of my .txt file information of the specific student that the user is looking for.
this is my content of the file
201707001 Michael_Tan
201707002 Richard_Lee_Wai_Yong
201707003 Jean_Yip
201707004 Mark_Lee
201707005 Linda_Wong
201707006 Karen_Tan
201707007 James_Bond
201707008 Sandra_Smith
201707009 Paul_Garcia
201707010 Donald_Lim
this is my source code
# user can find out the student info
userInput = input("Please enter a student ID: ")
# read the students file
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split(" ",1)
# check if the student exist
matched = True
while matched:
if userInput == stdId:
print("True")
else:
print("False")
matched = False
break
but the output i get is false even though i type the exact studentID
You should perform your checks as you read your file. Otherwise, you are splitting and obtaining your information, but this data is lost in the subsequent iteration. Try this:
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split()
if userInput == stdId:
print(stdName)
break
Better still, for large files, iterate line-wise. Do not use f.readlines because it loads all your data into memory.
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
for line in f:
stdId, stdName = line.strip().split()
if userInput == stdId:
print(stdName)
break
As it stands your code loops through every ID and name and assigns each into the stdId and stdName, but that loop exits before you check for a match... Because of that it only holds the last value stored in those variables by the loop. You need the check in the loop, as so
# user can find out the student info
userInput = input("Please enter a student ID: ")
# read the students file
with open('C:\\Users\\jaspe\\Desktop\\PADS Assignment\\Student.txt') as f:
studentFile = f.readlines()
for student in studentFile:
stdId, stdName = student.strip().split(" ",1)
# check for a match here, break the loop if a match is found
Use raw_input instead of input.
You almost never want to use input, because it does evaluation. In this case, typing in an exact integer gives you an integer, while the file gives you a string, so it won't match.
You have other minor / major issues in the code.
If the loop is entered with userInput == stdId you will loop forever printing True.
You never actually search through the student ids, you just check the last one set in your previous loop
(For this I would recommend using a dictionary if you plan to do multiple user queries, or just look as you read the lines of the file for a simple script)

Writing multiple lines to file and then reading them with Python

I've just undertaken my first proper project with Python, a code snippet storing program.
To do this I need to first write, then read, multiple lines to a .txt file. I've done quite a bit of googling and found a few things about writing to the file (which didn't really work). What I have currently got working is a function that reads each line of a multiline input and writes it into a list before writing it into a file. I had thought that I would just be able to read that from the text file and add each line into a list then print each line separately using a while loop, which unfortunately didn't work.
After going and doing more research I decided to ask here. This is the code I have currently:
'''
Project created to store useful code snippets, prehaps one day it will evolve
into something goregous, but, for now it's just a simple archiver/library
'''
#!/usr/local/bin/python
import sys, os, curses
os.system("clear")
Menu ="""
#----------- Main Menu ---------#
# 1. Create or edit a snippet #
# 2. Read a snippet #
# 0. Quit #
#-------------------------------#
\n
"""
CreateMenu ="""
#-------------- Creation and deletion --------------#
# 1. Create a snippet #
# 2. Edit a snippet #
# 3. Delete a snippet (Will ask for validation) #
# 0. Go back #
#---------------------------------------------------#
\n
"""
ReadMenu="""
#------ Read a snippet ------#
# 1. Enter Snippet name #
# 2. List alphabetically #
# 3. Extra #
# 0. Go Back #
#----------------------------#
"""
def readFileLoop(usrChoice, directory):
count = 0
if usrChoice == 'y' or 'n':
if usrChoice == 'y':
f = open(directory, 'r')
text = f.read()
f.close()
length = len(text)
print text
print length
raw_input('Enter to continue')
readMenu()
f.close()
elif choice == 'n':
readMenu()
def raw_lines(prompt=''):
result = []
getmore = True
while getmore:
line = raw_input(prompt)
if len(line) > 0:
result.append(line)
else:
getmore = False
result = str(result)
result.replace('[','').replace(']','')
return result
def mainMenu():
os.system("clear")
print Menu
choice = ''
choice = raw_input('--: ')
createLoop = True
if choice == '1':
return creationMenu()
elif choice == '2':
readMenu()
elif choice == '0':
os.system("clear")
sys.exit(0)
def create():
os.system("clear")
name = raw_input("Enter the file name: ")
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
while os.path.exists(dire):
os.system("clear")
print("This snippet already exists")
name = raw_input("Enter a different name: ")
dire = ('shelf/'+name+'.txt')
print("File created\n")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
else:
print("File created")
f = open(dire, "w")
print("---------Paste code below---------\n")
text = raw_lines()
print text
raw_input('\nEnter to write to file')
f.writelines(text)
f.close()
raw_input('\nSnippet successfully filled, enter to continue')
def readMenu():
os.system("clear")
name = ''
dire = ''
print ReadMenu
choice = raw_input('--:')
if choice == '1':
os.system("clear")
name = raw_input ('Enter Snippet name: ')
dire = ('shelf/'+name+'.txt')
if os.path.exists(dire):
choice = ''
choice = raw_input('The Snippet exists! Open? (y/n)')
'''if not choice == 'y' or 'n':
while (choice != 'y') or (choice != 'n'):
choice = raw_input('Enter \'y\' or \'n\' to continue: ')
if choice == 'y' or 'n':
break'''
readFileLoop(choice, dire)
else:
raw_input('No snippet with that name exists. Enter to continue: ') #add options to retry, create snippet or go back
readMenu()
elif choice == '0':
os.system("clear")
print Menu
def creationMenu(): ###### Menu to create, edit and delete a snippet ######
os.system("clear")
print CreateMenu
choice = raw_input('--: ')
if choice == '1': ### Create a snippet
os.system("clear")
print create()
print creationMenu()
elif choice == '2':
os.system("clear") ### Edit a snippet
print ("teh editon staton")
raw_input()
print creationMenu()
elif choice == '3':
os.system("clear") ### Delete a snippet
print ("Deletion staton")
raw_input()
print creationMenu()
elif choice == '0': ### Go Back
os.system("clear")
######## Main loop #######
running = True
print ('Welcome to the code library, please don\'t disturb other readers!\n\n')
while running:
mainMenu()
######## Main loop #######
Tl;Dr: Need to write and read multiline text files
The problem that I'm having is the way the multilines are being stored to the file, it's stored in list format e.g ['line1', 'line2', 'line3'] which is making it difficult to read as multilines because I can't get it to be read as a list, when I tried it added the whole stored string into one list item. I don't know if I'm writing to the file correctly.
OK, so the problem is with writing the file. You're reading it in correctly, it just doesn't have the data you want. And the problem is in your raw_lines function. First it assembles a list of lines in the result variable, which is good. Then it does this:
result = str(result)
result.replace('[','').replace(']','')
There are two small problems and one big one here.
First, replace:
Return[s] a copy of the string with all occurrences of substring old replaced by new.
Python strings are immutable. None of their methods change them in-place; all of them return a new string instead. You're not doing anything with that new string, so that line has no effect.
Second, if you want to join a sequence of strings into a string, you don't do that by calling str on the sequence and then trying to parse it. That's what the join method is for. For example, if your lines already end with newlines, you want ''.join(result). If not, you want something like '\n'.join(result) + '\n'. What you're doing has all kinds of problems—you forgot to remove the extra commas, you will remove any brackets (or commas, once you fix that) within the strings themselves, etc.
Finally, you shouldn't be doing this in the first place. You want to return something that can be passed to writelines, which:
Write[s] a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings.
You have a list of strings, which is exactly what writelines wants. Don't try to join them up into one string. If you do, it will run, but it won't do the right thing (because a string is, itself, a sequence of 1-character strings).
So, if you just remove those two lines entirely, your code will almost work.
But there's one last problem: raw_input:
… reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
But writelines:
… does not add line separators.
So, you'll end up with all of your lines concatenated together. You need the newlines, but raw_input throws them away. So, you have to add them back on. You can fix this with a simple one-line change:
result.append(line + '\n')
To read multiple lines from a file, it's easiest to use readlines(), which will return a list of all lines in the file. To read the file use:
with open(directory, 'r') as f:
lines = f.readlines()
And to write out your changes, use:
with open(directory, 'w') as f:
f.writelines(lines)
fileList = [line for line in open("file.txt")]
While the previously mention idiom will work for reading files, I like mine. Its short and to the point.

How to check for white space input in python

I'm very new to programming and python. I'm writing a script and I want to exit the script if the customer type a white space.
questions is how do I do it right?
This is my attempt but I think is wrong
For example
userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()
line = inf.readline()
while (userType == raw_input)
print "userType\n"
if (userType == "")
print "invalid entry, the program will terminate"
# some code to close the app
I know this is old, but this may help someone in the future. I figured out how to do this with regex. Here is my code:
import re
command = raw_input("Enter command :")
if re.search(r'[\s]', command):
print "No spaces please."
else:
print "Do your thing!"
The program you provided is not a valid python program. Because you are a beginner some small changes to you program. This should run and does what I understood what it should be.
This is only a starting point: the structure is not clear and you have to change things as you need them.
userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()
#line = inf.readline() <-- never used??
while True:
userType = raw_input()
print("userType [%s]" % userType)
if userType.isspace():
print "invalid entry, the program will terminate"
# some code to close the app
break
You could strip all whitespaces in your input and check if anything is left.
import string
userType = raw_input('Please enter the phrase to look: ')
if not userType.translate(string.maketrans('',''),string.whitespace).strip():
# proceed with your program
# Your userType is unchanged.
else:
# just whitespace, you could exit.
After applying strip to remove whitespace, use this instead:
if not len(userType):
# do something with userType
else:
# nothing was entered

Categories

Resources