Simple Phonebook - python

this is some simple code I wrote for a phonebook.
It does not seem to work though, and I do not know why.
I am very new to python, and I am sure there are many errors.
def startup(contactlist = {}):
print "Welcome to Contacts+\n"
print "Please enter your name"
name = raw_input()
print "Hi " + name + " would you like to check your existing contacts or make new ones?"
print "To make new contacts type in 'New'"
print "To check existing contacts type in 'Contacts'"
choose = ""
choose = raw_input()
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
def newcontact():
startup(contactlist = {})
print "To create a new contact please first input the name"
contactname = raw_input()
print "Next enter the phone number"
contactnumber = raw_input()
print "Contact created!"
contactlist[name] = number
def checkcontact():
startup(contactlist = {})
print contactlist
startup()

Have you tried to run this...?
This if/elif statement shouldn't be indented:
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
And why do you have:
startup(contactlist = {})
in the beginning of newcontact() and checkcontact() function?

Four things you can do right now to make your code better:
Go read about this gotcha in Python. We tricked you. (We're sorry! We had good reasons.) You can't really do that with lists and dicts, and you have to use a Python idiom involving None to do it right.
Use raw_input's first argument. Instead of print('Hey user!'); raw_input(), just write raw_input('Hey user!').
Learn the in keyword. Whenever you find yourself saying if x == 'x' or x == 'y' or x == 'z', it's probably easier to write if x in 'xyz' (strings are iterable, remember?). You can also get rid of two of those cases by stripping off quotes the user might enter if you don't want them -- choose.strip("'").
Fix your function calls. Functions in Python can be called in two ways, using positional arguments f(a, b, c) or keyword arguments f(a, b=0, c=2). Calls like startup(contactlist={}) are just explicitly setting that argument to the empty dict, its default value, so this is always equivalent to startup() the way you have it defined.

Related

Creating a Python game, working with returns in-between multiple modules

No matter how many times I google variations of my question, I cannot seem to find a solution. I am a beginner programmer, trying to build a game that randomly generates events as you progress through the stages. The problem I am running into are return statements, and passing the values between different modules. Each method for each file are inside of classes. They are all static methods, and calling these methods is not my problem. It is transferring the value of the variables. I'm not sure where I am going wrong, whether it is how I am structuring it, or if I just don't understand how these return statements work.
This is the first File I am starting from. Print statements will be filled out after everything functions properly.
def story():
print("---Intro Story Text here--- ... we will need your name, Traveler. What might it be?")
user_prompt = Introduction.PlayerIntroduction
name = user_prompt.player_info(1)
print(f"Welcome {name}!")
print(f"----After name is received, more story... how old might you be, {name}?")
age = user_prompt.player_info(2)
This is the file I am trying to get the values from. File: Introduction, Class: PlayerIntroduction
#staticmethod
def player_info(funct_select):
if funct_select == 1:
name = PlayerIntroduction.get_player_name()
player_name = name
elif funct_select == 2:
age = PlayerIntroduction.get_player_age()
player_age = age
return player_name, player_age
#staticmethod
def get_player_name():
print("\n\n\nWhat is your name?")
players_name = input("Name: ")
while True:
print(f"Your name is {players_name}?")
name_response = input("Yes/No: ")
if name_response == "Yes" or name_response == "yes":
name = "Traveler " + players_name
break
elif name_response == "No" or name_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_name()
else:
print("Please respond with 'Yes' or 'No'.")
return name
#staticmethod
def get_player_age():
print("\n\n\nHow old are you?")
age = input("Age: ")
while True:
print(f"Your age is {age}?")
age_response = input("Yes/No: ")
if age_response == "Yes" or age_response == "yes":
break
elif age_response == "No" or age_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_age()
else:
print("Please respond with 'Yes' or 'No'.")
return age
I would like to use the values for "name" and "age" throughout multiple modules/multiple methods within my program. But in order to get those values, I need to assign a variable to the function call.. Resulting in prompting the user to re-enter their name/age at later stages in the game. My idea to combat this was in the first method of this module, creating a conditional statement "if 'example' == 1: 'run the name prompt' and elif == 2: run age prompt, thinking the initial run with the arguments defined would run these prompts, store the values into the variables (name, age), and finally pass the values to the new variables that are NOT assigned to the function call (p_name, p_age), avoiding triggering the user prompt over and over. Ultimately, this failed, and as the code sits now I am getting:
UnboundLocalError: local variable 'player_age' referenced before assignment
Why is this? The only instance 'player_age' is called that is reachable at this point is in the return statement, indented in-line with the conditional statement. The code should read (If I understand incorrectly, please explain) from top to bottom, executing in that order. The 'if' condition is met, so it should run that. If I were to define 'player_name' and 'player_age' as null at the top of this method to avoid this error, then every time I would need to reference these values initially entered by the user, they would be re-assigned to 'null', negating everything I am trying to do.
Thank you all for your patience, I tried to explain what I was doing and my thought process the best I could. Any feedback, criticism, and flaws within my code or this post are GREATLY appreciated. Everything helps me become a better programmer!! (:

Python: 'other_activity' is not defined

I want to print the other_activity if its not empty after taking input from user but this error, I know its pretty basic but not able to find the solution
print("What kind of activity is this?")
print '\n'.join(acti)
userInput = raw_input("\n""Client->")
r = re.compile(userInput)
if not filter(r.match, acti):
print("not valid activity")
else:
if (userInput == "Other"):
event_activity = raw_input("-> Please specify your activity\n""Client->")
other_activity = ("Other:" + event_activity)
else:
event_activity = userInput
if not other_activity:
print("Activity type: ", other_activity)
else:
print("Activity type: ", event_activity)
Define other_activity = None at the top of your code (There are cases in your code when other_activity is never assigned, and thus, never created. By adding this default assignment, you are making sure the variable will exist when checking its value)
At the end, you can use a ternary condition to print one variable or the other:
print('Activity type:', other_activity if other_activity else event_activity)

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

Syntax error when creating simple python program

Hope you are all well.
Trying to create a Python program which acts as a dictionary however now having some issues with creating an elif statement. Im my IDLE I keep getting signs saying that my syntax is wrong for the elif, I am not quite what I am doing wrong though? I suppose it is an indentation error but what exactly is it?
if choice == "0":
print "good bye"
elif choice == "1":
name = raw_input("Which philosopher do you want to get")
if name in philosopher:
country = philosopher [name]
print name, "comes from" , country
else:
print "No such term"
***elif choice == "2" :*** ***<<I am being told that I have syntax error in this elif element, what am I doing wrong)**
name = raw_input(" What name would you like to enter")
if name not in philosopher:
country = raw_input( "Which country do you want to put your philosopher in")
philosopher [name] = country
print name, "has now been added and he is from", country
else:
print "We already have that name"
Assuming you fix the indentation, the if statements all go in this order for you:
if x:
#do something
elif x:
#do something
if x:
#do something
else:
#do something
elif x:#CAUSES ERROR
#do something
if x:
#do something
else:
#do something
Your elif comes AFTER an else statement. You can't do this. elif MUST go between if and else. Otherwise the compiler doesn't ever catch the elif (Because it just ran through and did the else statement). In other words, you must have your if statements ordered like so:
if x:
#do something
elif x:
#do something
else:
#do something
I think that you are correct as to an indentation problem. Here is what I think you are trying to do:
if choice == "0":
print "good bye"
elif choice == "1":
name = raw_input("Which philosopher do you want to get")
if name in philosopher:
country = philosopher [name]
print name, "comes from" , country
else:
print "No such term"
elif choice == "2" :
name = raw_input(" What name would you like to enter")
if name not in philosopher:
country = raw_input( "Which country do you want to put your philosopher in")
philosopher [name] = country
print name, "has now been added and he is from", country
else:
print "We already have that name"
The key problem is inconsistent indentation, which makes it hard for Python to determine what you want. Until you develop your own style and have a good reason for doing otherwise, a consistent four spaces of indentation per level is a good habit. Let your editor help you indent consistently. Oh, and make sure not to mix tabs and spaces when you indent: that has a way of seeming to work for a bit and then coming back and biting you.
It looks like you want to put your if name in philosopher...No such term" section inside of the block beginning elif choice == "1":. If so, you need to indent one additional time in order for Python to properly group your if, elif and else statements.
if choice == "0":
# code
elif choice == "1":
if name in philospher: # indented twice; can only run if choice == "1"
# code
else:
# code
elif choice == "2":
# code
# rest of code

text based game in python

heres my code
direction = 0
while direction != ("quit"):
direction = input("> ")
if direction[0:4] != "quit" and direction != "go north" and direction != "go south" and direction != "go east" and direction != "go west" and direction != "go up" and direction != "go down" and direction[0:4] != "look":
if direction[0:2] == "go" and direction[3:] == (""):
print("please tell me more")
else:
print("huh?")
elif direction[0:1] == "go" and direction != "north" and direction != "south" and direction != "east" and direction != "west" and direction != "up" and direction != "down":
print ("please tell me more")
elif direction[0:4] == "quit":
print ("OK ... but a small part of you may never leave until you have personally saved Muirfieland from the clutches of evil .. Bwahahahahahah (sinister laugh).")
elif direction[0:4] == "look":
print ("You see nothing but endless void stretching off in all directions ...")
else:
print ("You wander of in the direction of " + direction)
im trying to add this into my code
if the first word is recognised but the second is not, it will respond with :
"sorry, im afraid i cant do that"
im just having troubles getting that one bit into my code, any help will be appreciated thanks.
So quick analysis... You're making text parser which works as following:
Get first word of "command", if we don't know word user used invalid input -> inform and restart
If user used known "command", parse its arguments (like: go north, go south) and let "nested" function take care of argument
Note that "main parsing function" doesn't need to know whether arguments for go() are valid, it just delegates responsibility for validation to go().
So I think you should build code (class) like this:
class Game:
# Initialize internal variables, method automatically called on g = Game()
def __init__(self):
self._exit = False
# Array of known commands, used in run, basically maps commands
# to function and it says: if will get 'go' execute self._go
self._commands = {
'go': self._go,
'quit': self._quit
}
# Array of go sub commands, used by _go
self._commands_go = {
'north': self._go_north
# ...
}
# Mathod for parsing command, if it gets "comamnd" returns ("command",None)
# if "command arg1 arg2" returns ("command", "arg1 arg2")
#staticmethod
def parse_command(string):
string = str(string)
index = string.find(' ')
if index < 0:
return (string, None)
return (string[:index], string[index+1:])
# This is main method; the only one which should be called from outside
# It will just read data from input in never ending loop and parse commands
def run(self):
while not self._exit:
src = input('> ')
(command,args) = Game.parse_command( src)
# Do we have this command, execute it
if command in self._commands:
self._commands[command](args)
else:
print( 'I\'m sorry I don\'t known command {}, try one of these:'.format(command))
print( '\n'.join( self._commands.keys()))
#######################################################
# All game commands go here
#######################################################
def _quit(self,args):
self._exit = True
print( 'Bye bye')
# Movement handling, will get executed when user types 'go ...' nad '...' will be in arg
def _go(self,args):
# No argument
if args is None:
print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
return False
# Split sub command anr arguments
(command,args) = Game.parse_command(args)
if command not in self._commands_go:
print( 'Go excepts one of these:', '; '.join( self._commands_go.keys()))
return False
if args is not None:
print( 'Too many arguments for go')
return False
self._commands_go[command](args)
return True
# Go north
def _go_north(self, args):
print( 'Going north')
game = Game()
game.run()
Which would allow you to:
build complex nested commands
build nice and readable commands hierarchy (inventory item 123 update use potion 345) instead of hardly readable set of complex conditions
build function aliases go north can be aliased as gn by adding 'gn': self._go_north to _commands
build reusable arguments parsing (item_id, action, args) = self._parse_item_action(args)
take advantages of object oriented programming (no global variables, everything will be class attribute, lower risk of accidental variables overwriting)
And if you need to parse goasdf as go you can just simply:
for i in self._commands:
if input.startswirh( i):
return self._commands[i](...)
print('Invalid command')
return False
Note: I haven't tested the code, it's just out of my head.
Your code looks quite confusing to me, here is just a simpler version of your code:
flag = 0
count = 0
direction = 0
while direction != ("quit"):
direction = input("> ")
count += 1
if recognised and count == 1: # word is recognised
flag = 1
print "whatever you want..."
elif (not recognised) and count == 2 and flag == 1:
flag = 0
print "sorry, im afraid i cant do that"
else:
flag = 1
print "second is recognised or whatever you want..."
In my code, I've set a flag if first guess is recognised and incremented the count also. On second guess, I'm just checking the flag and count's value.
Not very relative with your code but, When you could instead get the user input, split it so it turns into a list and compare the first word then the second so it could be something like
user = user_input("> ")
user = user.split()
if user[0] == "look"
if user[1] == "left"
do something
if user[1] == "right"
do something
else
print ("sorry, im afraid i cant do that")
Not sure if this is what your looking for though
Simply, I think you need to learn more code to make things a lot easier for yourself here, though maybe classes are a bit much, and I don't mean this in an insulting way.
As a simple start, I'd suggest using the in keyword rather than ==.
For example:
if "north" in direction:
do something
This will "do something" if the input is North, NORTH, go North, go north please and so on.
To solve your issue therefore your code could use something like this:
input = ("> ")
if "go" in input and not ("north" in input and "south" in input...):
print "That is not a direction you can go in."
And so on. The "and not (...)" section can be rewritten much neater but I wrote it as-is to show what is happening easier.
truthcase = None
directions = ["north", "south", ...]
for i in directions:
if i not in input:
continue
else:
truthcase = True
truthcase = False
if "go" in input and not truthcase:
print something
Hopefully this helps.

Categories

Resources