So if i try to resize my Window with the same button back and forth just the one on the bottom will work but it wont go back to '384x470' as if the Window wasnt '500x500'
def sizeWindow():
if root.geometry('500x500'):
root.geometry('384x470')
else:
root.geometry('500x500')
buttonWinSize.configure(text="<<")```
You seem to misunderstand several things here. Tkinter has relatively cool feature that allows you to use some methods for different things. Either you get or you set with the same method. To get you leave the interface empty (e.g. root.geometry()) or you set with the required argument (e.g. root.geometry('500x500+0+0')). You should be aware that you get the current value(s) in the same format as you set them.
Therefore you retrieve a geometry string by root.geometry() and this has the form of width x height +x +y.
However, not every time this feature is the right tool to achieve the overall goal. In your case you want to check for the width and height. Tkinter provides another feature for exactly this task. It lets you ask for the width and height via winfo_width() and winfo_height().
In addition you should know that every function in python needs to return something and if nothing is specified None is returned by this function. Since you use the setter variant of root.geometry('500x500') you receive None and None equals to False in python, therefore your else block will always be executed instead of your if block.
Suggested change:
def sizeWindow():
if root.winfo_width() == 500 and root.winfo_height() == 500:
root.geometry('384x470')
else:
root.geometry('500x500')
Your if-statement is wrong. You are actually setting the size with your first root.geometry('500x500'). This does (AFAIK) not return a boolean. So you need to check the actual current dimensions:
if root.winfo_width() == 500 and root.winfo_height() == 500:
root.geometry('384x470')
else:
root.geometry('500x500')
buttonWinSize.configure(text="<<")
I could REALLY use your help with this one.
I'm trying to make a sort-of voice command operated menu for a toddler's learning app and kivy is giving me a headache
all of my screens are correctly defined and load as intended if the buttons are pressed but the voice commands, even though they register correctly and carry over their variables as intended they don't seem to have the desired effect when asked to act upon ScreenManager when the if statement is fulfilled
def on_enter(self):
....
Command.start()
Command.introMenu()
......
if Command.sel == "shapes":
ScreenManager().switch_to = "shapes"
elif Command.sel == "colours":
ScreenManager().switch_to = "colours"
......
else:
pass
the variable Command.sel is captured from a dependency, defined as a string and carried correctly as far as I can tell from the variables view in debugging
yet even though everything seems to be in order (in fact no error messages appear at all) the desired screen is not called when the if condition is met
what am I doing wrong here???
full code here
(please ignore the Greek bits in the code... it's just strings, imagine it's any other language for that matter...)
thank you!
issue resolved
correct command was
self.parent.current = "your_screen_name"
answer (eventually) found here
I made a simple game with python using the Pygame library but when I finished I just noticed that I forgot something. LIMITS
I am pretty new at python and I tried with
if player_pos[1] <= 600:
pygame.K_DOWN = None
*player_pos[1] is the y player's position
*600 is the display's limit
But then, the "down" key just stopped working so I just erased that lines.
You can't (or shouldn't try at least) to turn the input into None. Just use a logical test to decide if you want to move further...
if key_pressed == 'K_RIGHT': (or whatever syntax you use to catch keypress..)
if player_pos[1] < limit:
# update the player position
else:
pass
#JeffH has already suggested the a way to fix your code. I just wanted to make sure you understood why what you did caused problems and to point out the convention for constants. Not understanding and using that naming convention will make it more difficult for you to understand other code, and will complicate others trying to read your code.
pygame.K_DOWN is intended to be a defined constant, it is not an input or a control variable. You should absolutely not change it.
Python does not have true constants that enforce not being able to change them, so it is handled by convention. Variables that are intended to be constants by convention use all uppercase names, like K_DOWN and you are just not supposed to change them. As you discovered things may break or behave weirdly if you do.
In your case 'the down key stopped working' because the constant used to check it no longer contained the right value anymore. Pygame will give you the keycode for the down arrow key (the number 274 when I print it on my system) but you have assigned None to the constant that you are supposed to compare that value with to determine if it is the down arrow key, so that comparison will now fail.
That is why it stopped things working.
I am attempting to limit the character length of my input and then verify whether it is one of the three white characters. Struggling with the final part:
while True:
try:
letter=input("Please enter a character: ") #most intuitive way for me was the assert function but very happy to hear any other ways
assert len(letter) !=1
except AssertionError:
print("Please type only ONE character")
else:
whitespace=["\n"," ","\t"] #i believe the list specification here makes the not in code invalid? believe the two may not be compatible but errors not reached there yet
if whitespace not in letter:
print("Your character in lower case is: "+str(letter).lower())
else:
print("You typed a white space character!")
Welcome to Stackoverflow!
It looks like the error is on the if whitespace not in letter: line. This should actually be the other way around: if item not in list:. You have if list not in item:.
Also, it might help you if I reformat your code a little.
while True:
letter = input('Please enter a character: ')
if len(letter) != 1:
print('Please type only ONE character')
continue
if letter in ['\n', ' ', '\t']:
print("You typed a white space character!")
continue
lowercase_letter = letter.lower()
print(f'Your character in lower case is: {lowercase_letter}')
If you haven't already seen pylint, I'd recommend you take a look at it. It helps you format your code to PEP8 standard. It is also quite good at pointing out some simple errors in your code.
Raising Exceptions are for reporting errors to calling functions - i.e. you can't perform the job the function is supposed to be doing because the input or system state is not as required by the function.
Catching Exceptions is for handling specific errors you know how to handle in a higher level function. So for example, if your trying to read a file and it doesn't exist. In your program that mean the user hasn't set a specific flag in the config file... so you can catch that exception and let the user know how to fix the issue.
Raising an Exception and catching it in the same function (at least in this case) is just a very complicated way of writing an if statement.
When writing an if-else statement, it's a good idea to try and make the if branch positive. Which means avoid if not ...: else: if you can.
In your code, letter is already a string object - so there is no need to create a new string object with str(letter). In python everything is an object, even literals.
The continue statement jumps to the next iteration of the loop. Nothing after the continue is executed in the current iteration of the loop. You could also look at break statement that finishes executing the loop. As an exercise, you could look at adding an extra check to your code to see if the user typed 'quit', and then break. What do you think will happen?
if letter.lower() == 'quit':
break
This would have to be added before the check for single letters otherwise you would never get to this check.
Finally, rather than using string concatenation in your print statement (using str + str). You can use f-strings, format strings as in the example f'Hi my name is {name} and I am from {home}', where name and home are string variables.
Hope this helped!
I'd advise you not to use exceptions because they're very unstable. Instead, I'd use if/else conditions, like this one:
letter = input('Please enter a character: ')
if len(letter) == 1:
if letter in '\n\t ':
print('You typed a white space character!')
else:
print('Your character in lowercase is {}'.format(letter.lower()))
else:
print('Please type only ONE character')```
I need help with an ATM python program that I am creating. I am new to Python and I am worried that my coding is so off that I must start from the beginning. I am trying to separate the sections by def (): and I keep getting an error.
Traceback (most recent call last):
File "/Users/tonystrobach/Desktop/untitled3.py", line 44, in <module>
deposit()
File "/Users/tonystrobach/Desktop/untitled3.py", line 35, in deposit
if (answer == "D") or (answer == "d"):
NameError: global name 'answer' is not defined
I have been searching a long time and trying to grasp the concepts of Python the best I can. Any suggestions would be helpful.
Here is my code:
The purpose of this program is to create a simple ATM environment
Written by K. Strobach 11/22/13
def account():
print ("Hello, welcome to Bank of Python!")
print ("Please enter your account pin number")
account = raw_input("Account pin number is 1234: ")
account = (1234)
account()
def balance():
print ("would you like to see your account balance?")
see = raw_input("Enter Y or N: ")
if (see == "Y") or (see == "y"):
balance = int(0)
print ("Current balance: $" + str(balance))
balance()
def transaction():
print ("Would you like to make a transaction?")
more = raw_input("Enter Y or N: ")
if (more == "Y") or (more == "y"):
print ("Would you like to make a deposit or withdraw? Or would you like to end this transaction?")
answer = raw_input("Enter D for deposit; W for withdraw; E for end: ")
transaction()
def deposit():
if (answer == "D") or (answer == "d"):
print ("How much would you like to deposit?")
deposit = input("Enter amount to deposit: ")
deposit = int(deposit)
currentbalance = deposit + balance
print ("Deposited: $" + str(deposit))
print ("Current Balance: $" + str(currentbalance))
deposit()
def withdraw():
if (answer == "W") or (answer == "w"):
print ("How much would you like to withdrawl?")
withdraw = input("Enter amount to withdraw: ")
withdraw = int(withdraw)
currentbalance = withdraw - balance
print ("Withdrew: $" + str(withdraw))
print ("Current Balance: $" + str(currentbalance))
withdraw()
def end():
if (answer == "E") or (answer == "e"):
exit ("Thank you for Banking with Bank of Python, goodbye!")
else:
exit ("Thank you for Banking with Bank of Python, goodbye!")
end()
This is for a class, but I am not worried about that, I just want to get a better understanding of how to make this work.
Thanks in advance.
You mentioned that this was about learning, and I really respect that, so I'm going to offer a totally unsolicited review of the code you wrote as a whole, trying to point out stylistic and substantive improvements where I saw some. I'm sure you could get more competent help, but I wanted feedback like this from someone who was a little further along than me. The short answer has already been pointed out, that you're not assigning answer before referencing it within that function, but there are other things worth noting as well.
In the interest of keeping the short answer relevant, I also point to this good answer on how scoping works for Python. If you just want to know why answer wasn't working right, that should clear things up. If you want a really tedious breakdown of the code, read on :)
account
Let's look at account first. I'll only say this once, but you can (although are by no means obligated to) print multi-line strings. You can do this a number of ways:
print("This line\nwill print on\nthree lines!")
prints...
This line
will print on
three lines!
The key here being the newline character \n. Notice that I said it was a character, not characters. That will come up someday.
An alternative way to print multi-line strings is by making the string multi-line using triple quotation marks:
print('''This line
will print on
three lines!''')
prints... well, the same thing as above. People are not as keen on this approach since triple quotes are often used for block comments and docstrings, but there's no law against it.
While we're in account I want you to consider the logic of this pair of statements:
account = raw_input("Account pin number is 1234: ")
account = (1234)
What this is doing is prompting the user to enter a pin number, and then setting it to (1234) regardless. This might be intentional - like for testing purposes - but it seems weird to me. I'm also not sure if you're trying to create a tuple (which would just require a trailing comma), but if not, and you're just making a simple integer, you can say
account = 1234
which will disambiguate the intent a little bit.
I'll also bring up that raw_input is a python 2.x function, and in python 3k you just use input. you should be cautious, however, to convert the value the user gives into the appropriate type: input returns a string type regardless of what the user enters. You can quickly convert it into an integer by calling int(input("some prompt")), but you might want to catch errors, like if someone responds to that prompt with "I'm lost and not good with computers."
balance
When you ask if the user wants to see their balance, you set it to 0!
balance = int(0)
Not necessary, and in fact somewhat frustrating for anyone doing business at the Bank of Python.
This is also potentially a little too advanced for you, but consider using string formatting to print the balance. It's a nice way of taking care of the little odds and ends in a simple function. In this case, you'd use something like
print("Current balance: ${b:.2f}".format(b=balance))
transaction
So I accidentally skipped ahead and saw that you planned on using answer in a later function. You're thinking ahead, which is good, but you're thinking ahead of the computer, which is bad. Within the scope of deposit, answer doesn't exist yet, so it has no idea what you're talking about when you ask whether it =="D". It should throw an error, which you can solve a number of ways:
You could put everything into the transaction function (please don't do this)
You could pass answer to both deposit and withdraw, separately, and let them figure out what they each want to do with it (again, nope)
You could, keeping things at about this level of complexity, run your if statements from deposit and withdraw in the transaction function instead, and call whichever of the two matches up (this sounds good, let's do this).
To take option 3, you would actually pull the if statements from each function and then tell each one to run their corresponding functions... and that's it. Like
if answer[0].lower()=="d":
deposit()
elif answer[0].lower()=="w":
withdraw()
else:
print("I'm confused, this is not fun anymore.")
deposit
Your deposit function isn't retaining the new balance when people deposit money. You mentioned this is a simple ATM program so I'm trying to limit the scope of functionality I would expect in grading something like this, and ultimately you probably know better than anyone on StackOverflow what your assignment demands, but do think about how you would keep the new balance :)
withdraw
Same as all of the stuff from before
end
I'm pretty sure exit doesn't take arguments (in other words, you can't leave a parting message on your way out). Just print your goodbye and then exit quietly so to speak.
I haven't brought up things like function parameters or classes (let alone class attributes or methods), any of which could really broaden the scope and complexity of your assignment, but at the same time would make it much more interesting and rewarding to code. You seem to be thinking procedurally, which (in my opinion) is good for getting your arms around how a computer works through things. Keep at it; someday you'll look back at this code and think about how you could have optimized and abstracted certain things so much :P
You have declared answer only inside functions. Add
answer = 0
above the account() function and wherever you use answer, add
global answer
in that function. This is becasus, the scope of answer is limited to particular function and not outside the function. If you use a global variable, it can be used in any function.
Simple as this, you can either make answer a global variable. Not recommended, but an option or you can pass it to the function deposit by typing and to call it use deposit(answer)
def deposit(answer):
If you decide to use calling functions instead of just having every function called no matter what it makes your program more computer friendly.
Also one last thing is you might run into some problems because you have balance as the name of a function along with an int variable.