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.
Related
count=0
while count < 3:
Username = input('Username: ')
Password = input('Password: ')
numAttempts = 3
if Password=='123' and Username=='admin':
print('Successfully logged in')
elif:
print('Invalid username and password!')
count += 1
else numAttempts > 3:
print("Account has been blocked")
File "", line 8
if Password=='123' and Username=='admin':
^
IndentationError: unexpected indent
In python, indents matter. You would need to tab everything after the
while count < 3:
Any conditional or loop statement needs to be indented after. It's also important for the tabs to be consistent (IE, using the tab key or same number of spaces).
You also look like you have your logic flipped with your else and elif statement.
Also, you numAttempts should probably start at 0, and you need to update this in the else clause.
This should get you started.
count=0
while count < 3:
Username = input('Username: ')
Password = input('Password: ')
numAttempts = 3
if Password=='123' and Username=='admin':
print('Successfully logged in')
elif numAttempts > 3:
print("Account has been blocked")
else:
print('Invalid username and password!')
count += 1
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__
print'Free fall distance and velocity calculator'
g=9.81
def finalvelocity(t):
vf=g*t
return vf
def height(t):
h=0.5*g*t
return h
t=input('Enter the value of time in seconds: ')
print'What do you want to get?'
print'[1]. Final Velocity'
print'[2]. Height'
choice= input('Enter Selected Number: ')
if choice==1:
print 'Answer is', finalvelocity(t),'meter per second'
if choice==2:
print 'Answer is', height(t), 'meters'
if choice>2:
print 'Invalid Selection'
if choice<1:
print 'Invalid Selection'
for choice in range(choice>2):
n=raw_input('Do you want to continue?[y]yes/[n]no: ')
while True:
t=input('Enter the value of time in seconds: ')
print'What do you want to get?'
print'[1]. Final Velocity'
print'[2]. Height'
choice= input('Enter Selected Number: ')
if choice==1:
print 'Answer is', finalvelocity(t),'meter per second'
if choice==2:
print 'Answer is', height(t), 'meters'
if choice>2:
print 'Invalid Selection'
if choice<1:
print 'Invalid Selection'
if n==n:
break
Thanks for updating your question. You can use infinite loops to run the program again and again until the user wishes to exit. A super simple example of this would be:
while True:
t = raw_input("Do you want to exit? y/n: ")
if t == 'y':
break
else:
print "You stayed!"
As for your code, here's how you'd make it run infinite times. Note how if the user selects 'No' the code breaks out of the loop to exit the program.
print 'Free fall distance and velocity calculator'
g = 9.81
def finalvelocity(t):
vf = g*t
return vf
def height(t):
h = 0.5*g*t
return h
# Start an infinite loop of user input until they exit
while True:
# Ask for time
t = input('Enter the value of time in seconds: ')
# Ask for query type
print'What do you want to get?'
print'[1]. Final Velocity'
print'[2]. Height'
choice= input('Enter Selected Number: ')
# Perform calculations
if choice==1:
print 'Answer is', finalvelocity(t), 'meter per second'
if choice==2:
print 'Answer is', height(t), 'meters'
else:
print 'Invalid Selection'
# Offer the user a chance to exit
n = raw_input('Do you want to calculate another? [y]yes/[n]no: ')
if n == 'n':
# User wants to exit
break # Break out of the infinite loop
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
I have a multiple choice input that accepts A, B or C.
For each scenario, a while loop is utilised to continue prompting for input until there is a blank entry, i.e. just Enter is pressed.
Scenario B and Scenario C are working fine.
In Scenario A, however, I want to limit the input to be an integer, and I'm having difficulties applying these two conditions ie a blank entry will exit the program and an integer is required.
So basically, pseudo code is:
If option A is selected the input needs to be an integer which when entered will return the same prompt for an integer. To break the loop, press Enter.
I'm loathe to show my attempt, but just to demonstrate the kind of things I was trying, example code is below:
input_01 = raw_input("Multiple Choice - Enter A, B or C : ")
#
# when selecting A, continue to prompt for integer until input is blank
if input_01 == "A" or input_01 == "a":
print("\nDirections for scenario A.\n")
# BEGIN horrible attempt
while True:
try:
# test if input is an integer
a_input = int(raw_input("P1-Enter a number (blank entry to quit) : "))
# test if it is blank
while a_input != "":
print "\nA - DONE\n"
print("Directions for scenario A.\n")
# continue to prompt for integer
a_input = raw_input("P2-Enter a number (blank entry to quit) : ")
except ValueError:
print("\nGoing back to the first bit of A, enter a number please.\n")
# END horrible attempt
#
# this block works as required
#
if input_01 == "B" or input_01 == "b":
print ""
print("Directions for scenario B.\n")
b_input = raw_input("B - Enter anything (blank entry to quit) : ")
# this will keep prompting for input until blank entry
while b_input != "":
print "\nB - DONE\n"
print("Directions for scenario B.\n")
b_input = raw_input("B - Enter anything (blank entry to quit) : ")
#
# this block works as required
#
elif input_01 == "C" or input_01 == "c":
print ""
print("Directions for scenario C.\n")
c_input = raw_input("C - Enter anything (blank entry to quit) : ")
# this will keep prompting for input until blank entry
while c_input != "":
print "\nC - DONE\n"
print("Directions for scenario C.\n")
c_input = raw_input("C - Enter anything (blank entry to quit) : ")
#
# this is the quit message that shown on blank entry
#
print "\nThank You, Good Bye.\n"
Why not try a simpler approach?
user_choice = raw_input('Please enter A B or C: ')
while user_choice.upper() not in ('A', 'B', 'C'):
print('Sorry, invalid entry.')
user_choice = raw_input('Please enter A B or C: ')
if user_choice.upper() == 'A':
print('Choice A Directions')
user_input = raw_input('Please enter only integers, or a blank to quit: ')
while user_input.isdigit():
# do something with user_input, as it will be
# overwritten
user_input = raw_input('Please enter only integers, or a blank to quit: ')
print('Quitting choice A, because a non-integer was entered.')
Note that isdigit() has its limitations. It won't deal nicely with fractions for example.
Assuming I am correct in that you just want to prompt for an integer twice...
Break out of the while True: loop if an exception is not caught:
if input_01.lower() == "a":
print("\nDirections for scenario A.\n")
# BEGIN horrible attempt
while True:
try:
# test if input is an integer
a_input = raw_input("P1-Enter a number (blank entry to quit) : ")
a_input = int(a_input)
# This will only be executed if input is not blank
print "\nA - DONE\n"
print("Directions for scenario A.\n")
# continue to prompt for integer
a_input = raw_input("P2-Enter a number (blank entry to quit) : ")
a_input = int(a_input)
except ValueError:
if a_input == '':
break
print("\nGoing back to the first bit of A, enter a number please.\n")
This code will just keep repeating the loop until either input receives an empty string
Note that there a likely better ways to do what you are trying to do... but since I'm not positive what exactly you are trying to do I can just do my best to fix your code.