Python Breaking a While Loop with user input - python-2.7

new to Python. Within a while loop, I'm asking the user for an input which is a key for a dict. and then print the value of that key. This process should continue until the input does not match any key in the dict. I'm using an if statement to see if the key is in the dict. If not I'like the while loop to break. So far I can't get it to break.
Thank you all
Animal_list = {
'lion': 'carnivora', 'bat': 'mammal', 'anaconda': 'reptile',
'salmon': 'fish', 'whale': 'cetaceans', 'spider': 'arachnida',
'grasshopper': 'insect', 'aligator': 'reptile', 'rat': 'rodents',
'bear': 'mammal', 'frog': 'amphibian', 'turtles': 'testudines'
}
while True:
choice = raw_input("> ")
if choice == choice:
print "%s is a %s" % (choice, Animal_list[choice])
elif choice != choice:
break

choice == choice will always be true. What you really want to do is check if choice is in the Animal_list. Try changing to this:
Animal_list = {
'lion': 'carnivora', 'bat': 'mammal', 'anaconda': 'reptile',
'salmon': 'fish', 'whale': 'cetaceans', 'spider': 'arachnida',
'grasshopper': 'insect', 'aligator': 'reptile', 'rat': 'rodents',
'bear': 'mammal', 'frog': 'amphibian', 'turtles': 'testudines'
}
while True:
choice = raw_input("> ")
if choice in Animal_list:
print "%s is a %s" % (choice, Animal_list[choice])
else:
break

Related

Python 2.7, trouble printing docstrings (doc comments) "function has no attribute _doc_" error

I'm working on LPTHW ex 41, where we modify a bunch of print statements to use a docstring style and then use a runner to print them.
The code originally was like this:
Function()
Print "Several lines of printed material"
Revised, the functions begin:
Function()
"""doc comment"""
A runner connects all the functions ("rooms") like so, with the goal being to print doc comments instead of print commands.
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
def runner(map, start):
next = start
while True:
room = map[next]
print "\n----------------"
print room._doc_
next = room()
runner(ROOMS, 'central_corridor')
But I keep getting the error
'function" object has no attribute '_doc_'
Example room:
def central_corridor():
"""You wanna blow thing up.
You running toward place for to get bomb.
Emeny approach!
1 = shoot at enemy
2 = avoid emenemeny
3 = use bad pick up line on emenie
4 = hint"""
#print(_doc_)
action = int(raw_input("> "))
if action == 1:
print "He shoot you first."
return 'death'
elif action == 2:
print "No he still gots you."
return 'death'
elif action == 3:
print "Oh yeah sexy boy."
print "You get past laughing enemy."
return 'laser_weapon_armory'
elif action == 4:
print "Emeny like good joke."
return 'central_corridor'
else:
print "You enter wrong input"
return 'central_corridor'
Can anyone tell me how to get the doc comments to print? Thanks!
Noticed doc needs two underscores. Fixed
_doc_
__doc__

Python palindrome code doesn't return anything

Why?
It returns:
if word[0] != word[-1]:
IndexError: list index out of range
If I change "print "Palindrome"" to "return True" and "return False" it returns nothing at all.
import sys
exstring = "f"
data = list(exstring)
def palindrome(word):
if len(word) < 2:
print "Palindrome"
if word[0] != word[-1]:
print "Not Palindrome"
return palindrome(word[1:-1])
palindrome(data)
First, you need an elif in there like Hypnic Jerk mentioned. Second you need to return after your prints.
Working code:
import sys
exstring = "radar"
data = list(exstring)
def palindrome(word):
if len(word) < 2:
print "Palindrome"
return True
elif word[0] != word[-1]:
print "Not Palindrome"
return False
return palindrome(word[1:-1])
palindrome(data)
What you want to do is this:
def palindrome(word):
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return palindrome(word[1:-1])
You do not need elif in this case. It's just good practice. The second if statement will not be reached unless the first is false anyway. More "correct" (but still completely equivalent) is:
def palindrome(word):
if len(word) < 2:
return True
elif word[0] != word[-1]:
return False
else
return palindrome(word[1:-1])
Furthermore, it's good practice to only let the function decide if it's a palindrome or not, and not print it. Instead, you should use it like this:
if palindrome(word):
print "Palindrome"
else
print "Not palindrome"
Don't mix functionality unless you have a good reason.

Converting integers for loop in Python - Loop ignores function value?

I'm working on a number guessing game and can't seem to get my loop to work while utilizing a function. I was manually typing out conversion under each if/elif in the block, but that was tedious and only checking for integers - string inputs couldn't read and broke the system.
I tried creating a conversion function to check the values and determine if it was an integer or string and change the variable type accordingly. However this results in an infinite loop fo line 18.
Can someone point out what I'm doing wrong here?
Heads up, I do have the random.py script from Python.org and am importing it so the game plays differently each time.
from random import randint
print 'Hello, my name is Skynet. What\'s yours?'
myName = raw_input()
print 'Good to meet you, ' + myName + '! Let\'s play a game.'
print 'I\'m thinking of a number between between 1 and 20, can you guess it?'
pcNum = randint(1,20)
myNum = raw_input()
def checkNum(myNum):
try:
int(myNum)
except ValueError:
returnVAL = 'That\'s not a number I know, try again.'
else:
returnVAL = int(myNum)
return returnVAL
while myNum != pcNum:
if myNum > pcNum:
print 'That\'s too high! Try again.'
myNum = raw_input()
checkNum(myNum)
else:
print 'That\'s too low! Try again.'
myNum = raw_input()
checkNum(myNum)
if myNum == pcNum:
print 'Good job, my number was ' + str(pcNum) + ' too! Good job, ' + myName
Any input is appreciated. I did some browsing here and got some a better idea of how to pull this off, or so I thought, and now here I am asking. First post!
print "I'm thinking of a number between between 1 and 20, can you guess it?"
while True:
guess = raw_input("What's your guess? ")
try:
guess = int(guess, 10)
except ValueError:
print "That's not a number I know, try again."
continue
if guess == pcNum:
...
break
elif guess > pcNum:
...
else:
...
Don't mix responsibilities. It is wrong to have myNum be both a number and an error message.
Also, think what you want to do when a user enters a non-number. In your case, the user's guess is "That's not a number I know, try again.", and it's being compared to pcNum; this makes no sense. If it was me, I would want the user to enter the number again. So rather than checkNum, I want input_valid_integer:
def input_valid_integer():
result = None
while result is None:
text = raw_input()
try:
result = int(text)
except ValueError:
print 'That\'s not a number I know, try again.'
return result

How do you make a conditional statement In Python?

I'm confused on how to make conditional statements. I just can't seem to figure it out. In the example bellow I want the shoot input to only work if the user chose in this case the gun earlier in the game. Same with the knife and so on.
def chap4():
print "You feel around the room.\n"
time.sleep(3)
print "You find a small chest...\n"
time.sleep(3)
print "You open the chest...\n"
time.sleep(2)
print "[pickaxe, shovel, lighter, axe, 9mm(0), knife]\n"
while (True):
chest = raw_input("What will you take?: ")
if chest == "pickaxe":
print "You take the pickaxe"
break
elif chest == "shovel":
print "You take the shovel"
break
elif chest == "lighter":
print "You take the axe"
break
elif chest == "9mm":
print "You take the empty 9mm pistol"
break
elif chest == "knife":
print "You take the knife"
break
elif chest == "axe":
print "You take the axe"
break
else:
print "Invalid choice. Try again..."
chap4()
def zombie():
print "A zombie is seem in the distance"
while (True):
attack = raw_input("> ")
if attack == "shoot":
print "Zombie hp 50/100"
elif attack == "stab":
print "Zombie hp 70/100"
else:
print "Invalid input. Try again..."
So as you can tell by the code in having trouble... I originally thought maybe I'd make another if statement within the if statement but I'm not sure. Please help if you can... Thanks!
I recommend putting a conditional if
def chap4():
....
return(chest)
def zombie()
weapon = chap4()
if weapon == "9mm":
if attack =="shoot":
print(...)
elif attack =="stab":
...
And so on.
So specify the weapon in the conditional in zombie(). Also, zombie() will have to know the chest variable, soreturn(chest) at the end of chap4() function, and call chap4() within zombie()
EDIT: when calling chap4() in zombie(), it needs to called a variable, in this case, weapon
The conditional statements are fine, so far as they go. The problem is that you aren't saving the outcomes anywhere. Do something like
if chest == "pickaxe":
print "You take the pickaxe"
weapon = "pickaxe"
elif chest == "shovel":
print "You take the shovel"
weapon = "shovel"
etc.
When the user choose an attack mode, you can check that he has the appropriate weapon:
if attack == "shoot":
if weapon == "9mm":
print "Zombie hp 50/100"
else:
print "you don't have a pistol"
Here too, printing is probably not enough. You'll want to keep track of what's happened, I would think
You can store what chest cointain like this:
chestContainer= {"pickaxe": "pickaxe", "shovel": "shovel", "lighter": "lighter", "9mm(0)": "9mm(0)", "knife": "knife", }
And then you can print the option like this:
print chestContainer[chest]
And you can evaluate if the input is valid like this:
if chestContainer[chest] == None:
print "Invalid choice. Try again..."
Edit:
As user908293 said you have to save what weapon you chose.
weapon = chestCointainer[chest]

Conditional statement not redirecting like it should

I'm new to python and I working on a stript that gets user input to redirect to another part of the program. I'm using a conditional statement to either go back or exit. But when I press the key to continue it exits. Please help
def infoMenu():
a = '''
1 = Volume Information
2 = Volume Status
3 = Display Peer Status
4 = CTDB Status
5 = CTDB Ip
6 = Display CTDB config file
'''
print a
a = raw_input('Enter your option: ')
if a == '1':
option = raw_input('Please enter name of vol: ')
subprocess.call(['gluster vol ', option, 'info'], shell=False)
elif a == '2':
option = raw_input('Please enter name of vol: ')
subprocess.call(['gluster vol ', option, 'status'], shell=False)
elif a == '3':
subprocess.call(['lvdisplay'], shell=False)
answer = raw_input('Press 0 to go back or any to exit (default[0]): ')
if answer == '0':
printOptions()
else:
exit()
elif a == '4':
option = raw_input('Please enter name of vol')
subprocess.call(['gluster vol ', option, 'info'], shell=False)
elif a == '5':
option = raw_input('Please enter name of vol')
subprocess.call(['gluster vol ', option, 'info'], shell=False)
else:
exit()
I'm talking about condition statement 3 when I press 0 its suppose to go back to the beginning menu and anything else should exit. What am I doing wrong.
Tracing your code:
function infoMenu() is run
if the user enters "3" (return)
your subprocess.call is run
then user is asked for a new input
After this your code and your description don't seem to match, because if the user enters "0", your calling some other function (which isn't included) called "printOptions()"
A super simple fix (that would break if you ever return) would be to re-call infoMenu in place of your printOptions call, but I strongly suspect you would be better off better off rewriting.
If I where trying to do what you described (using something like your style) I would do:
def infoMenu():
def thing1():
pass #do_somethings()
def thing2():
#do_someotherthings()
user_input = raw_input('Press 0 to go back or any to exit (default[0]): ')
if (len(user_input)==0) or (user_input == '0'):
return
else:
exit()
a="""
1 = thing1
2 = thing2
"""
print a
user_input = raw_input('Enter your option')
if user_input == '1':
thing1()
if user_input == '2':
thing2()
while 1:
infoMenu()
Try putting everything inside the function to a
def function()
while True:
everything here
and then change
if answer == '0':
pass
else:
break
also, if you do this, change the exit() at the end to break.
Your problem is that the function is only called once, and thus all the conditionals are run only once, and does not revert back to one.