input() function throwing error in presence of threading in python - python

Following code works as expected. It takes two inputs and outputs the same
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n,str(parents)))
if __name__ == "__main__":
main()
The moment I add this additional code for enabling more depth for recursion and threading, it throws a value error. Inputs I give are '3' for the first input (without quotes) and '-1 0 1' for the second input (without quotes).
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n,str(parents)))
sys.setrecursionlimit(10**7) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
threading.Thread(target=main).start()
if __name__ == "__main__":
main()

The main() function is called from two places.
First, From the thread main() function will be called
threading.Thread(target=main).start()
Second, the __main__ will be called. So here also the main() function is called.
if __name__ == "__main__":
main()
So you were asked to enter the "input n" two times. While entering the string value ('-1 0 1') the second time, you are giving value to the "input n" again. It's expecting int as input. So the issue is happening.
Code Fix:
Move the thread inside main and remove the existing main()
import sys
import threading
def main():
n = int(input("input n:"))
parents = list(map(int, input("input parents:").split()))
print("n is {0} and parents is {1}".format(n, str(parents)))
if __name__ == "__main__":
sys.setrecursionlimit(10 ** 7) # max depth of recursion
threading.stack_size(2 ** 27) # new thread will get stack of such size
threading.Thread(target=main).start()
I hope it'll help you...

Related

Terminate Python program if input isn't specified in due timeframe

I'm trying to terminate python program if an input isn't provided by user within specific time frame, say - 5 seconds.
The code has been taken and edited from mediocrity's answer
import sys
import time
from threading import Thread
x = None
def check():
global x
time.sleep(5)
if x:
print("Input has been given!")
return
sys.exit()
Thread(target=check).start()
x = input("Input something: ")
But it keeps waiting for the input and doesn't terminate, unless the input is given.
How could I change the code so that it executes as inteded?
you should try this code its working on vscode
import sys
import time
from threading import Thread
x = None
def check():
global x
time.sleep(5)
if x:
print("Input has been given!")
return
else:
print("input has not been given for last 5 sec")
sys.exit()
if __name__=='__main__':
t1=Thread(target=check)
t1.start()
x = input("Input something: ")
t1.join()

Passing values out of functions in python

I am trying to get my head around python. This is a snippet of code where I want to have the user input an option in a function and then use that input in another function(s). This tells me 'myInput' is not defined.
def main():
myInput = input("Enter a number ")
# This is the main function that will be the primary executuable function - the start of the program
return(myInput)
if __name__ == '__main__':
main()
#
print (myInput)
Function main returns the user's input, so try this:
if __name__ == '__main__':
myInput = main()

Parallel multiprocessing in python easy example

I need to say that multiprocessing is something new to me. I read some about it but it makes me more confused. I want to understand it on a simple example. Let's assume that we have 2 functions in first one I just increment 'a' variable and then assign it to 'number' variable, in second I start first function and each every one second I want to print 'number' variable. It should looks like:
global number
def what_number():
a=1
while True:
a+=1
number=a
def read_number():
while True:
--> #here I need to start 'what_number' function <--
time.sleep(1)
print(number)
if __name__ == "__main__":
read_number()
How can I do that? Is there an easy and proper way to do that ?
UPDATE:
I saw noxdafox answer I'm really thankfull but it isn't exactly what I want. First of all I don't want send value in first function ('main' in noxdafox code). Second I don't want to get all values so quene will won't work. I need to get after each second number of while loops. Code should be something like :
import multiprocessing
import time
number = 0
def child_process():
global number
while True:
number += 1
print(number)
def main():
process = multiprocessing.Process(target=child_process)
process.start()
while True:
print("should get same number:",number)
time.sleep(0.001)
if __name__ == "__main__":
main()
If u run above code you get something like:
but this blue selected values should be same ! and that's the main problem :)
P.S sorry for chaos
Ok it takes some time but I figured it out. All it was about Sharing state between processes now all it works like charm. Code :
from multiprocessing import Process, Value
import time
def child_process(number):
number.value = 0
while True:
number.value += 1
#print(number)
def main():
num = Value('i')
process = Process(target=child_process, args=(num,))
process.start()
while True:
print("should get same number:", num.value)
time.sleep(1)
if __name__ == "__main__":
main()
As processes live in separate memory address spaces, you cannot share variables. Moreover, you are using global variables incorrectly. Here you can see an example on how to use global variables.
The most straightforward way to share information between processes is via a Pipe or Queue.
import multiprocessing
def child_process(queue):
while True:
number = queue.get()
number += 1
queue.put(number)
def main():
number = 0
queue = multiprocessing.Queue()
process = multiprocessing.Process(target=child_process, args=[queue])
process.start()
while True:
print("Sending %d" % number)
queue.put(number)
number = queue.get()
print("Received %d" % number)
time.sleep(1)
if __name__ == "__main__":
main()

Addition Python Function

So I have to create a program that asks the user 5 addition questions and they can type the right answer. I am very new at python and functions in general so helpful answers only please. I know how to get random numbers and make it so the question for ex: "What is 4 + 5?" I just do not know how to ask 5 different addition questions within the function. This is what I have.
import random
def add():
num1=random.randint(1,10)
num2=random.randint(1,10)
return num1,num2
def main():
x,y= add()
plus=int(input("What is {} + {} ?".format(x,y)))
main()
I don't get an error when I run your code. Here is an answer for you:
Right now your main() is asking for an input back from the user and each time main() is called it will ask for a different number, so if you like you can do something like this:
for _ in range(5):
main()
But from the sound of it, you want to have the function main() ask all of the questions, namely - something like this:
def main():
for _ in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
Simplest is to use a counting loop:
def main():
for i in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
The following program demonstrates how to have a program ask five addition questions:
import random
import sys
def main():
for count in range(5):
ask_addition_question()
def ask_addition_question():
numbers = random.randrange(10), random.randrange(10)
answer = get_number('What is {} + {}? '.format(*numbers))
total = sum(numbers)
if answer == total:
print('That is correct!')
else:
print('Actually, the correct answer is {}.'.format(total))
def get_number(query):
while True:
try:
return int(input(query))
except KeyboardInterrupt:
print('Please try again.')
except EOFError:
sys.exit()
except ValueError:
print('You must enter a number.')
if __name__ == '__main__':
main()
Just use a for loop to ask the user 5 times
def main():
for i in range(5):
x,y = add()
plus = int(input("What is {} + {} ?".format(x,y)))
To check if the answer is correct just you can do:
if x + y == plus: print "good"
else: print "bad"

Python- how to init random function

I am a beginer python learner. I am trying to create a basic dictionary where random meaning of words will come and user have to input the correct word. I used the following method, but random doesn't work. I always get the first word first and when the last word finishes, I get infinite 'none' until I kill it. Using python 3.2
from random import choice
print("Welcome , let's get started")
input()
def word():
print('Humiliate')
a = input(':')
while a == 'abasement':
break
else:
word()
# --------------------------------------------------------- #
def word1():
print('Swelling')
a = input(':')
while a == 'billowing':
break
else:
word()
# ------------------------------------------------------------ #
wooo = [word(),word1()]
while 1==1:
print(choice(wooo))
is there any faster way of doing this and get real random? I tried classes but it seems harder than this. Also, is there any way I can make python not care about weather the input is capital letter or not?
To answer one part of your question ("is there any way I can make python not care about weather the input is capital letter or not?"): use some_string.lower():
>>> "foo".lower() == "foo"
True
>>> "FOO".lower() == "foo"
True
An this is to help you how you could improve the structure of your code:
import sys
from random import choice
WORDPAIRS = [('Humiliate', 'abasement'), ('Swelling', 'billowing')]
def ask():
pair = choice(WORDPAIRS)
while True:
answer = raw_input("%s: " % pair[0]).lower()
if answer == pair[1]:
print "well done!"
return
def main():
try:
while True:
ask()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()
It works like that:
$ python lulu.py
Swelling: lol
Swelling: rofl
Swelling: billowing
well done!
Humiliate: rofl
Humiliate: Abasement
well done!
Swelling: BILLOWING
well done!
Humiliate: ^C
$
wooo = [word, word1]
while 1:
print(choice(wooo)())
But in any case it will print you None, cause both of your functions return nothing (None).

Categories