Variable Being Evaluated as Anything - variables

I am having a problem with the following code. This is supposed to be the beginning of a small text based game. I want to take the users input and then output a message (such as a help menu, or the start of the game).
def start (): # This runs when the program starts
print("THE LAST RANGER")
print ("Type Start to Begin")
print ("Type About for Credits")
print ("Type Help for Instructions")
prompt_start()
def Waking_up(): # This should run when the user enters "Start"
print ("SIR... Sir. We need to get you out of here, come on.")
def About(): #This should run when the user enters "About"
print ("Welcome to THE LAST RANGER created by Michael Frazer.")
#add more to this at some point
def Help(): #This should run when the user enters "Help"
print ("This is the help menu")
def prompt_start(): #This function takes the users input
global input_0
input_0 = input()
start () #This runs the "start" function defined in the first lines
if input_0 == "Start" or "start": #These should evaluate the users input
Waking_up ()
elif input_0 == "About" or "about":
About ()
elif input_0 == "Help" or "help":
Help ()
else:
print ("Enter Valid Command")
My problem is that the input variable is being evaluated as literally anything. For example the line
if input_0 == "Start" or "start": #These should evaluate the users input
Waking_up ()
Runs the "Waking_up" function even when the input is not equal to "Start". If the user enters something like "Help", the program seems to think that "Help" is equal to "Start" and runs the waking up function. I've tried to debug this with 3 friends and we are all out of ideas. Thanks for any help.

"start" is evaluating to true because you don't have the full expression. Try:
if input_0 == "Start" or input_0 == "start": #These should evaluate the users input
Waking_up ()

Just change the following:
if input_0 == "Start" or input_0 == "start":
Waking_up ()
elif input_0 == "About" or input_0 =="about":
About ()
elif input_0 == "Help" or input_0 == "help":
Help ()
else:
print ("Enter Valid Command")
This will work as you want and will only evaluate the corresponding input(s) instead of "Start" all the time.
Depending on what you're doing with the program, consider filtering the user's input as well (such as converting the input string to .lower() and only have your if/elif/else commands accept lowercase input -- may save you some time. Just a suggestion from a fellow python newbie.

Related

How do I make this so that way whenever the user says no it will stop or terminate the program? Currently, it's not doing that

def Main():
global more
InitializeReport()
TeamCode()
more = input("Do you have more to enter?")
while (more != "N" or "No" or "n" or "no"):
ProcPlyr()
more = input("Do you have more to enter?")
CalcAvg()
DisplaySummary()
while (more == "N" or more == "No" or more == "n" or more =="no"):
exit()

Pysimplegui and Pygame merge

hi I am trying to merge a pygame program with pysimplegui.
i'm looking for a way of grabbing the downstroke of a keyboard key. at the moment i can only see an upstroke of the key no matter what im doing.
I have sucessfully created pysimplegui programs but this is the first time i'm trying to merge with pygame.
window is setup by
window = sg.Window('UNICHALL V2.0',
Win_layout,
border_depth =20,
resizable = True,
keep_on_top = False,
finalize=True,
return_keyboard_events=True,
use_default_focus=False)
and in my pygame program i use
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
stop = pygame.time.get_ticks()
delta = stop - start
key = event.key
if key == 27:
sys.exit(1) ...
i can't get these two work in harmony, they either internally loop forever or simply stop the program dead.
Any help appreciated.
If you just need to detect when key pressed and released, try to bind the event '<KeyPress>' and '<KeyRelease>', not set option return_keyboard_events=True of sg.Window.
Example Code
import PySimpleGUI as sg
layout = [
[sg.InputText('', key='-INPUT-')],
[sg.Button('Add Binding'), sg.Button('Remove Binding')],
]
window = sg.Window('Test Program', layout, finalize=True)
while True:
event, values = window.read()
if event == sg.WIN_CLOSED:
break
elif event in ('Press', 'Release'):
e = window.user_bind_event
action = 'pressed' if event == 'Press' else 'released'
print(f'char:{repr(e.char)} | keycode:{e.keycode} | keysym:{e.keysym} | keysym_num:{e.keysym_num} {action}')
elif event == 'Add Binding':
window.bind("<KeyPress>", "Press")
window.bind("<KeyRelease>", "Release")
elif event == 'Remove Binding':
window.TKroot.unbind("<KeyPress>")
window.user_bind_dict.pop("<KeyPress>", None)
window.TKroot.unbind("<KeyRelease>")
window.user_bind_dict.pop("<KeyRelease>", None)
window.close()

while loop end everything after it's complete

So I'm trying to make a lottery program where you pick a animal, letter, and number, those are put into a array and compared to another that has the parts chosen by random.
Testing with what I call the animal round.
I have a while loop for invalid entries, that it will not move on till one of the four animals is accepted. But when it does that, the variable invalid goes to false and the coding after it doesn't get used at all. I had this problem last night, and when I finally gave up and went to bed, I decided I'll write it out on flowgorithm (If you haven't heard it makes a flow chart and you can go through programming with it step by step).
I made it, and it worked like expected, I copy and paste it over, and I get the exact same problem as last night.
Here is the code.
#import library
import random
#get variables
game = True
invalid = True
animalarray = [""]
animalarray.append("tiger")
animalarray.append("cow")
animalarray.append("turtle")
animalarray.append("bird")
lotteryarray = [""]
#game loop
#animal round
print("Pick a animal: ")
print("tiger")
print("cow")
print("turtle")
print("bird")
print(" ")
lotteryarray[0] = input()
#while loop for invalid entry
while invalid == True:
if lotteryarray[0] == "tiger" or lotteryarray[0] == "cow" or lotteryarray[0] == "turtle" or lotteryarray[0] == "bird":
invalid == False
else:
print("Invalid entry!")
lotteryarray[0] = input()
print(" ")
print("You chose " + lotteryarray[0])
game == False
And this is all I get in the shell:
Pick a animal:
tiger
cow
turtle
bird
tiger
the tiger there is what I put in, it isn't being printed.
And here is the flowgorithm, like I said, in flowgorithm this works.
flowgorithm of lottery game
I figured it out.
I printed what invalid was after it was meant to change to False and it didn't change, I changed the two equal signs to one and it worked and changed the value.

Key Releases Psychopy

I'm fairly new to psychopy but I'm having a lot of trouble recording keyboard events so far. The keyboard demo works so I know it is possible, but when I implement the code in my own program it doesn't record any keyboard activity at all. Right now my program is super simple as I'm just trying to get the hang of it. I have a picture and want to record the duration of keypresses during the time the picture is on screen. I have a couple print statements as sanity checks and when I run it (and am using the keyboard) it doesn't print anything. Here's an outline of my code:
from psychopy.iohub import launchHubServer, EventConstants
io = launchHubServer()
keyboard = io.devices.keyboard
keyboard.reporting = True
#-------Start Routine "trial"-------
continueRoutine = True
io.clearEvents('all')
duration_lst=[]
while continueRoutine and routineTimer.getTime() > 0:
# get current time
t = trialClock.getTime()
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *image* updates
if t >= 0.0 and image.status == NOT_STARTED:
# keep track of start time/frame for later
image.tStart = t # underestimates by a little under one frame
image.frameNStart = frameN # exact frame index
image.setAutoDraw(True)
if image.status == STARTED and t >= (0.0 + (5.0- win.monitorFramePeriod*0.75)): #most of one frame period left
image.setAutoDraw(False)
# *ISI* period
if t >= 0.0 and ISI.status == NOT_STARTED:
# keep track of start time/frame for later
ISI.tStart = t # underestimates by a little under one frame
ISI.frameNStart = frameN # exact frame index
ISI.start(0.5)
elif ISI.status == STARTED: #one frame should pass before updating params and completing
ISI.complete() #finish the static period
# get keyboard events
for event in keyboard.getEvents():
print event
if event.type == EventConstants.KEYBOARD_CHAR:
key_press_duration=event.duration
duration_lst.append(key_press_duration)
print duration_lst
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# check for quit (the Esc key)
if endExpNow or event.getKeys(keyList=["escape"]):
core.quit()
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
I tried stripping off all unnecessary stuff here (variables, window, stimuli etc.) and uses keyboard.getReleases() so it boils down to this:
from psychopy import iohub
io = iohub.launchHubServer()
keyboard = io.devices.keyboard
print 'press something now!'
while True:
# get keyboard releases
for event in keyboard.getReleases():
print 'Released!'
This should print all info about each key release in the console. It works for me, at least. If it also works for you, the problem is probably related to something else in your script.

Python 3.x tkinter - can't get checkbox' variable value

Please help! As it says in the title - I can't get checkbox' variable value.
def init_widgets(self):
ttk.Button(self.root, command=self.insert_txt, text='Button', width='10').place(x=10, y=10)
...
cbcc = ttk.Checkbutton(root, text="Damage", onvalue="on", offvalue='off').place(x=235, y=12)
...
def insert_txt(self):
...
cbcd = StringVar()
cbcd.get()
print(cbcd)
if cbcd == "on":
self.damage
else:
Print delivers "PY_VAR2" and counting up from there with every time I click (PY_VAR3, etc.)
It seems in your code, the argument 'variable' in your Checkbutton is not bounded, furthermore to get the value from IntVar or StringVar you would use (IntVar.get(), StringVar().get()), you could use the next code as example to use Checkbutton widget.
'''
CheckBox Test
References:
http://effbot.org/tkinterbook/checkbutton.htm
'''
from tkinter import *
class App:
def __init__(self, master):
self.var = IntVar() #This is the variable bounded to checkbutton to
#get the checkbutton state value
#
frame = Frame(master)
frame.pack()
self.checkbutton = Checkbutton(frame, text="Hello Checkbutton",
command=self.say_hello, variable=self.var)
self.checkbutton.pack(side=LEFT)
#
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
def say_hello(self):
'''
Function Bounded to Checkbutton in command parameter, every click
either check or un-check print the current state of the checkbutton
'''
print("State Changed:", self.var.get())
if __name__ == '__main__':
root = Tk()
app = App(root)
#
root.mainloop()
root.destroy() # Quit the App when you click "Quit"
Every click on the check button, you will see printed in the console the value of the current state for the checkbutton. You can check the next reference to get an general overview tkinter widgets: http://effbot.org/tkinterbook/checkbutton.htm
I hope this snippet helps you.
Very Best Regards.