hello all I am python programmer
I made a program with spyder IDE with python 3.7.0
when I ran this program the program didn't execute the desired action
that is they don't shutdown this pc or lock it and doesn't open cmd
can you show me the mistake and if possible correct the code by typing below
import os
import ctypes
command = "cmd"
print ("select from any commands")
print ('1.open CMD')
print ('2.shutdown pc')
print ('3.restart pc')
print ('4.lock pc')
choice = input()
if choice == 1: #starts command prompt
os.system(command);
if choice == 2: #trigger shutdown
os.system("shutdown -p");
if choice == 3: #trigger restart
os.system("shutdown -r");
if choice == 4: #trigger lockscreem
ctypes.windll.user32.LockWorkStation()
[Python 3]: input([prompt]) returns a string. When comparing a string with an integer (e.g. "1" == 1), the result will always be False.
To fix your problem, either:
Convert each of the 4 values (used in comparisons) to a string, by placing its value between quotes e.g:
if choice == "1":
Convert input's result to an integer e.g.:
choice = int(input())
but you'll have to enclose that in a try / except block (to avoid program crash if user doesn't input an integer)
Notes (to improve your code):
When calling functions, always check their return value (which may be an error indicator)
Since the 4 are choices, then they are mutually exclusive, meaning that only one (or none) will be executed. As a consequence, you could replace each of the last 3 if clauses by an elif, so if the program entered one branch, it won't test for the ones that follow it
You could also add a final else clause, where you could let the user know that none of the choices executed (the value entered was different than all of them)
Instead of the 5 print statements (for the menu), you could just pass one string (you'll have to format it) to input:
choice = input("select from any commands:\n 1.open CMD\n 2.shutdown pc\n 3.restart pc\n 4.lock pc\n")
For better flexibility, you could use the subprocess module (instead of os.system) to execute external commands
ctypes is a tricky topic, and although if for this case things are fine, for more complex ones (e.g. calling a function with parameters) it might not work as expected. There are many examples (on this site and on others) showing how to deal with such cases
When program doesn't work as expected, you could always debug it, or at least print the variables involved, and thus increase the chances of figuring the problem yourself
Related
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 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 have a big dictionary and some of the elements occasionally end up with illegal values. I want to figure out where the illegal values are coming from. PyCharm should constantly monitor the values of my dictionary, and the moment any of them take the illegal value, it should break and let me inspect the state of the program.
I know I can do this by just creating a getter/setter for my dictionary instead of accessing it directly, and then break inside the setter with an appropriate condition.
Is there a way to do it without modifying my code?
I'm not sure if this answers your question but you can set a breakpoint on the line of code you want to break at, right click on that break point once it is set and then apply a condition.
An example of such a condition could be:
x > 5
Once you are at the stage in your loop/code where this condition is true i.e. when x = 6 then it will break and you can inspect all the current values/ status of your code.
Hope this helps
I am new to programming, and new to Python. I am running Python 3 on Windows 10, and I am having a strange problem. I built the following script, and it doesn't work:
def count_item(sequence, item):
return sequence.count(item)
count_item([1,2,1,1], 1)
When I run it, it comes up empty. Not so much as an error, or the "none" that Python likes to give.
However, when I run it from the interactive shell:
>>> item = 1
>>> sequence = [1,2,1,1]
>>> sequence.count(item)
3
I am guessing that this has something to do with how functions work on a deep level in Python, but I am just not sure.
Any help would be appreciated.
The REPL, or interactive shell, is built to be interactive. One way that is manifested is that you don't need to print variables and other objects - you can just type their name, hit Enter, and the relevant info shows up.
However, when actually running a program, you need to explicitly call the print() function in order to make anything show up on the screen. return just returns a value to the calling function or statement. So, for your code, modify the last line to:
print(count_item([1,2,1,1], 1))
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.