really new to python and stack overflow, and I'm currently trying out a choose your own adventure game. I'm already a bit familiar with if-else statements but I need a little help in a specific mechanic I want in the game. Basically, the character will have a certain set of choices so like:
print('[a]Wash the Dishes')
print('[b]Feed the Dog')
print('[c]Brush Teeth')
input = choice('What should I do? ')
So how could I make it that once the character inputs their choice, it'll show the same set of options, but now removing the one already selected?
game_choice = {'a':"Wash the Dishes",'b':"Feed the Dog",'c':"Brush Teeth"}
# printing the choices to user
for key in game_choice:
print(f"[{key}]: {game_choice[key]}")
# Iteratively asking user for input
while(len(game_choice)>0):
choice = input('What should I do? ')
if choice in game_choice:
print(game_choice[choice])
game_choice.pop(choice)
else:
print("You Entered wrong choice, Please try again")
Above we created a Dict() to store all the options and values in key pair groups.
You can use a similar approach to do build your game.
choices = {'a': 'Wash the Dished', 'b': 'Feed the Dog', 'c': 'Brush teeth'}
def print_choices():
for key in choices:
print(f'[{key}]: {choices[key]}')
# by using f'' you can use Curly Braces to call variables like what i did here
# instead of doing .format or 'text' + variable + 'text' or ...
def choice(txt):
# your code
input_value = input(txt)
choices.pop(input_value, None)
# None here causes the dict to NOT raise an error if the key doesn't exist in the dictionary
print_choices()
input_value = choice('What should I do? ')
This answer is based on considering you already know what a dictionary is in python.
Also if you wanted to have a message shown to the player if their input is not VALID you could do this instead:
def choice(txt):
# your code
input_value = input(txt)
if input_value not in choices:
print("Invalid Input")
else:
choices.pop(input_value)
Related
I'm currently working on a guessing game assignment. The assignment uses a dictionary to store the course name which is the key and the course number which is the value. The user guesses the course number of the course name given. If the value matches the key then it should print "correct!" and vice versa.
I have gotten the program to display the keys one at a time with an input statement separating them. I've gotten the correct/incorrect counters working. I'm not able to get an if statement working which is supposed to check if the value matches the key. It prints incorrect every time regardless of if the answer is correct. I realize there's probably something wrong with the condition of the if statement because i'm not really sure how to extract one value at a time.
Here's what I have so far:
# Mainline
def main():
programming_courses={"Computer Concepts":"IT 1025",\
"Programming Logic":"IT 1050",\
"Java Programming":"IT 2670",\
"C++ Programming":"IT 2650",\
"Python Programming":"IT 2800"}
print ("Learn your programming courses!\n")
correct=0
incorrect=0
v=0
# Game Loop
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses.values():
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
# Display correct and incorrect answers
print ("You missed ",incorrect," courses.")
print ("You got ",correct," courses.\n")
# Entry Point
response=""
while (response!="n"):
main()
response=input("\n\nPlay again?(y/n)\n# ")
Your problem is here:
if answer != programming_courses.values():
programming_courses.values() is a list of all the values in the dictionary. If you don't understand what's happening in your program, it's really helpful to just print stuff out and see if it looks like what you expect.
What you want is the specific value for the key you're on right now, which you need to look up from the dictionary like so:
if answer != programming_courses[key]:
Also, iterating over a dict gives you the keys by default, so you can just say:
for key in programming_courses:
You don't need to use .keys() there.
Your problem is when you are checking your dict. Currently your code is comparing the answer to a list of all the values in the dict:
out[]:
dict_values(['IT 1025', 'IT 1050', 'IT 2670', 'IT 2650', 'IT 2800'])
If you change to the following it works, by taking the specific value from the dict with the given key:
for key in programming_courses.keys():
print(key)
answer = input("Enter the Course Number: ")
if answer != programming_courses[key]:
print("Incorrect")
incorrect += 1
else:
print("Correct!")
correct += 1
you could try this
if answer != programming_courses[key]:
I am writing a English dictionary using python 2. I created a dictionary. for example, "home" and "horse" in the dictionary's key. If the user types "ho", "home" and "horse" will come. I put these in the bottom line. But when the user selects word 1, I want to call the key and value in the dictionary that I set first. How can I do it?
myEngDict = {"horse": "The horse (Equus ferus caballus) is one of two extant subspecies of Equus ferus","home": "the place where one lives permanently, especially as a member of a family or household."}
def Words():
word_List = []
count = 0
search_words = raw_input("Please enter a search term: ")
for i in myEngDict.keys():
if i.startswith(search_words):
count+=1
word_List.append(i)
print "{}{}{}".format(count,".", i)
else:
pass
choose = input("Which one?")
For example, if "home" comes out first, user choose 1:
Program display:
home: the place where one lives permanently, especially as a member of a family or household.
First, you should use raw_input in that final line. Then you need to look up the provided in the word_List.
while True:
try:
choose = int(raw_input("Which one?"))
# Keep the key as a separate variable for faster reference
key = word_List[choose - 1]
# Use labels with the format function. It's easier to read and understand
print '{label}: {text}'.format(label=key, text=myEngDict[key])
# Be sure to have a break or return on success.
return
except ValueError:
# If someone provides 'cat', it will raise an error.
# Inform the user and go back to the start.
print 'Please provide an integer'
except IndexError:
# The user has provided a value above the length of word_List or
# less than one. Again, inform the user and go back to start.
print 'You must enter a number between 1 and {c}'.format(c=len(word_List))
By not changing to much your code, you can just add a print statement after choose in your function at the same identation:
print ("%s : %s"%(word_List[choose-1], myEngDict[word_List[choose-1]]))
I am currently writing a code for my GCSE coursework and I am kind of stuck with my for loop which also contains an if-else statement.
I have done a code similar to this earlier in the program and it works perfectly fine but for some reason this part doesn't and I was wondering if someone could help me.
What I am trying to do is make a quiz type program and the part that I need help with is choosing the subject that the user wants to do.
The user has to type in their preferred subject but if they type the subject in wrong, or type in something invalid, then the program should allow the user to type it in again.
So far, if you type in a subject correctly the first time, the program will proceed to the next stage.
However, if you type it incorrectly the first time, it will ask the user to try again. But if you type it in correctly the second time, it will again ask the user to try again. Instead of having the program make the user type the subject again, even though it should've been valid the when they typed it in correctly, I want the program to proceed to the next stage.
Available subjects:
subjects = []
algebra = ("algebra")
computing = ("computing")
subjects.append(algebra)
subjects.append(computing)
Part that I need help with:
with open("student_file.csv", "a+") as studentfile:
studentfileReader = csv.reader(studentfile, delimiter = ',')
studentfileWriter = csv.writer(studentfile, delimiter = ',')
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
ChosenSubject.lower()
for i in range(2):
if ChosenSubject in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject == input("What subject would you like to do?")
ChosenSubject.lower()
if ChosenSubject in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
In the else block, perhaps you'd want to replace the '==' with '='.
Also do you want to give the user just two tries or keep asking them until they answer correctly? (The latter is what I inferred from your question, for that I'd recommend using continue)
The for loop just iterates over a collection of objects. Consider a list my_list = ['a', 'b', 'c']. On each iteration over my_list using for loop, it fetches one of the elements in order without repetition. range(2) is equivalent to [0, 1].
Try this:
print("Available subjects:\n-Algebra\n-Computing\n")
for i in range(2):
# `i` is 0 on first iteration and 1 on second. We are not using `i` anywhere since all we want is to loop :)
chosen_subject = input("What subject would you like to do? ")
if chosen_subject.lower() in subjects:
print("\n")
break
if chosen_subject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This is not an optimal solution, but since your learning I will try to keep it as close as your solution. Your problem is that calling ChosenSubject.lower() does not change the actual value in ChosenSubject.
Here is a working example:
print("Available subjects:\n-Algebra\n-Computing\n")
ChosenSubject = input("What subject would you like to do? ")
subjects = ["algebra", "computing"]
for i in range(2):
if ChosenSubject.lower() in subjects:
print("\n")
break
else:
print("\nPlease try again.")
ChosenSubject = input("What subject would you like to do?") #not '=='
if ChosenSubject.lower() in subjects:
print("working")
else:
print("You keep typing in something incorrect.\nPlease restart the program.")
This from the doc:
This method returns a copy of the string in which all case-based
characters have been lowercased.
I am relatively new to python, and I just started learning how to use classes. This is the first program I've made where I've tried to integrate them, but I'm coming up with a small issue I can't seem to fix, and I think it has to do with lists. The code is as follows:
(The topic is getting the user to choose what type of seat to purchase).
class SeatBooking:
def __init__(self, seat):
self.seat = seat
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
while True:
if self.seat not in possible_types:
print("Sorry, but this is not a valid answer. Please try again!")
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("You have chosen to book a {} ticket.".format(self.seat))
confirmation = str(input("Please confirm with 'Yes' or 'No': ")).lower()
if confirmation == "yes":
print("Excellent decision! Ready to continue")
print("=" * 170)
break
elif confirmation == "no":
self.seat = str(input("What type of ticket would you like? The possible types are: {} "
.format(possible_types)))
else:
print("That doesn't seem to be a valid answer.")
Here is the main file (to execute the different classes I'll make):
import type_seat
# Choose the seat to book
print("=" * 170)
print("Welcome to Etihad! This program can help you organize your flight, payments and usage of miles!")
possible_types = []
possible_types.extend(["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"])
possible_types = " ".join(possible_types)
seat_type = str(input("What type of ticket would you like? The possible types are: {}. "
.format(possible_types)))
type_seat.SeatBooking(seat_type)
The problem I have is that I seem to be able to enter certain letters and it doesn't count them as an error even though they're not one of the available seats. For example, when I enter the letters "h" or "s", my error checking part of the code doesn't respond to it, but when I enter the letter "b" or random words like "try" it does. It doesn't seem to be completely random though, and it seems to only happen with letters or parts of the first 3 'items' in the possible_types[] list. However, I haven't tested this fully. This is why I thought it had something to do with lists, so if anyone knows what's causing this, I'd really appreciate it if they could help me resolve this and perhaps help me from repeating this mistake in the future!
Note, for the lists I am using .join, but I also tried str().
You don't have a list, you are testing characters against one long string:
possible_types = " ".join(possible_types)
The letters h and s are in that string (in the words High_Economy and Business, respectively), but the sequence try doesn't appear anywhere in the string.
If you only wanted to allow whole words to match, you'd need to leave possbile_types a list, or ideally convert it to a set (as sets allow for fast membership testing). You can define the list, no need for list.extend() here:
possible_types = ["Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"]
or make it a set by using {...}:
possible_types = {"Low_Economy", "Standard_Economy", "High_Economy",
"Business", "First", "Residence"}
Do not join this into a string, just test directly against the object:
if self.seat not in possible_types:
If you still need to show the values to a user in an error message, join the values then, or store the str.join() result in a different variable for that purpose.
Note that you shouldn't deal with user input validation in the class __init__ method. Leave user interaction to a separate piece of code, and create instances of your class after you validated. That way you can easily swap out user interfaces without having to adjust all your data objects too.
possible_types = " ".join(possible_types)
Above statement will create one string as "Low_Economy Standard_Economy High_Economy Business First Residence".
Now you are doing
if self.seat not in possible_types:
This will check for a particular character in the string present or not. In your case you are finding 'h' which is present and 'try' which isn't.
Your program will work if you remove this statement
possible_types = " ".join(possible_types)
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 6 years ago.
Improve this question
The user should insert a name as an input and then confirm with a yes or no (or any of its derivatives) if the 3 worded name includes a middle name or not. So far, I've gotten the loop to work if the answer is yes; however it keeps looping the question if the answer is no.
The purpose: if the answer is yes, the program will understand its a 3 worded name with a middle name and therefore execute naming combinations with the middle name; if its no, the program will understand its a 3 worded name with a second last name instead of a middle name and therefore execute naming combinations accordingly.
Please note I have exluded a lot of the code for sharing purposes.
What I'm I doing wrong? My question is in regards to the elif part of the loop.
print ('enter name')
providedname = input ()
while providedname != 'quit':
if len(providedname.split())==4:
pass
elif len(providedname.split())==3:
print ('Does the name include a middle name or middle initial? Please type yes or no:')
userinput = input()
if userinput.startswith ('ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'):
firstname, middlename, lastname = providedname.split()
elif userinput.startswith ('no' or 'No' or 'NO' or 'na' or 'Na' or 'NA'):
firstname, lastname, secondlastname = providedname.split()
else:
pass
print ('enter name or type quit or q to exit')
providedname=input()
continue
You can't use or like that. It makes sense in English, but it doesn't work in Python. One way to express what you're doing is with a mini for loop along with the any function, like so:
if any(userinput.startswith(string) for string in ['ye', 'Ye', 'YE', 'ya', 'Ya', 'YA']):
It reads almost like English if you shuffle the word order around a bit:
If the user input starts with any of the strings in this list...
Even better is to lowercase the input string first. Then you don't have to check so many combinations.
userinput = input().casefold() # Python 3.3+
userinput = input().lower() # Earlier
if any(userinput.startswith(string) for string in ['ye', 'ya']):
As it happens, startswith can also accept a list of strings. You can actually ditch the all the any() machinery and have simply:
if userinput.startswith(('ye', 'ya')):
(Thanks to #kindall for that tip.)
So, just run this in the interpreter
>>> 'ye' or 'Ye' or 'YE' or 'ya' or 'Ya' or 'YA'
'ye'
Your startswith isn't working the way you think it does.
Other than that, you can shorten that statement up if you lowercase your strings.
Runnable example
while True:
providedname = input ('enter name or type quit or q to exit: ')
if providedname in {'quit', 'q'}:
break
names = providedname.split()
if len(names) == 4:
pass
elif len(names) == 3:
userinput = input('Does the name include a middle name or middle initial? Please type yes or no:')
if userinput[:2].lower() in {'ye', 'ya'}:
firstname, middlename, lastname = names
elif userinput[:2].lower() in {'no' , 'na'}:
firstname, lastname, secondlastname = names
else:
pass
print(firstname, lastname)
It LOOKS as though you're missing the ending ' on the print command inside your elif ('Does the name include....), causing the rest of it to be taken as more text input. Try adding that ' and see if that helps!
First, you could have more complex names, for example, "Oscar De La Hoya", which would skip because the name would have length = 4. Ignoring 'difficult names', the next thing would be to work on cleaning the user's input. I would clean the user's input like so:
userinput = input().lower().strip()
This way you can make is simpler for yourself and also more readable.
Now you can do:
if userinput == 'yes':
firstname, middlename, lastname = providedname.split()
else:
firstname, lastname, secondlastname = providedname.split()
Finally (as the other answer states), if a 'valid' input is given, you'll want to break out of the while loop with a break.
You have 2 main problems (ignoring all the syntax errors assuming that they are just here on your question but your actual code is OK)
First you are never breaking out of the while loop, you must use the break statement anywhere you want to exit the loop.
Second you are overwriting the providedname at the end of the loop, that will leave you without the actual name, the variable will be quit even after the correct name was provided.