I wrote two different sequences, how do I get them to print in order? Do I need to use a loop? If so how would i do that?
name = input("Who Goes There?")
print("Ah" , name , "-I'll Call You Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
It's difficult to figure out what you're asking, particularly since there is no syntax error in that code. I'm assuming you're running it with the Python interpreter, yes(1)?
In any case, you only need a loop if you want to do things more than once. If all you want to do is execute some statements in sequence, you write them in the order desired, exactly as you have done, as the following transcript shows:
pax:~> python3 testprog.py
Who Goes There?pax
Ah pax -I'll Call You Ted Instead
Ted, Dont You Miss The Water?yes
What About The Seagulls?no
yes no
If the order of those actions is different to what you need, simply rearrange the statements into the order you do need.
(1) The reason I ask is that you do get a syntax error if, for example, you try to run it with a shell:
pax:~> bash testprog.py
testprog.py: line 1: syntax error near unexpected token `('
testprog.py: line 1: `name = input("Who Goes There?")'
But, if that's the case, you're just using the wrong tool to run it (possibly implicitly if it's executable and you just run it with ./testprog.py. You may benefit from the use of a shebang line to specify a different interpreter in that case, something like (the actual line may be different on your system but the concept is the same):
#!/usr/bin/env python3
name = input("Who Goes There?")
print("Ah" , name , "-I'll Call You Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
If you write a script - then run the entire script - the order should execute top-down.
name = input("Who Goes There?")
print("Ah" , name , "-I'll Call You Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
you can do this.
name = input("Who Goes There?")
print(f"Ah {name} I'll call you Ted Instead")
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
or if you want you can do this too
name = input("Who Goes There?")
print("Ah {} I'll call you Ted Instead").format(name)
water = input("Ted, Dont You Miss The Water?")
seagulls = input("What About The Seagulls?")
print(water, seagulls)
Related
I am making a text adventure game while i get stuck in 'NameError: name 'inputwhichpower' is not defined. Did you mean: 'inputwhichpet'?' inputwhichpower and inputwhichpet is a input. I have no idea what is causing the problem and how to fix it. my code is so big, so i am just uploading the code where the problem is facing on.
if inputcattype=="fire":
inputwhichpower = input("Choose a power. [Fire Balls]")
if inputwhichpower=="fire balls":
print("Fire balls come out of nowhere and hit Slenderbot.")
print("It took 3 Damage. It died.")
Your variable inputwhichpower is out of the second if statement's scope.
Here's the solution, you jsut have to specifiy that there IS a variable like that:
inputwhichpower = "";
if inputcattype=="fire":
inputwhichpower = input("Choose a power. [Fire Balls]")
if inputwhichpower=="fire balls":
print("Fire balls come out of nowhere and hit Slenderbot.")
print("It took 3 Damage. It died.")
I'm taking the example from the book "Conceptual Programming with Python".
Some introduction to the problem that the code is aimed at solving:
Example: Creating a Knowledge Base
As a second example for OOP, we are going to implement a simple guessing game! But this game will be able to learn from experience, that is, you will be able to teach the program as you play. For this example, we will create a knowledge base of animals. The user will think of an animal, and the computer will have to figure out which animal it is by asking you (sensible) questions about that animal; the answer will be either yes or no. If it fails to guess correctly the animal, the program will ask you what would be a sensible question to be able to find the right solution next time!
Example 1: The computer only knows how to distinguish between a bird or a cat depending on whether it has 4 legs or not. That is, the initial knowledge base only contains these two animals and one single question.
You: Think of a cat.
Computer: Does it have 4 legs?
You: Yes
Computer: Were you thinking of a cat?
You: Yes
Computer: I knew it !! Let's keep playing! I am good at this!
Once again, this follows a tree structure! Depending on whether the user answers yes or no, the computer will ask a different question, or will provide an answer!
Example 2: You teach the computer a new question.
You: Think of a dog.
Computer: Does it have 4 legs?
You: Yes
Computer: Were you thinking of a cat?
You: No
Computer: What animal were you thinking of?
You: Dog
Computer: What is a question to distinguish between dog and cat?
You: Does it bark?
Computer: For a dog, what should be the answer?
You: Yes
Now for the pickle fragment:
Files need to be always opened first; then manipulate them (for example loading their content into a data structure), and finally close them when they are no longer in use. So, we are going to try to open a file called animal.kb in which we will save the tree. The first time we open the file, it will be empty, so we will create our previous knowledge base. To do so, we will use a try-except structure. Why? Whenever we try to open a file that doesn’t exist, this will create an exception FileNotFoundError. We can simply catch it and create the knowledge base ‘manually’. Then we let the user play, and we keep updating the knowledge base kb. At the end of the program, when the user doesn’t want to play anymore, we ‘dump’ the information contained in kb on the file “animal.kb”.
After the 2nd try with opening the "animal.kb" knowledge base the error appears:
```
Do you want to play? y
Traceback (most recent call last):
File "...\ConceptualPython02\knowledgeBase.py", line 71, in <module>
kb = kb.play()
AttributeError: 'NoneType' object has no attribute 'play'
Process finished with exit code 1
```
That's the problematic code:
import pickle
class Knowledge:
pass
class Question(Knowledge):
def __init__(self, text, if_yes, if_no):
self.text, self.if_yes, self.if_no = text, if_yes, if_no
def play(self):
if ask(self.text):
self.if_yes = self.if_yes.play()
else:
self.if_no = self.if_no.play()
return self
class Answer(Knowledge):
def __init__(self, text):
self.text = text
def play(self):
if ask("Were you thinking of a {} ? ".format(self.text)):
print("I knew it!")
return self
# here we got it right, # so we simply return the
# Answer node as it is.
else:
newanimal = input("What animal were\ "
"you thinking of? ")
newquestion = input("What is a question "
"to distinguish between {} and {} ?"
.format(self.text, newanimal))
# but in case we didn't know the animal
# we need to modify the node adding # the appropriate question and# what to do
# ifyes and if no
if ask("For {} , what should be the answer? ".format(newanimal)):
return Question(newquestion,
Answer(newanimal), self)
else:
return Question(newquestion,
self, Answer(newanimal))
def ask(q):
while True:
ans = input(q + " ")
if ans == "y":
return True
elif ans == "n":
return False
else:
print("Please answer y or n!")
try:
file = open("animal.kb", "rb")
kb = pickle.load(file)
file.close()
except FileNotFoundError:
kb = Question("Does it have 4 legs?", Question("Does it bark?",
Answer("dog"), Answer("cat")), Answer("bird"))
while True:
if not ask("Do you want to play?"):
break
kb = kb.play()
file = open("animal.kb", "wb")
pickle.dump(kb, file)
file.close()
Of course, also, it doesn't cache the new questions about the animals as it should have.
play should always return a Knowledge instance (or inherited from it). But when in Question.play the call to ask returns True, you don't return anything:
def play(self):
if ask(self.text):
self.if_yes = self.if_yes.play()
else:
self.if_no = self.if_no.play()
return self
So change the indentation of return self so it is always executed.
Over the past few months I've been attempting to create a text-based Zork-style game as a project to teach myself Python.
Thanks to the wonderful people here at stackoverflow and plenty of youtube video's, I've made decent progress. The issue I'm currently dealing with is towards the bottom of the code, in the Bag class.
As you will see below in my bag class, I have a method called Take. This method originally was not within the bag class, it was in the section at the bottom that reads user commands.
class Bag:
def __init__(self, inventory):
self.inventory = inventory
def addToInventory(self, item):
for key in list(Location.room.roominv.keys()):
self.inventory.append(Location.room.roominv[key])
del Location.room.roominv[key]
def SearchRoom(self):
if Location.room.roominv:
for item in list(Location.room.roominv.keys()):
print("you find a", item)
else:
print("You don't find anything")
def NoneHere(self, command):
print("You can't find a", command)
def Take(self, command):
for key in list(Location.room.roominv.keys()):
if Location.room.roominv[key].name == command.split()[1]:
bag.addToInventory(key)
print('you take the', key)
def CheckTake(self):
if Location.room.roominv and command.split()[1] in Location.room.roominv:
self.Take(command)
else:
self.NoneHere(command.split()[1])
def CheckInv(self):
for item in list(bag.inventory):
print("Your bag contains:", item.name)
player = Player("Jeff", 100)
bag = Bag([])
Location = Location('introd')
command = ' '
while command != "":
command = input('>>> ')
if command in Location.room.exits:
Location.travel(command)
elif command == 'look':
Location.RoomDesc()
elif command == '':
print('You have to say what it is you want to do!')
command = '#'
elif command == 'search':
bag.SearchRoom()
elif command.split()[0] == 'Take':
bag.CheckTake()
elif command == 'Inventory':
bag.CheckInv()
else:
print('Invalid command')
I was advised to separate the logic of user commands from the rest of the game so I moved it to a specified class.
Before I did this however, the game would have no problem picking up only specific items from a rooms inventory. Now it picks up all.
(Code defining each room will be posted at bottom, I've been importing it from a separate .py file)
Currently, only one of my rooms contains more than one Item. The "inside cottage" room, which contains "Ornate_Key" and "Knife".
Here's the strange thing. If I try to take the Ornate_Key, it picks it up fine (Also picks up the Knife though).
However if I try to take the Knife, I receive an error with this traceback
Traceback (most recent call last):
File "C:/Users/Daniel/Python 3.6/Scripts/PythonPR/Flubbo'sModuleTest.py", line 156, in <module>
bag.CheckTake()
File "C:/Users/Daniel/Python 3.6/Scripts/PythonPR/Flubbo'sModuleTest.py", line 130, in CheckTake
self.Take(command)
File "C:/Users/Daniel/Python 3.6/Scripts/PythonPR/Flubbo'sModuleTest.py", line 122, in Take
if Location.room.roominv[key].name == command.split()[1]:
KeyError: 'Ornate_Key'
I've spent about 6 hours tinkering with this code, going back to older versions and comparing this current one to ones where I wasn't hitting this issue, and I can't figure out why this suddenly started happening.
I am very new to coding in general, so I'm very fuzzy on architecture/the fundamentals of things. Does anyone have any idea what is causing this issue?
At the very bottom of this page I will post a section of code from an older version that is not experiencing this problem.
Considering this post is already very long, I might as well post an example game to demonstrate exactly what is happening.
>>> look
You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.
{'Search the ground', 'Go North'}
>>> search
you find a Sword
>>> Take Sword
you take the Sword
>>> n
moving to clearing
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. To the South is the way you entered the forest. A well worn path goes to the East. In the distance a harp can be heard.
{'Go East', 'Take flower', 'Go south'}
>>> e
moving to forest path
You begin walking down a well beaten path. The sounds of the forest surround you. Ahead you can see a fork in the road branching to the South and East.You can smell smoke coming from the South, and can hear a stream to the East
{'Go East', 'Go West', 'Go South'}
>>> e
moving to stream
You come upon a relaxing stream at the edge of the woods. It looks like there is something shiny in the water. To your South is a rickety looking shack, to your West is the forest path you came down
{'Go West', 'Go South'}
>>> Take Rusty_Key
you take the Rusty_Key
>>> s
moving to shack
In front of you is a shack, possibly used as an outpost for hunting. It looks dilapidated.
{'Go North', 'Go South'}
>>> s
moving to inside shack
The inside of the shack is dirty. Bits of ragged fur are scattered about the floor and on a table against the back wall.A sharp looking knife is on the table. There is an ornate key hanging on the wall by a string.
{'Take Key', 'Take Knife', 'Go North'}
>>> search
you find a Knife
you find a Ornate_Key
>>> Take Ornate_Key
you take the Ornate_Key
>>> Inventory
Your bag contains: Sword
Your bag contains: Rusty_Key
Your bag contains: Knife
Your bag contains: Ornate_Key
>>>
Any particular reason why you have a Take method in Bag? It seems totally redundant, considering all you want to do is add that item if it exists in a dictionary. Try this:
def CheckTake(self):
key = command.split()[1]
if Location.room.roominv and key in Location.room.roominv:
bag.addToInventory(key)
print('you take the', key)
else:
self.NoneHere(key)
Also, your code is inconsistent. In some places, you access globals directly, while in other places, you redundantly pass it to a function. I would strongly advice you to take this to Code Review and get your act together once you get this working.
I'm struggling a lot with my code. Now my teacher wants me to make a function out of this and I'm really trying but I can't figure it out.
So I need to make a function out of this and then call it again further down. Can someone please help me or give me some tips :) :)
opengraph = False
while opengraph is not True:
if len(sys.argv) == 2:
name = sys.argv[1]
g = openmap(name)
opengraph = True
else:
try:
name = raw_input('Please enter a file: ')
g = openmap(name)
opengraph = True
except:
print 'Not able to read the file you wrote, try another time.'
origdest = raw_input('Enter origin and destination (quit to exit): ')
There are tons of references, on the internet, on how you can do this. Like this one, or this one, or this one.
Anyways.. you need to use def, give it a name and its input parameters, like this:
def MyFunction(input1, input2):
# <Rest of the code here>
Don't forget identation and if you are expecting your function to return something you need to insert a:
return output1, output2, output3
in the end.
Once you function is defined, you just need to call it in your main code and pass the correct input arguments if there is any.
output1, output2, output3 = MyFunction(input1, input2)
I hope this link to this tutorial helps, functions must be defined and then called to execute. In Python, functions syntactically look like this...
def nameOfFunction (parameters):
code to perform task/tasks...
# Call your function...
nameOfFunction(parameter)
Follow this link to go to the tutorial and good luck! Link to tutorial
Struggling to work out why python complaining at line 4:
import sys
import re
problem = input("What is wrong with your mobile device?").lower
water = re.search(r'water', problem)
screen = re.search(r'screen', problem)+ re.search(r'smashed',problem)or re.search(r'cracked',problem)+ re.search(r'display',problem)
software=re.search(r'software',problem)+ re.search(r'program',problem)
keypad=re.search(r'keypad',problem)+ re.search(r'keyboard',problem)+ re.search(r'text',problem)
speakers=re.search(r'sound',problem)+ re.search(r"can't here",problem)+ re.search(r'cant hear',problem)
microphone=re.search(r'microphone',problem)+ re.search(r'cant hear me',problem)+ re.search(r"can't hear me",problem)
battery=re.search(r'battery',problem)+ re.search(r'swollen',problem)
charger=re.search(r'Charger',problem)+ re.search(r'charge',problem)+ re.search(r'charging',problem)
if water:
print("If your phone has suffered water dammage there is not much you can do, it is recomended that you buy a new phone")
sys.exit
elif screen:
print("If your screen is cracked then it is recomended that you get it repaired this is not too expensive.")
sys.exit
elif software:
print("If you have a software issue then contact the product manurfacture, they are the only ones qualified to fix this.")
sys.exit
elif keypad:
print("Clean your keypad with a wetwipe, do not get the charger port or jack port wet.")
sys.exit
elif microphone:
print("Your microphone hole may be blocked, please clean this with a soft dry tooth brush, if this does not work then please retern the hand held device to its manufactures.")
sys.exit
elif battery:
print("If your battery is enlarged/swollen you have probbaly over charged it it is recomended that you buy a ned battery.")
sys.exit
elif speakers:
print("The speaker on most phone is located on the side or back or the device if this is blocked then please attemt to clean this with a dry, soft toothbrush, if this does not work please contact the product manurfacture.")
sys.exit
elif charger:
print("If you have not tryed buying a new charger then try that. If a new charger does not work, please send your mobile device to the product manurfacture.")
sys.exit
else:
print("please write your problem again, attempt to use keywords that relate to your problem.")
sys.exit
If someone could tell me how to correct this or correct this themselves it would be much appreciated.
you are not calling the function lower in line 3. In order to call it, you have to write 2 parenthesis after it. Thus, correct that line as follows:
problem = input("What is wrong with your mobile device?").lower()
The problem is actually on line 3. According to this article, Python 2 uses raw_input to get input, while Python 3 uses input. It looks like your code is expecting a Python 3 environment, but your environment is actually Python 2.
You can replace your call to input with a call to raw_input if you are, indeed, running in a Python 2 environment.
In addition, you must use parentheses after the call to lower so that the method actually gets called.
Python 2
problem = raw_input("What is wrong with your mobile device?").lower()
Python 3
problem = input("What is wrong with your mobile device?").lower()