I apologize for how simplistic this may be, but I am a little confused looking at one part of this code.
# Geek Translator
# Demonstrates using dictionaries
geek = {"404": "clueless. From the web error message 404, meaning page not found.",
"Googling": "searching the Internet for background information on a person.",
"Keyboard Plague": "the collection of debris found in computer keyboards.",
"Link Rot" : "the process by which web page links become obsolete.",
"Percussive Maintainance" : "the act of striking an electronic device to make it work.",
"Uninstalled" : "being fired. Especially popular during the dot-bomb era."}
choice = None
while choice != "0":
print(
"""
Geek Translator
0 - Quit
1 - Look Up a Geek Term
2 - Add a Geek Term
3 - Redefine a Geek Term
4 - Delete a Geek Term
"""
)
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# get a definition
elif choice == "1":
term = input("What term do you want me to translate?: ")
if term in geek:
definition = geek[term]
print("\n", term, "means", definition)
else:
print("\nSorry, I don't know", term)
# add a term-definition pair
elif choice == "2":
term = input("What term do you want me to add?: ")
if term not in geek:
definition = input("\nWhat's the definition?: ")
geek[term] = definition
print("\n", term, "has been added.")
else:
print("\nThat term already exists! Try redefining it.")
# redefining an existing term
elif choice == "3":
term = input("What term do you want me to redefine?: ")
if term in geek:
definition = input("What's the new definition?: ")
geek[term] = definition
print("\n", term, "has been redefined.")
else:
print("\nThat term doesn't exist! Try adding it.")
# delete a term-definition pair
elif choice == "4":
input("What term do you want me to delete?")
if term in geek:
del geek[term]
print("\nOkay, I deleted", term)
else:
print("\nI can't do that!", term, "doesn't exist in the dictionary.")
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
input("\n\nPress the enter key to exit.")
I understand how all of this works with the exception of the print() function after choice = input(Choice: ")
Why is that there? If I remove it, nothing changes (as far as I can tell), so I was curious about its significance.
print() with no parameters prints a newline. The point is to show a blank line in the terminal output.
It prints a new line (which is visible as an empty line in the console output).
An empty print() outputs a newline, so maybe the only reason it's there is to add a newline?
Related
I've been set a task by my lecturer to complete a couple challenges to help improve my understanding of dictionaries and the concepts behind them. I've been able to complete the first task quite easily but I'm quite stuck with the second task. The first task was to create a 'Who's your Daddy? program'.
The challenge states: Write a Who's Your Daddy program that lets the user enter the name of a male and produces the name of his father. (You can use celebrities, fictional characters, or even historical figures for fun.) Allow the user to add, replace, and delete son-father pairs.
I was able to create this challenge with only one issue where I could only replace a father of a son and not both.
The second challenge states: Improve this program by adding a choice that lets the user enter a name and get back a grandfather. Your program should still only use one dictionary of son-father pairs. Make sure to include several generations in you dictionary so that a match can be found.
I thought that I could maybe use a dictionary nested in a dictionary and researched that, but it only stated one dictionary. I then thought could I use a tuple within a dictionary and then access this tuple when the user requests a son and their grandfather, but have not had much luck with this either, so I decided to come on here.
So now I wonder, how can I add grandfathers to each of the pairs, can you add a second value to a key in a dictionary?
names = { "henry" : "michael",
"louis" : "jason",
"owen" : "justin",
"jake" : "glynn",
"adam" : "mark",
}
choice = None
while choice != "0":
print(
"""
Welcome to the Who's Your Daddy? program.
You can find out a father of the names listed,
you can then add, replace and delete a son/father pair.
0 - Exit
1 - List sons and their fathers
2 - Add a pair
3 - Replace a pair
4 - Delete a pair
"""
)
choice = input("Choice: ")
#exit
if choice == "0":
print("Goodbye")
#List sons
if choice == "1":
print(*names.keys(), sep='\n')
son_choice = input("Who's father would you like to know the name of?: ")
if son_choice in names:
print(names[son_choice])
else:
print("That name is not in the list!")
#Add a pair
elif choice == "2":
son_add = input("Enter the name of someone: ").lower()
if son_add not in names:
father_add = input("Now enter the name of their father: ").lower()
names[son_add] = father_add
print("That pair has been added")
else:
print("That name already exists!")
#Replace a pair
elif choice == "3":
son_replace = input("What name do you want to replace?: ")
if son_replace in names:
father_replace = input("Enter the name of their father: ")
names[son_replace] = father_replace
print("The pair has been replaced")
else:
print("That name doesn't exist, please add it first!")
#Delete a pair
elif choice == "4":
son_delete = input("What name do you want me to delete?: ")
if son_delete in names:
del names[son_delete]
print("Pair deleted!")
else:
print("That pair does not exist!")
else:
print("Sorry, that's an invalid choice!")
input("\n\nPress the enter key to exit!")
With the help of Ronald and a little common sense I've now solve this issue.
For a grandfather to be found, I needed to create a new son father pair where the son's father would be a son already in the list. For example, if I create a new pair, with the son being called tom and the father being called henry. I can then use the find the grandfather function to show that tom's grandfather would be michael.
#Find a grandfather
elif choice == "5":
grandson = input("Please enter the son and I will find the grandfather: ").lower()
if grandson in names:
father = names[grandson]
if father in names:
grandfather = names[father]
print("The grandfather of " + grandson + " is " + grandfather)
else:
print(father + " is not in the dictionary")
else:
print(grandson + " is not in the dictionary")
This is the code I created, however, how would I make this work for several generations, or is that already accomplished by this piece of code.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm trying to create a text-based game. I've made a basic/generic intro and now it's getting long so I want to create a new file so that I can add things like armor and weapons. When I went to try to import 'my_character' it gave me an error so I went to research this problem and I found this, so I tried it. I just got an error message saying it wasn't define (similar to the error below). This is the intro part named intro:
# Date started: 3/13/2018
# Description: text based adventure game
import time
def display_intro():
print('It is the end of a 100 year war between good and evil that had\n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n'
+ 'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n'
+ 'wed and had you. \n')
time.sleep(3)
def main():
display_intro()
main()
gen = input('\nYour mother had a [Boy or Girl]: ')
name = input("\nAnd they named you: ")
print("You are a {} named {}".format(gen, name))
chara_class = None
# Assigning points Main
my_character = {
'name': name,
'gender': gen,
'class': chara_class,
'strength': 0,
'health': 0,
'wisdom': 0,
'dexterity': 0,
'points': 20
}
# This is a sequence establishes base stats.
def start_stat():
print("\nThis is the most important part of the intro")
time.sleep(3)
print("\nThis decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category: Strength, Health, Wisdom, or Dexterity.\n"
)
def add_character_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much? "))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character['points'] -= amount
else:
print("That attribute doesn't exist! \nYou might have to type it in all lowercase letters!!!")
def remove_character_points():
attribute = input("\nWhich of the catagories do you want to remove from? ")
if attribute in my_character.keys():
amount = int(input("How many points do you want to remove? "))
if amount > my_character[attribute]:
print("\nYou are taking away too many points!")
else:
my_character[attribute] -= amount
my_character['points'] += amount
else:
print(
"That attribute doesn't exist! \nYou might have to type it in all lowercase letters!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_character_points()
elif Continue == "n" or "No" or "no":
main()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_character_points()
elif choice == "2":
remove_character_points()
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
def story_str():
print(
"\nYou were always a strong child who easily do physical labor and gain lots of muscle."
)
time.sleep(3)
print("\nYou regularly trained with your dad who was also a skilled swordsman.")
time.sleep(3)
print("\nAs you grew into an adult, you're swordsmanship improved drastically.")
time.sleep(3)
print("\nOnce old enough, you joined the local guild as a warrior.")
time.sleep(3)
def story_dex():
print("\nYou were a sly child. You would always be stealing from other people and with"
+ "\nconstant practice you became proficient at thieving.")
time.sleep(3)
print("\nCombined with the skill of knives and short-blades, you became an extremely deadly assassin."
)
time.sleep(3)
print("\nOnce old enough, you joined the local guild as an assassin.")
time.sleep(3)
def story_wis():
print("\nYou grew up as a very intellegent child. You read books everyday and realized that magic"
+ "is the best offensively and defensively.")
print("\nYou grew up and attended the best magic school avalible and graduated."
)
print("\nYou soon went to the local guild and joined as a wizard.")
run_story = False
while run_story:
if my_character['strength'] >= 13:
story_str()
chara_class = 'Warrior'
run_story = True
else:
continue
if my_character['dexterity'] >= 13:
story_dex()
chara_class = 'Assassin'
run_story = True
else:
continue
if my_character["wisdom"] >= 13:
story_wis()
chara_class = 'Mage'
run_story = True
else:
continue
The command I have typed on part1 is to try to import my_character is:
from intro import my_character
print(my_character)
I have been trying to import my_character but it comes up as:
Traceback (most recent call last):
File "C:/Users/user/Desktop/part1.py", line 5, in <module>
my_character
NameError: name 'my_character' is not defined
The original file was named "intro" and the new one is named "part1". Do I need to do the 'if name == "__main"' thing? If so, what does that do?
Check for:
1) is the file name my_character.py
2) you have imported it as my_character
3) my_character is in the main python directory (if you are importing in interpreter)
I'm trying to create a menu for my application, the menu has 4 options and each of these options should return with the correct information when the user has entered the chosen value. i keep getting an error with the Elif statements.
I am a newbie so please understand where am coming from.
much appreciation.
when i indent the while ans: i will receive an error says invalid syntax after indenting the elif ans==2.
elif ans==2 <--- this error keeps saying indention block error or syntex invalid when i indent it.
def print_menu(self,car):
print ("1.Search by platenumber")
print ("2.Search by price ")
print ("3.Delete 3")
print ("4.Exit 4")
loop=True
while loop:
print_menu()
ans==input("Please choose from the list")
if ans==1:
print("These are the cars within this platenumber")
return platenumber_
while ans:
if ans==2:
elif ans==2:
print("These are the prices of the cars")
return price_
elif ans==3:
print("Delete the cars ")
return delete_
elif ans==4:
return Exit_
loop=False
else:
raw_input("please choose a correct option")
You have a while loop without a body. Generally speaking, if there is an indentation error message and the error is not on the line mentioned, it's something closely above it.
loop=True
while loop:
print_menu()
ans = int(input("Please choose from the list"))
if ans==1:
print("These are the cars within this platenumber")
# return some valid information about plate numbers
elif ans==2:
print("These are the prices of the cars")
# return some valid information about pricing
elif ans==3:
print("Delete the cars ")
# Perform car deletion action and return
elif ans==4:
# I am assuming this is the exit option? in which case
# return without doing anything
else:
# In this case they have not chosen a valid option. Send
# A message to the user, and do nothing. The while loop will run again.
print("please choose a correct option")
Also, your code is a bit confusing to me. It looks like you're going to return car_ no matter what, which means your loop will only execute once. Also, = is assignment and == is equality. Be careful.
Hi I have this project of Mad libs but I donĀ“t know how to make a function that ask the user what level of difficulty between easy, medium or hard they want, and depending on their answer redirect them to the desired level of mad libs. This is what I have so far. Thanks.
parts_of_speech_words = ["VERB","PLACE","ADJECTIVE","NOUN","PLURALNOUN","ADVERB"]
level_easy = """I __VERB__ to go to the __PLACE__
but I don't go in the __ADJECTIVE__
I am __ADJECTIVE__ of the __NOUN__
and getting __VERB__ by a __NOUN__."""
level_medium = """Begging to hear __NOUN__
My ears remain __ADJECTIVE__
__NOUN__ for signs
my __NOUN__ remain __VERB__
Yet __NOUN__still VERB."""
level_hard = """I __VERB__ you without __NOUN__
how, or when, or from where,
I love you __ADVERB__,
without __PLURALNOUN__ or pride;
So I love you because I know
no other way that this:
Where I does not VERB, nor you,
so close that your NOUN
on my chest is my hand,
so close that your NOUN close
as I fall ADJECTIVE."""
greeting = raw_input ("Welcome to mad libs, What's your name? ")
prompt = raw_input ("Select your level: easy, medium or hard: ")
def entry_level_prompt (variable_level):
easy = level_easy
medium = level_medium
hard = level_hard
for e in variable_level:
if prompt == easy:
return level_easy
print level_easy
if prompt == medium:
return level_medium
print level_medium
if prompt == hard:
return level_hard
print lever_hard
print "Ok %s you chose the %s level" % (greeting , prompt)
print entry_level_prompt (variable_level)
def parts_of_speech (words_string, list_of_part_of_speech):
for pos in list_of_part_of_speech:
if pos in words_string:
return pos
return None
def play_mad_libs (split_string, list_of_part_of_speech):
replaced = []
split_string = split_string.split ()
for words_string in split_string:
replacement = parts_of_speech (words_string, list_of_part_of_speech)
if replacement != None:
user_input = raw_input ("Type in a: " + replacement + " ")
words_string = words_string.replace (replacement, user_input)
replaced.append(words_string)
else:
replaced.append(words_string)
replaced = " ".join(replaced)
return replaced
print play_mad_libs (entry_level_prompt, parts_of_speech_words)
You have a bug in your code. You are calling entry_level_prompt(variable_level) but variable_level does not exist outside of the method scope.
To control the difficulty, you can create a method called get_difficulty()
def get_difficulty():
choice = ""
while choice not in ('easy', 'medium', 'hard'):
choice = raw_input("choose your difficulty: ")
if choice == "easy":
return level_easy
elif choice == "medium":
return level_medium
elif choice == "hard":
return level_hard
else:
print("Invalid choice...")
You've confused the selector -- "easy", "medium", or "hard" -- with the variable you want to return -- level_easy, level_medium, or level_hard. You cannot use the variable prompt for both purposes at the same time.
I recommend that you keep variable prompt as you started: it holds the user input. Then, simply test it and return the needed script:
if prompt == "easy":
return level_easy
elif prompt == "medium"
return level_medium
elif prompt == "hard"
return level_hard
else:
"Please enter easy, medium, or hard for the level."
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...