Python switching the display based on input using If, Else - python

I want to display print text based on my Input value using IF/Else or Switch. And Also let me know how to use switch case for below code.
# OnButtonOK after clicking it, display the input value
def OnButtonOK(self):
Input = self.entrytext.get()
# self.text.insert(END, Input + '\n')
# self.scroll.config(Input = self.text.yview)
print Input
useroption = atoi(Input)
# self.OnButtonClick();
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
return;
def SubMenu1(self):
print 'SubMenu1'
return;
def SubMenu2(self):
print 'SubMenu2'
return;
def SubMenu3(self):
print 'SubMenu3'
return;
I am able to print only else part:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
Let me know where exactly i am going wrong.

I think you have indentation problems in your code:
Python use 4 spaces(you can use 1 space but 4 is good practice) indentation language. Means if/else statement will be like this:
if a == 1:
print("A = 1") # 4 spaces w.r.t to above statement
elif a == 2:
print("A = 2")
elif a ==3:
print("A = 4")
else:
print("A = pta nahi")
you can use above if/else statements as a switch case and also your indentation problem will be solved

It's a simple beginner's mistake, you're indenting it worng:
if (useroption == 1):
print "input is output"
self.SubMenu1();
else:
print "Error:Invalid"
should be
if (useroption == 1):
print "input is output" # You had an indent too many here
self.SubMenu1();
else:
print "Error:Invalid"
Python is indentation sensitive; too many or too few indentations will break your code.

Related

Multiple instructions in switch return statement

I am new to Python. Here is my question:
import sys
def main():
print "option 1) check updates 2) rewrite index 3) ..."
option = raw_input()
print "\nthe option: is: " + option
switch_option(option)
def switch_option (option):
return {
1:
# print "option is 1",
1,
2: 2
}.get(option, 0)
if __name__ == '__main__':
main()
This program works fine, but if I uncomment <print "option is 1", I get an error.
I get this error:
SyntaxError: invalid syntax.
What am I missing? I tried adding <,> and <;>.
Questions:
How can I include debug statements such as print inside a return statement?
Is the Python syntax waiting for a certain template in my case?
Does return accept multiple instructions?
Does print break the execution flow?
The short answer is that you can't use a print statement inside an expression the way you're proposing. You'd have to answer questions like "when does it get evaluated" that some languages have answers to, but not Python.
That having been said, and especially if you're new to Python but have familiarity with other functional languages, you can create a dictionary that has functions as values. Here's a way to recast your example:
#!/usr/bin/env python3
def main():
print("option 1) check updates 2) rewrite index 3) ...")
option = input().strip()
print("the option: is: " + option)
switch_option(option)
def switch_option (option):
options = {
'1': option_one,
'2': lambda: 2
}
f = options[option]
result = f()
print("the result is: " + str(result))
def option_one():
print("option is 1")
return 1
if __name__ == '__main__':
main()
I'm not sure why you're trying to put a print statement inside a dictionary
You can print before the return
def switch_option (option):
print "option is %r" ‰ option
return {
1: 1,
2: 2
}.get(option, 0)
Then you'll need to get that result
o = switch_option(option)
And yes, python supports multiple return values

Variable will not update

Made my very first program for school using a basic calculator program but added a variable, not sure if it should be global or local. It calculates fine, but does not return 'tribble' as a new integer.
tribble = 1
def buy():
x=int(raw_input("How many?"))
return (tribble + x);
def sell():
x=int(raw_input("How many?"))
return (tribble - x);
def breed():
x=int(raw_input("Multiply them by 2"))
return (tribble * x);
def cull():
x=int(raw_input("Kill half your Tribbles"))
return (tribble / x);
print "1: Buy"
print "2: Sell"
print "3: Breed"
print "4: Cull"
print "0: QUIT"
while True:
CHOICE = int(raw_input("What will you do with your Tribbles?"))
if CHOICE == 1:
print "Buying Tribbles"
print buy()
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 2:
print sell()
print 'Selling Tribbles'
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 3:
print 'Breeding Tribbles, good luck.'
print breed()
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 4:
print "You're killing them!!"
print cull()
print "You have" + str(tribble) + "Tribbles."
elif CHOICE == 0:
exit()
Are you trying to update the value of tribble?
Then instead of print buy() you should update your variable by using: tribble = buy()
That way you know the value has been updated into the result from the function buy().
Do the same for other functions as well.
Hope it helps.
You don't update the value of tribbles in your functions and thus every time a function is called tribbles is being treated as 1, it's original value. Instead of returning tribbles * 2, for example, just do tribbles *= 2 and then return tribbles.
Yes 'tribble' does not get updated inside the while loop. Because everytime the function returns updated tribble, you're just printing it.
You may want to update tribble this way:
...
...
tribble= buy()
print tribble
...
....
You never reassign the result of your operation to the tribble. I also recommend that you avoid global variables where possible. For example, I would rewrite your cull function to the following:
def cull(number_of_tribbles):
x=int(raw_input("Kill half your Tribbles"))
return number_of_tribbles / x # No need for the parenthesis or the semicolon
# To use
tribble = cull(tribble)
# No need for explicit str conversion in print
print "You have", tribble, "Tribbles."
As a side note, it is odd that your message is "Kill half your Tribbles" yet you ask the user for input. You should either hard code to return tribbles / 2 or change the message to the user; same goes for breed.
You can also do it this way:
tribble = 1
def buy():
global tribble
x = int(raw_input("How many?"))
tribble = tribble + x;
...
print "1: Buy"
print "2: Sell"
print "3: Breed"
print "4: Cull"
print "0: QUIT"
while True:
CHOICE = int(raw_input("What will you do with your Tribbles?"))
if CHOICE == 1:
print "Buying Tribbles"
print buy()
print "You have " + str(tribble) + " Tribbles."
...
elif CHOICE == 0:
exit()
All other methods should be changed in a similar way.
However, it's recommended to avoid using global variables.

Python not reading string a second time

I'm writing a text adventure (does anyone remember Zork?), and I'm having troubles with this code:
from random import randint
def prompt():
action = input(">>> ").lower()
if action == "exit":
quit()
elif action == "save":
save()
else:
return action
def action_error(custom=False):
if custom != False:
print(custom)
else:
phrases = ["A bunch", "of funny", "error phrases"]
print(phrases[randint(1, len(phrases)-1)])
return prompt()
action = prompt()
while True:
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action = action_error("What do you want to switch?")
action = action_error()
The matter is that if I enter a string that contains "switch", the next input is not picked up.
Also, anyone has better ways to parse verb-noun strings like "switch the light", "open the door" or "look around"/"look at OBJECT"?
First of all I noticed that if you enter switch twice the second time it's caught as an error by your program.
I think the problem lies at the end of the action_error function where you assign the return value to prompt(), so the input get consumed too early.
A possible fix would be:
def action_error(custom=False):
if custom != False:
print(custom)
else:
phrases = ["A bunch", "of funny", "error phrases"]
print(phrases[randint(1, len(phrases)-1)])
while True:
action = prompt()
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action_error("What do you want to switch?")
else:
action_error()
So no return value for action_error() and direct assignment at the beginning of the while loop.
How about, in the case of a partially entered compound action, you concatenate the new input to the old one? Then "switch" becomes "switch light", and both of your conditionals will pass.
action = prompt()
while True:
print(action) #Debugging purposes
if action.find("switch") != -1:
if action.find("light") != -1:
second_room() #Story continues
else:
action = action + " " + action_error("What do you want to switch?")
continue
action = action_error()
Bonus style suggestions:
replace a.find("b") != -1 with "b" in a
use random.choice(phrases) instead of phrases[randint(1, len(phrases)-1)]

if statement exception when a list is modified for a dialogue tree

I'm creating a dialogue tree for a text-adventure game that uses a list to hold the dialogue choices. When a user selects an option from the list, it responds and then removes that option from the list so that users can't select it again. The problem is that once I select one option (the first instance of the loop), the second choice always returns an error.
Here's the code:
x = 1
dec1 = '"Why are you doing this? What do you want?"'
dec2 = '"You keep talking about Thread. What is it?"'
dec3 = '"Can you help me?"'
dec4 = 'Say nothing.'
decision = [dec1, dec2, dec3, dec4]
while x == 1:
for i in decision:
print '%d. %s' % (decision.index(i) + 1, i)
current_input = input.return_input(charstate)
if isinstance(current_input, int):
if int(current_input) > len(decision) or int(current_input) < 1:
print '\n"I don\'t understand, %s."' % charstate.charname
continue
elif int(current_input) == decision.index(dec1) + 1:
print 'text'
decision.remove(dec1)
elif int(current_input) == decision.index(dec2) + 1:
print 'text'
decision.remove(dec2)
elif int(current_input) == decision.index(dec3) + 1:
print 'text'
decision.remove(dec3)
elif int(current_input) == 4:
print 'text'
x += 1
else:
exit(1)
else:
print '\n"I don\'t understand, %s."' % charstate.charname
continue
The problem appears to be that after I select one option, the if conditional returns an error because decision.index(dec#) no longer exists. At least, that's what I've been able to figure out. The specific error is "ValueError: x is not in list". I'm trying to figure out a way to set it up so that that doesn't happen.
The only idea I've had is creating separate try...except statements for each of the choices, which seems incredibly inelegant and bloated. There has to be something simple that I'm missing.
Thanks everyone!
edit: input.return_input(charstate) is a function that just returns a raw_input. "charstate" is an object that holds the current character information and choice history--it's passed between events and scenes.
Delete from the array by the index instead, i believe this will give you the functionality your looking for
dec1 = '"Why are you doing this? What do you want?"'
dec2 = '"You keep talking about Thread. What is it?"'
dec3 = '"Can you help me?"'
dec4 = 'Say nothing.'
decision = [[dec1,'text1'], [dec2,'text2'], [dec3,'text3'], [dec4,'text4']]
while True:
for i in decision:
print '%d. %s' % (decision.index(i) + 1, i[0])
current_input = input.return_input(charstate)
if isinstance(current_input, int):
if int(current_input) > len(decision) or int(current_input) < 1:
print '\n"I don\'t understand, %s."' % charstate.charname
continue
elif int(current_input) in xrange(1,len(decision)):
print '%s' % (decision[int(current_input)-1][1])
del decision[int(current_input)-1]
elif int(current_input) == 4:
print 'text'
break
else:
exit(1)
else:
print '\n"I don\'t understand, %s."' % charstate.charname
continue
Ok, I actually figured out how to do what I needed to do. pseudonym's answer was a good first step for me, but then I realized I needed to actually run separate code depending on the answer, not just print something different.
I've restructured the code so that I don't need to call an index to identify which answer was chosen. It was actually a relatively simple fix, once I got my head around it.
dec1 = '"Why are you doing this? What do you want?"'
dec2 = '"You keep talking about Thread. What is it?"'
dec3 = '"Can you help me?"'
dec4 = 'Say nothing.'
decision = [dec1, dec2, dec3, dec4]
while True:
for i in decision:
print '%d. %s' % (decision.index(i) + 1, i)
current_input = input.return_input(charstate)
if isinstance(current_input, int):
current_input = int(current_input)
if current_input - 1 in xrange(0, len(decision)):
response = decision[current_input - 1]
elif current_input - 1 not in xrange(0, len(decision)):
print '\n"I don\'t understand, %s."\n' % charstate.charname
continue
else:
exit(1)
else:
print '\n"I don\'t understand, %s."\n' % charstate.charname
continue
if response == dec1:
print 'dec1'
elif response == dec2:
print 'dec2'
elif response == dec3:
print 'dec3'
elif response == dec4:
print 'dec4'
break
else:
exit(1)
del decision[current_input - 1]

python while loop break

I am trying to make an on/off switch for my program:
(see after the ### for what I'm talking about)
while 1:
str = raw_input("insert your word: ")
n = input("insert your scalar: ")
def string_times(str, n):
return n * str
print string_times(str, n)
###
def switch(on,off):
raw_input("On or off? ")
if switch == "on":
continue
if switch == "off":
break
switch(on,off)
I get a continue not in loop error. Basically, I want to create an on or off switch after the program runs once. What do I fix?
You cannot use break and continue in a nested function. Use the return value of the function instead:
def switch():
resp = raw_input("On or off? ")
return resp == "on":
while True:
# other code
if not switch():
break
Note that there is little point in defining your functions in the loop. Define them before the loop, as creating the function object takes some performance (albeit a small amount).
The switch() function needs no arguments (you didn't use them at all), and the continue is also not needed. If you didn't break out of the loop, it'll just continue from the top when you reach the end.
You only need continue if you want the loop to start at the top again skipping the rest of the code in the loop:
count = 0
while True:
count += 1
print count
if loop % 2 == 0:
continue
print 'We did not continue and came here instead.'
if count >= 3:
break
print 'We did not break out of the loop.'

Categories

Resources