How to repeat an instruction of raw_input - python

I have a question: how to repeat an instruction of raw_input in python 2.7.5?
print("This is a NotePad")
main = raw_input()
this is the code(I started 3 minutes ago.)
I can't find an answer to my question on Google.
This is the code with me trying but suffering
print("This is a NotePad")
main = raw_input()
for i in range(12000):
main
The error is Process finished with exit code 0
Okay, it's not an error but it's not what I was expecting.

main = raw_input() does not make main a "macro" equivalent to raw_input(). It assigns the return value of a single call of raw_input to the name main. The closest thing to what you appear to be trying to do is to assign the value of the name raw_input itself (the function) to the name main, then call that function in the loop.
main = raw_input # Another name for the same function
for i in range(12000):
# Resolve the name lookup, then call the resulting function
main()

Related

can't print variable from previous function in python [duplicate]

This question already has answers here:
Cannot call a variable from another function
(4 answers)
Closed 2 years ago.
I have got a database program to keep data in, and I can't solve this problem:
I have got two functions. When you input A into the program
the function called addy() starts
and ask for more input into a variable
then it returns to the main screen,
then the user can Input S
which starts Show()
and then it's supposed to show what you have added into the variable
PROBLEM:
It's not getting the value from the previous definition.
CODE:
def addy():
os.system('cls')
addel = input('what is the name of the operating system?: \n')
os.system('cls')
time.sleep(1)
print(addel + ' Has been added to the database!')
time.sleep(2)
program()
def show():
print('Heres a list of the operating systems you have added:')
time.sleep(5)
program()
addel = addy()
print(addel) # this should print the value from the previous function
The are 2 reasons why
Addel is a local variable not a global one. Therefore, you can only use it in your addy function.
Say your intent was not to use it which is what it seems, you wrote
addel = addy()
the function addy has no return value so your code wont work.
to fix this write
return addel
as the last line in your addy function then it will work because now the function has a return value.

How to terminate exec() function in python if it takes too long?

I am trying to make a function that takes in user's code and runs it:
code = input("Your code: ")
def execute(c):
exec(c)
execute(code)
However, if the user enters in an infinite loop, the function runs forever.
Is there a way to terminate the exec() function if the function takes too long? For example, if the code takes longer than 15 seconds to execute, the programme terminates.
Thanks in advance.
There are multiple solutions,
For example you could pass a global variable stop condition and raise exception from inside the exec once condition has met.
Other solution would be to run exec in a separate thread/process and sending some stop signal once desired.
You can use wrapt_timeout_decorator
from wrapt_timeout_decorator import *
#timeout(15)
def execute(c):
exec(c)
code = input("Your code: ")
execute(code)
This will throw an exception if the function takes more than 15 sec to finish - TimeoutError: Function execute timed out after 15.0 seconds

What is the entry point of Python program of multiple modules?

I want to understand from which point a Python program starts running. I have previous experience in Java. In Java every program starts from main() function of it's Main class. Knowing this I can determine the execution sequence of other classes or functions of other Classes. I know that in Python I can control program execution sequence by using __name__ like this:
def main():
print("This is the main routine.")
if __name__ == "__main__":
main()
But when we don't use __name__ then what is the starting line of my Python program?
Interpreter starts to interpret file line by line from the beginning.
If it encounters function definition, it adds it into the globals
dict. If it encounters function call, it searches it in globals
dict and executes or fail.
# foo.py
def foo():
print "hello"
foo()
def test()
print "test"
print "global_string"
if __name__ == "__main__":
print "executed"
else:
print "imported"
Output
hello
global_string
executed
Interpreter starts to interpret foo.py line by line from the beginning like first the function definition it adds to globals dict and then it encounters the call to the function foo() and execute it so it prints hello.
After that, it adds test() to global dict but there's no function call to this function so it will not execute the function.
After that print statement will execute will print global_string.
After that, if condition will execute and in this case, it matched and will print executed.

Get user input while printing to the screen

I would like to get user input while printing to the screen. I researched this a lot. but didn't find anything. I'm not very advanced with class programming in Python, so I didn't understand the other examples on stackoverflow.
Example:
import time
def user_input():
while True:
raw_input("say smth: ")
def output():
while True:
time.sleep(3)
print "hi"
input()
output()
I want the prompt to stay, even if the output is printing "hi". I already tried an example, but the input prompt disappears even if it is in a while loop.
First, let's go over your code
import time
def user_input():
while True:
raw_input("say smth: ")
def output():
while True:
time.sleep(3)
print "hi"
input()
output()
You are calling input() which is not actually your function name. It's user_input(). Also, once user_input() is called, output() will never be called because the while True condition in user_input() is always True, meaning it never exits outside the function.
Also, if you want to do something with multithreading, but you don't understand classes in Python, you should probably do a tutorial related to classes.
Take a look at this other StackOverflow Post on a multithreaded program.

How to pause and wait for command input in a Python script

Is it possible to have a script like the following in Python?
...
Pause
->
Wait for the user to execute some commands in the terminal (e.g.
to print the value of a variable, to import a library, or whatever).
The script will keep waiting if the user does not input anything.
->
Continue execution of the remaining part of the script
Essentially the script gives the control to the Python command line interpreter temporarily, and resume after the user somehow finishes that part.
What I come up with (inspired by the answer) is something like the following:
x = 1
i_cmd = 1
while True:
s = raw_input('Input [{0:d}] '.format(i_cmd))
i_cmd += 1
n = len(s)
if n > 0 and s.lower() == 'break'[0:n]:
break
exec(s)
print 'x = ', x
print 'I am out of the loop.'
if you are using Python 2.x: raw_input()
Python 3.x: input()
Example:
# Do some stuff in script
variable = raw_input('input something!: ')
# Do stuff with variable
The best way I know to do this is to use the pdb debugger. So put
import pdb
at the top of your program, and then use
pdb.set_trace()
for your "pause".
At the (Pdb) prompt you can enter commands such as
(Pdb) print 'x = ', x
and you can also step through code, though that's not your goal here. When you are done simply type
(Pdb) c
or any subset of the word 'continue', and the code will resume execution.
A nice easy introduction to the debugger as of Nov 2015 is at Debugging in Python, but there are of course many such sources if you google 'python debugger' or 'python pdb'.
Waiting for user input to 'proceed':
The input function will indeed stop execution of the script until a user does something. Here's an example showing how execution may be manually continued after reviewing pre-determined variables of interest:
var1 = "Interesting value to see"
print("My variable of interest is {}".format(var1))
key_pressed = input('Press ENTER to continue: ')
Proceed after waiting pre-defined time:
Another case I find to be helpful is to put in a delay, so that I can read previous outputs and decide to Ctrl + C if I want the script to terminate at a nice point, but continue if I do nothing.
import time.sleep
var2 = "Some value I want to see"
print("My variable of interest is {}".format(var2))
print("Sleeping for 5 seconds")
time.sleep(5) # Delay for 5 seconds
Actual Debugger for executable Command Line:
Please see answers above on using pdb for stepping through code
Reference: Python’s time.sleep() – Pause, Stop, Wait or Sleep your Python Code
I think you are looking for something like this:
import re
# Get user's name
name = raw_input("Please enter name: ")
# While name has incorrect characters
while re.search('[^a-zA-Z\n]',name):
# Print out an error
print("illegal name - Please use only letters")
# Ask for the name again (if it's incorrect, while loop starts again)
name = raw_input("Please enter name: ")
Simply use the input() function as follows:
# Code to be run before pause
input() # Waits for user to type any character and
# press Enter or just press Enter twice
# Code to be run after pause

Categories

Resources