Here is my code. I can't save more than 1 thing in the list, I don't know why.
The point of the program is to save words (like "banana") and then add a description to it ("yellow"). I'm using Python 2.7
word = []
desc = []
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word.append(raw_input("Word to insert: "))
desc.append(raw_input ("Description of word: "))
main_list()
def look():
up = raw_input("Word to lookup: ")
i = 0
while up != word[i]:
i+1
print "Description of word: ", desc[i]
main_list()
You're not updating the value of i. You're calling i+1 which doesn't really do anything (it simply evaluates i + 1 and discards the result). Do instead i += 1 which seems to work.
Furthermore that's a rather strange approach to creating a dictionary, when you have a built-in data structure for that - the dictionary ({}).
In general, you should not use two list to save the words and their respective descriptions.
This is a classic case for using a dictionary, which will also help you once you have a lot of words, as you do not need to loop over all entries to find the corresponding description.
words = {}
def main_list():
print "\nMenu for list \n"
print "1: Insert"
print "2: Lookup"
print "3: Exit program"
choice = input()
print "Choose alternative: ", choice
if choice == 1:
insert()
elif choice == 2:
look()
elif choice == 3:
return
else:
print "Error: not a valid choice"
def insert():
word = raw_input("Word to insert: ")
desc = raw_input ("Description of word: ")
words[word] = desc
main_list()
def look():
up = raw_input("Word to lookup: ")
print "Description of word: ", words.get(up, "Error: Word not found")
main_list()
Related
I am making a small quiz and trying to learn python. The quiz takes the first answer then loops all the way to the bottom instead of asking the user the rest of the questions. It will print the first question, then ask for the answer , then it will run throught the rest of the code but it won't actually ask for the input or anything like that.
question_1 = ("ex1")
question_2 = ("ex2")
question_3 = ("ex3")
question_4 = ("ex4")
answer = input ("Please type the letter you think is correct: ")
count = 0
# answers
print (question_1)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "b" or answer == "B":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_2)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "a" or answer == "A":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_3)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "d" or answer == "D":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_4)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "c" or answer == "C":
print ("Correct")
count +=1
else:
print ("Incorrect")
You are only asking for one input and then checking that answer against every question.
You will need to add a new input for every question and then check against that input
e.g.
count = 0
print('Q1')
ans1 = input('A/B/C?')
if ans1.lower() == 'c': # Checks for it as a lowercase so no need to repeat it
print('Correct')
count += 1
else:
print('Incorrect')
print('Q2')
ans2 = input('A/B/C?')
if ans2.lower() == 'b':
print('Correct')
count += 1
else:
print('Incorrect')
You need to have the input() function after each question. An input is asked for at each input, writing it once before all the questions won't work.
By the way, you might want to use lists and a loop to get the same done with less code.
I have provided a list of words that will randomly be picked for the game. What it does is to prompt the player to enter an alphabet of the selected word. If the letter provided by the users is found in the selected word, they if be asked if they want to attempt spelling the whole word. if they say yes, then they will be able to do so. Else, they will have to try entering another alphabet.how do I get the output/ results of each user input to be printed as (eg: Outcome: a------) And if the users ended up saying yes to spelling the whole word, how should they be prompt to enter the word?
eg: Do you want spell the word now? (y/n): y
Spell the complete word:
You are correct!
The correct word is albumen
Spell another word? (y/n): y
import random
wordList = ('apple', 'albumen', 'toothpaste', 'enthusiastic')
word = random.choice(wordList)
letter_guess = ""
word_guess = ""
store_letter = ""
count = 1
limit = 5
countLetters = len(word)
choice1 = ("Do you want to spell the word now? (y/n):")
choice2 = ("Spell another word? (y/n):")
choiceY = ("y")
choiceN = ("n")
startGame = print("The word ________ has {} letters. Spell it in 5 tries.".format(countLetters))
while count < limit:
letter_guess = input("Try {} - Current: ________. Your guess? ".format(count))
if letter_guess in word:
print ("yes")
print (input(choice1))
else :
print("no")
count += 1
if choice1 == choiceY:
print (input("Spell the complete word: "))
else:
print (letter_guess)
store_letter += letter_guess
count += 1
while count == limit:
spellFinal = input("Spell the complete word: ")
if spellFinal in word:
print ("You are correct!")
print ("Spell another word? (y/n):")
if choice == "y":
print (startGame)
else:
print('Remaining Words are: ', store_letter)
if spellFinal not in word:
print ("You are incorrect")
print ("The correct word is {}.".format(correct))
You are not collecting the information from your print (input(choice1)) line. You should be assigning it to a variable to be able to compare it later with your choiceY (or you could simply compare the new variable to "y" without having a choiceY variable defined, up to you).
For example:
user_choice = ""
complete_word = ""
if letter_guess in word:
print ("yes\n")
user_choice = input(choice1)
if user_choice.lower() is "y":
complete_word = input("Spell the complete word: ")
#here you compare complete_word with your word variable
else:
print (letter_guess)
store_letter += letter_guess
count += 1
else:
print("no\n")
count +=1
The same applies to the other sections of you code that have the print(input(...)).
Nested ifs can get messy. Perhaps you can consider having a verification function and call that instead.
Hope this helps!
This is my first year programming with Python.
I am trying to create a hangman game.
So my questions: how do I check for
If the person is guessing a letter that has already been guessed and where to include it.
Check they are inputting a valid letter not multiple letters or a number.
What happens if it's a word such as 'Good' and they guess an 'o' at the moment my code breaks if this is the case. Also where on Earth would this be included in the code?
Here is my code
import random
import math
import time
import sys
def hangman():
if guess == 5:
print " ----------|\n /\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike one, the tigers are getting lonely!"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 4:
print " ----------|\n / O\n|\n|\n|\n|\n|\n|\n______________"
print
print "Strike two, pressure getting to you?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 3:
print " ----------|\n / O\n| \_|_/ \n|\n|\n|\n|\n|\n______________"
print
print "Strike three, are you even trying?"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 2:
print " ----------|\n / O\n| \_|_/ \n| |\n|\n|\n|\n|\n______________"
print
print "Strike four, might aswell giveup, your already half way to your doom. Oh wait, you can't give up."
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 1:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n|\n|\n|\n______________"
print
print "One more shot and your done for, though I knew this would happen from the start"
time.sleep(.5)
print "You have guessed the letters- ", guessedLetters
print " ".join(blanks)
print
elif guess == 0:
print " ----------|\n / O\n| \_|_/ \n| |\n| / \\ \n| GAME OVER!\n|\n|\n______________"
print "haha, its funny cause you lost."
print "p.s the word was", choice
print
words = ["BAD","RUGBY","JUXTAPOSED","TOUGH","HYDROPNEUMATICS"]
choice = random.choice(words)
lenWord = len(choice)
guess = 6
guessedLetters = []
blanks = []
loading = ".........."
print "Loading",
for char in loading:
time.sleep(.5)
sys.stdout.write(char)
sys.stdout.flush()
time.sleep(.5)
print "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
print "Great I'm glad to see you have finally woken."
time.sleep(1)
raw_input("Did you have a nice journey? ")
time.sleep(2)
print """
Oh wait, I don't care.
I have brought you to this island simply for my amusment. I also get paid to do this.
"""
time.sleep(2)
print"""
Don't worry this isn't all for nothing.
I'm sure the tigers will enjoy your company.
"""
time.sleep(2)
print"""
Hold on, let us make things interesting.
"""
time.sleep(2)
print "I will let you live if you complete an impossible game!"
time.sleep(2)
print "A game know as hangman!"
time.sleep(2)
print "HAHAHAHAHAH, I am so evil, you will never escape!"
time.sleep(2)
print "Enjoy your stay :)"
time.sleep(1)
print
print "Alright lets begin! If you wish to guess the word type an '!' and you will be prompted"
time.sleep(.5)
print
for s in choice:
missing = choice.replace(choice, "_")
blanks.append("_")
print missing,
print
time.sleep(.5)
while guess > 0:
letterGuess = raw_input("Please enter a letter: ")
letterGuess = letterGuess.upper()
if letterGuess == "!":
print "If you guess the FULL word correcly then you win, if incorrect you die. Simple."
fullWordGuess = raw_input("What is the FULL Word? ")
fullWordGuess = fullWordGuess.upper()
if fullWordGuess == choice:
print "You must have hacked this game"
time.sleep(.5)
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
print "You lost, I won, you're dead :) Have a nice day!"
print "P.S The word was ", choice
break
else:
print
if letterGuess in choice:
location = choice.find(letterGuess)
blanks.insert(location, letterGuess)
del blanks[location+1]
print " ".join(blanks)
guessedLetters.append(letterGuess)
print
print "You have guessed the letters- ", guessedLetters
if "_" not in blanks:
print "Looks like you beat an impossible game! \nGood Job \nI'll show myself out."
break
else:
continue
else:
guessedLetters.append(letterGuess)
guess -= 1
hangman()
I did not really follow your code since there seems to be something wrong with your indentation, and the many print's confused me a little, but here is how I would suggest soving your Questions:
1.1. Create a list of guessed characters:
guessed_chars = []
if(guess in guessed_chars):
guessed_chars.append(guess)
#do whatever you want to do with the guess.
else:
print("You already guessed that.")
#do what ever you want to do if you already guessed that.
1.2 Lets say the word the player has to ges is word = "snake". To get the indices (since a string is just a list of charcters in python, only that it is immutable) where the guessed letter is in the word you could then use something like:
reveal = "_"*len(word)
temp = ""
for i, j in enumerate(word):
if j == guess:
temp += guess
else:
temp += reveal[i]
reveal = temp
print(reveal)
Maybe not fancy but it should work:
if (guess not in [a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z]):
with my suggestion for 1.2 you would just have to check if(word==reveal): no problem with duplicate charcters.
Since I am just a hobbyist there would probably be a more professional way though.
Next time maybe splitting up your question and first looking them up individually would be better, since I am pretty sure that at least parts of your questions have been asked before.
I have everything right in my code (I think) except the part where I get the correct names from my dictionary.
My code is:
studentdirectory = {"Andrew": ["Jane", "John"], "Betsy": ["Ellen", "Nigel"], "Louise": ["Natalie", "Louis"], "Chad": ["Mary", "Joseph"]}
def menu():
print
print ("Enter 1 to retrieve the mother's name of the child.")
print ("Enter 2 to retrieve the father's name of the child.")
print ("Enter 3 to retrieve the name of both parents of the child.")
print ("Enter 0 to quit.")
print
while True:
choice = input("Enter your choice now: ")
if (choice >= 0) and (choice<= 3) and (int(choice) == choice):
return choice
else:
print ("Your choice is invalid. Please try again with options 0 to 3.")
for key in studentdirectory:
mom = studentdirectory[key][0]
dad = (studentdirectory[key][1])
def main():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Enter the name of the child: ")
if studentdirectory.has_key(name):
if choice == 1:
print "The name of the child's mother is ", mom, "."
elif choice == 2:
print "The name of the child's father is ", dad, "."
else:
print "The name of the child's parents are ", mom, " and ", dad, "."
else:
print "The child is not in the student directory."
main()
I would like to keep my code as close to this as possible. I just need help in understanding how to get separate values in the dictionary, because right now for every mom and dad I only get Louise's parents back. How do i fix this??
This is Python Language.
You're getting the values of mom and dad in a loop, but overwriting them each time, so they're always set to the value of the last loop cycle (Louise in your case). You should define them when you need them only instead:
def main():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Enter the name of the child: ")
if studentdirectory.has_key(name):
mom = studentdirectory[name][0]
dad = studentdirectory[name][1]
if choice == 1:
print "The name of the child's mother is ", mom, "."
elif choice == 2:
print "The name of the child's father is ", dad, "."
else:
print "The name of the child's parents are ", mom, " and ", dad, "."
else:
print "The child is not in the student directory."
if studentdirectory.has_key(name):
mom = studentdirectory[key][0]
dad = (studentdirectory[key][1])
And delete the for key in studentdirectory loop part
Because when you get a student name in the main loop.Your original code only return a const mom and dad varible,which comes from your for loop above the main() defination.
And logically
You can only get the parents name after you have the child's name
I'm having trouble inputting scoring in my python quiz code. Here is the script:
#This is the Test script for )TUKT(, Developed by BOT.
print ""
print "Welcome to the Ultimate Kirby Test."
print ""
begin = (raw_input("Would you like to begin?:"))
if begin == "yes":
print ""
print "Alright then! Let's start, shall we?"
print "Q1. What color is Kirby?"
print "1) Black."
print "2) Blue."
print "3) Pink."
print "4) Technically, his color changes based on the opponent he swallows."
choice = input("Answer=")
if choice ==1:
print "Incorrect."
print ""
elif choice ==2:
print "Incorrect."
print ""
elif choice ==3:
print "Tee hee.... I fooled you!"
print ""
elif choice ==4:
score = score+1
print "Well done! You saw through my trick!"
print ""
elif choice > 3 or choice < 1:
print "That is not a valid answer."
print ""
print "Well done! You have finished my test quiz."
print("Score:")
print ""
#End of Script
The error always says
score = score+1 is not defined.
I did not get anywhere researching.
Thanks! Help is very much appreciated!
You forgot to define a variable called score. You can't reference a value that doesn't exist!
Just declare it at the start:
score = 0
In the line score = score + 1, Python goes: 'so I need to create a variable called score. It contains the value of score, plus 1.' But score doesn't exist yet, so an error is thrown.
The varibale score has never been defined. Insert score = 0 as first line of your scirpt.