IDLE does not Run Module - python

New here and very novice in Python. I have a question about Python.
At my workplace, I have some trainings with PL/SQL, where our first task was create RPN calculator. Because I'm not that good in PL/SQL and syntax of that language is strange in my opinion, I made it in Python.
Everything worked smoothly, until a time when I was asked to create function to check if string of values are RPN. Just before that, I made simple program to check if entered values match with those in dictionary, but I stopped to Run.
AcceptedChars = ["0","1","2","3","4","5","6","7","8","9","+","-","/","*"," "]
def checking_for_rpn():
checking = str(input("Enter values for check: "))
for AcceptedCharsCheck in checking:
if not(AcceptedCharsCheck in AcceptedChars):
print("False")
return False
print("Ok")
return True
Then, I added some crazy codes from web for checking RPN and that's fricked my code.
Now, I canot run it by Run Module. Shell displays standard view when it's ready.

Related

What is the difference between running a code through the "console" and running it regularly?

I'm a beginner at Python and coding in general, and I've been primarily using the trinket interpreter to work out some of my scripts. I was just trying to get used to defining a function with if and elif lines alongside the return command.
The code I'm trying to run is a pretty simple one, but when I run it regularly nothing shows up. However, when I run it through the console it
comes out fine. What am I doing wrong?
def the_line(text):
if text == ("just a boy"):
phrase = ("I fly alone")
elif text == "syndrome":
phrase = ("darn you syndrome")
return phrase
the_line("just a boy")
The first picture is what happens when I run it regularly and the second is through the console.
In the console, when you run a statement but don't assign it to anything, the shell will print the resulting object. You call the function but don't save it in a variable, so it is displayed. The "console" in your IDE is also called a Read, Evaluate and Print Loop (REPL).
But your code really just discarded that return value. That's what you see in the first case, the returned object wasn't assigned to anything and the object was deleted. You could assign it to a variable and print, if you want to see it.
def the_line(text):
if text == ("just a boy"):
phrase = ("I fly alone")
elif text == "syndrome":
phrase = ("darn you syndrome")
return phrase
foo = the_line("just a boy")
print(foo)
(As a side note, 4 spaces for indents please. We are not running out of spaces).
This is very clearly explained in Think Python's section 2.4. It has everything to do with the Read-Eval-Print-Loop (REPL) concept.
Briefly, the console is a REPL, so you see the output because it Prints what it Evaluated after Reading something (and then it prompts again for you to input something, that's the loop part). When you run the way you call "regularly", you are in what is called "script mode" (as in Think Python). Script mode simply Reads and Evaluates, there is not the Print-Loop part. A REPL is also called "interactive mode".
One could say that a REPL is very useful for prototyping and testing things out, but script mode is more useful for automation.
What you need to see the output would be like
print(the_line("just a boy"))
for line number 9.

Python command to jump into interactive mode from a script

I have a python script that runs and accepts user input to make decisions. Based on the input I would like to give the user control of the python repl. Here is an example:
def func():
# hand over control to the user
breakpoint()
while True:
print('What would you like to do?\nq: quit\ni: interact')
i = input()
if i=='q':
break
elif i=='i':
func()
else:
print(f'invalid command: {i}')
Calling this code snippet with for example ipython3, the user is prompted for input. When the user presses i, func() is called, at which point I would like the user to be able to type python commands such as print(i).
My current best solution is to then set a breakpoint, the user may then need to type r to get to the right frame and then must then type interact. This is nearly acceptable, but I would like my user to not need to know that I'm using a debugger to give them interactive control, rather I would like them to be given an ipython prompt directly.
I looked at this post from 10 years ago: Jump into a Python Interactive Session mid-program? rz.'s comment looks interesting, but it looks like too much has changed for me to use his answer as is, plus there may be newer ways of doing things.

Write a program that prints out the first N emirps, five on each line, using python

An Emirp is a prime number whose reversal is also a prime number. For example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
The following code compiles and accepts input. The input validation is correct but the program keeps running and does not output anything. I also wanted to know how it's possible to find errors in python. Please ignore indentation errors if there are any.
class negerror(UserWarning):
pass
while True:
prompt = input('Please enter a positive number: ')
try:
number=int(prompt)
if number<=0:
raise negerror
break
except ValueError:
print('You did not enter an integer. Please try again. ')
except negerror:
print('You entered a negative number. Please make sure to enter a positive number')
def isPrime(value):
count=0
for i in range(1,value+1):
if value%i==0:
count=count+1
if count<=2:
return True
else:
return False
def reverse(value):
val=str(value)
val=val[::-1]
val=int(val)
return val
Test=2
countemirps=0
numberinoneline=0
while countemirps<number:
if isPrime(Test) and isPrime(reverse(Test)):
print('%6s'%Test, end = ' ')
countemirps=countemirps+1
Test=Test+1
numberinoneline=numberinoneline+1
if numberinoneline%5==0:
print('\n')
Your isPrime function is off. It counts the number of divisors of value and stores it in variable count. However, you return True if count>2 and False otherwise. It should be the other way around: a prime number has two divisors and composite numbers have more then two. So change the test to count <= 2. Even better and more pythonic, replace the last lines of that function with
return count <= 2
or perhaps
return count == 2
Do you see why that works?
(I see that you have now corrected this error and edited your question but the program still does not work.)
Another error is that in your main loop you have the test
if isPrime(Test) and isPrime(reverse(Test)):
If that test is passed, you print the number and update your variables including Test--all is well. However, if the test fails you do nothing, and in particular the value of Test is not changed. The loop repeats and you do exactly the same test, and nothing changes. The program is stuck in an infinite loop.
You can fix this by moving the line that updates Test out of the if test and place it at the end of the loop so it is executed on each loop. Your loop then becomes
while countemirps<number:
if isPrime(Test) and isPrime(reverse(Test)):
print('%6s'%Test, end = ' ')
countemirps=countemirps+1
numberinoneline=numberinoneline+1
if numberinoneline%5==0:
print('\n')
Test=Test+1
When I test your program now, it seems to work.
There may be other errors as well that I do not see. You should test function isPrime separately from the rest of your code. When that works well, then test function reverse. Then test sections of your code. Running your code all at once makes it difficult to localize and find errors.
Finally, you ask "how it's possible to find errors in Python". This is too broad a question for this site--you should read a book chapter or a tutorial on debugging. But in brief, there are two main approaches for beginners. The first is to liberally put print statements in your code, showing the flow of the program execution and the values of your key variables. If you had place the statement
print(Test)
at the beginning of your loop, you would have seen that the loop was repeating indefinitely and the value of Test was not changing. When the errors seem to be gone, you can remove or comment-out the print statements. Logging can do this a bit more easily
Another, better approach is to use a debugger. I do most of my Python programming in Spyder, a development environment which includes a debugger. I used that to execute your program one line at a time, and one window in Spyder showed my the values of your variables. There also are debuggers that work outside a development environment. I encourage you to find, learn, and use an Integrated Development Environment that includes a debugger. Spyder is a free, excellent one that specializes in scientific programming. I use it for my mathematics programming.

How to transfer a value from a function in one script to another script without re-running the function (python)?

I'm really new to programming in general and very inexperienced, and I'm learning python as I think it's more simple than other languages. Anyway, I'm trying to use Flask-Ask with ngrok to program an Alexa skill to check data online (which changes a couple of times per hour). The script takes four different numbers (from a different URL) and organizes it into a dictionary, and uses Selenium and phantomjs to access the data.
Obviously, this exceeds the 8-10 second maximum runtime for an intent before Alexa decides that it's taken too long and returns an error message (I know its timing out as ngrok and the python log would show if an actual error occurred, and it invariably occurs after 8-10 seconds even though after 8-10 seconds it should be in the middle of the script). I've read that I could just reprompt it, but I don't know how and that would only give me 8-10 more seconds, and the script usually takes about 25 seconds just to get the data from the internet (and then maybe a second to turn it into a dictionary).
I tried putting the getData function right after the intent that runs when the Alexa skill is first invoked, but it only runs when I initialize my local server and just holds the data for every new Alexa session. Because the data changes frequently, I want it to perform the function every time I start a new session for the skill with Alexa.
So, I decided just to outsource the function that actually gets the data to another script, and make that other script run constantly in a loop. Here's the code I used.
import time
def getData():
username = '' #username hidden for anonymity
password = '' #password hidden for anonymity
browser = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
browser.get("https://gradebook.com") #actual website name changed
browser.find_element_by_name("username").clear()
browser.find_element_by_name("username").send_keys(username)
browser.find_element_by_name("password").clear()
browser.find_element_by_name("password").send_keys(password)
browser.find_element_by_name("password").send_keys(Keys.RETURN)
global currentgrades
currentgrades = []
gradeids = ['2018202', '2018185', '2018223', '2018626', '2018473', '2018871', '2018886']
for x in range(0, len(gradeids)):
try:
gradeurl = "https://www.gradebook.com/grades/"
browser.get(gradeurl)
grade = browser.find_element_by_id("currentStudentGrade[]").get_attribute('innerHTML').encode('utf8')[0:3]
if grade[2] != "%":
grade = browser.find_element_by_id("currentStudentGrade[]").get_attribute('innerHTML').encode('utf8')[0:4]
if grade[1] == "%":
grade = browser.find_element_by_id("currentStudentGrade[]").get_attribute('innerHTML').encode('utf8')[0:1]
currentgrades.append(grade)
except Exception:
currentgrades.append('No assignments found')
continue
dictionary = {"class1": currentgrades[0], "class2": currentgrades[1], "class3": currentgrades[2], "class4": currentgrades[3], "class5": currentgrades[4], "class6": currentgrades[5], "class7": currentgrades[6]}
return dictionary
def run():
dictionary = getData()
time.sleep(60)
That script runs constantly and does what I want, but then in my other script, I don't know how to just call the dictionary variable. When I use
from getdata.py import dictionary
in the Flask-ask script it just runs the loop and constantly gets the data. I just want the Flask-ask script to take the variable defined in the "run" function and then use it without running any of the actual scripts defined in the getdata script, which have already run and gotten the correct data. If it matters, both scripts are running in Terminal on a MacBook.
Is there any way to do what I'm asking about, or are there any easier workarounds? Any and all help is appreciated!
It sounds like you want to import the function, so you can run it; rather than importing the dictionary.
try deleting the run function and then in your other script
from getdata import getData
Then each time you write getData() it will run your code and get a new up-to-date dictionary.
Is this what you were asking about?
This issue has been resolved.
As for the original question, I didn't figure out how to make it just import the dictionary instead of first running the function to generate the dictionary. Furthermore, I realized there had to be a more practical solution than constantly running a script like that, and even then not getting brand new data.
My solution was to make the script that gets the data start running at the same time as the launch function. Here was the final script for the first intent (the rest of it remained the same):
#ask.intent("start_skill")
def start_skill():
welcome_message = 'What is the password?'
thread = threading.Thread(target=getData, args=())
thread.daemon = True
thread.start()
return question(welcome_message)
def getData():
#script to get data here
#other intents and rest of script here
By design, the skill requested a numeric passcode to make sure I was the one using it before it was willing to read the data (which was probably pointless, but this skill is at least as much for my own educational reasons as for practical reasons, so, for the extra practice, I wanted this to have as many features as I could possibly justify). So, by the time you would actually be able to ask for the data, the script to get the data will have finished running (I have tested this and it seems to work without fail).

how to check if any program is running in windows using python

I would like to use win32 in python to create 2 functions... 1. A function that checks if a certain application is running. 2. A function that checks if an application is installed...
I have tried the following to check if something is running;
def IsRunning(ProgramName):
if win32ui.FindWindow(None, ProgramName):
print("its running")
return True
else:
print("its not running!")
but the findwindow always throws an error if the program is not running before my program ever gets to the else statement and I do not know how to bypass that....
I needed to pass it like this;
def IsRunning(WindowName):
try:
if win32ui.FindWindow(None, WindowName):
print("its running")
return True
except win32ui.error:
print("its not running!")
return False
You need to put the window title exactly for it to pass the test and return True...
The next thing I want to write is a similar function that uses regular expressions to find any part of a title name...
Brilliant!!! Happy now :)
The only thing with this, is that if the Applications creator decides to change the title of the main window of the program you are trying to test for, it will no longer work... I was hoping for a much more robust way of doing it... i.e. through some kind of unique process code!
in any case this will do for the time being, but if anyone has a more definitive answer please let me know...

Categories