the question i have sounds complicated but i'm sure its simple. i want my code to remember if the player is male or female and take them down different paths. so males have one story and females have another.
while True:
sex = raw_input ("> ")
if sex.lower() not in ('male', 'female'):
print("What? Try again")
continue
else:
break
if sex.lower() == "male":
print("'Okay Mr %s get ready for the test, it won't be easy'")% name
elif sex.lower() == "female":
print("'Well Ms %s i hope youre ready for the test'")% name
def male_questions():
# all the questions for men
def female_questions():
# all the questions for women
while True:
sex = raw_input ("> ")
if sex.lower() not in ('male', 'female'):
print("What? Try again")
continue
else:
break
if sex.lower() == "male":
print("'Okay Mr %s get ready for the test, it won't be easy'")% name
male_questions()
elif sex.lower() == "female":
print("'Well Ms %s i hope youre ready for the test'")% name
female_questions()
Note that this is a poor implementation of a finite state machine. The link may be able to help you build a much (MUCH) better one.
Also possible (without a state machine) if all you need to do is vary the question:
class Question(object):
def __init__(self, male_q, female_q):
"""Question("Do you have a beard? ", "Purses or wallets? ")"""
self.male = male_q
self.female = female_q
questions = [Question("foo","bar"), Questions("spam","eggs"), ...]
for num,question in enumerate(questions, 1):
print("{}. {}".format(num, question.__dict__.get(sex, "male")))
Related
Here is my approach to simulate a goto sequence. Is there a more eloquent way?
PS: the idea with storing the variable in a class variable was just for fun (because of the .(format()) accessing story.
n=0
while n==0:
print("Whats your height?")
height=input()
print("Whats your age?")
age=input()
class loop:
h=height
a=age
print("Your height is {answer.h}".format(answer=loop()))
print("Would you like to continue?")
answer=input()
if answer=="yes":
++n
print("alright ONE MORE TIME!")
else:
print("see you")
Solution
class Person():
def __init__(self,name, height, age):
self.name = name
self.height = height
self.age = age
while True:
name = input("What's your name?\n")
height = input("What's your height?\n")
age = input("What's your age?\n")
user = Person(name, height, age)
print(f"\nHello {(user.name).title()}, your height is {user.height} and you are" \
f" {user.age} years old!")
answer = input("\nWould you like to continue?('yes' or 'no')\n")
if answer == 'yes':
print("alright ONE MORE TIME!")
continue
else:
print("See you!")
break
This is how I would go about this, although there is no reason to have a class here for what you are trying to accomplish, but since you had it in there I'm assuming you were using it as practice, so I threw in a class here as well.
Edit
Ah you mentioned the class was for fun, not claiming I used class in the best fashion here but it's an improvement for the way you attempted, would definitely look over proper utilization of class.
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 text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
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 get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This 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_charater_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[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
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_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
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_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.
Okay so how could I make my code so instead of putting 1 to 4 I could just put in a keyword like "Freezing" or "Froze" How could i put a keyword searcher in my code, all help is immensely appreciated thank you in advanced :)
def menu():
print("Welcome to Kierans Phone Troubleshooting program")
print("Please Enter your name")
name=input()
print("Thanks for using Kierans Phone Troubleshooting program "+name +"\n")
def start():
select = " "
print("Would you like to start this program? Please enter either y for yes or n for no")
select=input()
if select=="y":
troubleshooter()
elif select=="n":
quit
else:
print("Invalid please enter again")
def troubleshooter():
print("""Please choose the problem you are having with your phone (input 1-4):
1) My phone doesn't turn on
2) My phone is freezing
3) The screen is cracked
4) I dropped my phone in water\n""")
problemselect = int(input())
if problemselect ==1:
not_on()
elif problemselect ==2:
freezing()
elif problemselect ==3:
cracked()
elif problemselect ==4:
water()
start()
def not_on():
print("Have you plugged in the charger?")
answer = input()
if answer =="y":
print("Charge it with a diffrent charger in a diffrent phone socket. Does it work?")
else:
print("Plug it in and leave it for 20 mins, has it come on?")
answer = input()
if answer=="y":
print("Are there any more problems?")
else:
print("Restart the troubleshooter or take phone to a specialist\n")
answer=input()
if answer =="y":
print("Restart this program")
else:
print("Thank you for using my troubleshooting program!\n")
def freezing():
print("Charge it with a diffrent charger in a diffrent phone socket")
answer = input("Are there any more problems?")
if answer=="y":
print("Restart the troubleshooter or take phone to a specialist\n")
else:
print("Restart this program\n")
def cracked():
answer =input("Is your device responsive to touch?")
if answer=="y":
answer2 = input("Are there any more problems?")
else:
print("Take your phone to get the screen replaced")
if answer2=="y":
print("Restart the program or take phone to a specialist\n")
else:
print("Thank you for using my troubleshooting program!\n")
def water():
print("Do not charge it and take it to the nearest specialist\n")
menu()
while True:
start()
troubleshooter()
Since you want the user to type in the description of the phone's problem, you probably want a list of problems and keywords associated with those problems. The following program shows how you might arrange such a database and how to search it based on the user's input. There are faster alternatives to this solution (such as indexing the database), but this basic implementation should be sufficient for the time being. You will need to provide further code and information on how to resolve problems, but answers to your previous question should help direct you in that regard.
#! /usr/bin/env python3
# The following is a database of problem and keywords for those problems.
# Its format should be extended to take into account possible solutions.
PROBLEMS = (('My phone does not turn on.',
{'power', 'turn', 'on', 'off'}),
('My phone is freezing.',
{'freeze', 'freezing'}),
('The screen is cracked.',
{'cracked', 'crack', 'broke', 'broken', 'screen'}),
('I dropped my phone in water.',
{'water', 'drop', 'dropped'}))
# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))
def main():
"""Find out what problem is being experienced and provide a solution."""
description = input('Please describe the problem with your phone: ')
words = {''.join(filter(str.isalpha, word))
for word in description.lower().split()}
for problem, keywords in PROBLEMS:
if words & keywords:
print('This may be what you are experiencing:')
print(problem)
if get_response('Does this match your problem? '):
print('The solution to your problem is ...')
# Provide code that shows how to fix the problem.
break
else:
print('Sorry, but I cannot help you.')
def get_response(query):
"""Ask the user yes/no style questions and return the results."""
while True:
answer = input(query).casefold()
if answer:
if any(option.startswith(answer) for option in POSITIVE):
return True
if any(option.startswith(answer) for option in NEGATIVE):
return False
print('Please provide a positive or negative answer.')
if __name__ == '__main__':
main()
You are looking for an enum
from enum import Enum
class Status(Enum):
NOT_ON = 1
FREEZING = 2
CRACKED = 3
WATER = 4
Then in your if checks, you do something like this:
if problemselect == Status.NOT_ON:
...
elif problemselect == Status.FREEZING:
...
First off. My code:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
I am not that good at coding, so this is probably something that I have done really wrong
This post seems a bit duchy, since I almost just have code,
but I have absolutely no idea on how to make this work.
What the code looks like without shortening:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
EDIT: I see that it might be hard to see what I'm asking.
I'm wondering how I can shorten my original code
If all your elif blocks have the same pattern, you can take advantage of this.
You can create a dictionary for the text you want to print and then do away with the conditionals.When it comes to choosing which one to print, you simply fetch the relevant text using its corresponding key. You use the get(key, default) method. If there is no key in the dictionary, the default value will be returned. For example,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
I found a solution, just stop using elif entirely.
Example:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")