How do I make this restart after the number is guessed? - python

from flask import Flask
from random import random, randint
def restart():
number = randint(1, 10)
print(number)
app = Flask(__name__)
#app.route('/')
def start():
return 'What number am I?'
#app.route(f'/{number}')
def found():
return 'You found me!'
#app.route('/<num>')
def check(num):
lownum = int(num)
if lownum < number:
return 'Too Low!'
if lownum > number:
return 'Too High!'
if __name__ == "__main__":
app.run(debug=True)
restart()
Detecting if the number is high or low works fine it's just I want to make it make a new number after the previous number is found. I there a simple way to do this?

Don't use the found() route, check for a matching number in check(). Then you can reset number when then guess the number.
Also, if __name__ == "__main__": is normally put at top-level, not inside the function.
from flask import Flask
from random import random, randint
def restart():
number = randint(1, 10)
print(number)
app = Flask(__name__)
#app.route('/')
def start():
return 'What number am I?'
#app.route('/<num>')
def check(num):
nonlocal number
lownum = int(num)
if lownum < number:
return 'Too Low!'
if lownum > number:
return 'Too High!'
number = randint(1, 10)
return 'You found me!'
app.run(debug=True)
if __name__ == "__main__":
restart()

Related

How can I save the random output to use it in another function in python

I am new to python3 I am trying very hard to add the output of the function, is there any way that I can save an output of an random integer
so that i can altogether add it please help me.
def dice():
import random
rollball = int(random.uniform(1, 6))
return (rollball)
def dice2():
import random
rollball = int(random.uniform(1, 6))
return (rollball)
print(dice())
input("you have 10 chances left")
print(dice2())
input("you have 9 chances left")
print(dice() + dice2())
#i want to print this last function but by adding only this first and second nothing else
Use a variable or set a global variable for it
import random
def dice():
rollball = int(random.uniform(1, 6))
return (rollball)
def dice2():
rollball = int(random.uniform(1, 6))
return (rollball)
roll1 = dice()
print(roll1)
input("you have 10 chances left")
roll2 = dice2()
print(roll2)
input("you have 9 chances left")
print(roll1 + roll2)
#i want to print this last function
Or
use
import random
roll1 = 0
roll2 = 0
def dice():
global roll1
rollball = int(random.uniform(1, 6))
roll1 = rollball
return (rollball)
def dice2():
global roll2
rollball = int(random.uniform(1, 6))
roll2 = rollball
return (rollball)
print(dice())
input("you have 10 chances left")
print(dice2())
input("you have 9 chances left")
print(roll1 + roll2)
#i want to print this last function
This should provide you with a basic example. I would spend some time searching out some resources to help you get started with the basics of python programming; There are an enumerable amount. You'll find it much easier to progress if you understand how to do the little things first.
#!/usr/bin/env python3.9
"""
Basic Function Usage
"""
from random import uniform
from typing import NoReturn
def dice() -> int:
"""A dice function
Returns:
(int)
"""
return int(uniform(1, 6))
def dice2() -> int:
"""Another dice function
Returns:
(int)
"""
return int(uniform(1, 6))
def main() -> NoReturn:
""" Main
Returns:
(NoReturn)"""
d = dice()
d2 = dice2()
print('Dice: ', d)
print('Dice2:', d2)
print(f'Dice Total: {d + d2}')
if __name__ == '__main__':
try:
main()
except Exception as excp:
from sys import exc_info
from traceback import print_exception
print_exception(*exc_info())
Output:
Dice: 1
Dice2: 3
Dice Total: 4
Some possibly helpful resources:
Real Python - Defining Your Own Python Function
Real Python - f-Strings
Official Python Documentation

input() function throwing error in presence of threading in 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...

2 actions at the same time in python

I don't know how to make a function work while the program is waiting for an input.
I have tried with threading module but it didn't work. Also I've tried with the code below but it runs the function after someone have answered and not while they're thinking the answer.
import random
def whileAnswering():
print("You can do it")
a = random.randint(0, 9)
ans = 2*a
q = ""
q = int(input("Calculate 2 * %d" %(a)))
while q != int():
whileAnswering()
You can use threading or multiprocessing to implement this. Here is a code example for you:
import random
import time
from threading import Thread
class WaitForUserInput(Thread):
def run(self):
# your original code
a = random.randint(0, 9)
ans = 2 * a
q = ""
q = int(input("Calculate 2 * %d\n" % a))
# added these lines of code from my side :)
if q == ans:
print('You did it!')
def print_message():
print("You can do it")
time.sleep(3)
if __name__ == '__main__':
waiting_for_input = WaitForUserInput()
waiting_for_input.start()
while waiting_for_input.is_alive():
print_message()
You may want to look into chapter 13 from this book by Dusty Phillips

I am using idle for python but the main function is not executing properly, can someone tell me on this where am i doing wrong?

PFB Code it's giving me only the number but its not executing the function inside the main function
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
def main():
n = int(input("Enter the number : "))
factorial(n)
main()
output:
Enter the number: 8
8
You need to return the result from factorial:
def main():
n = int(input("Enter the number : "))
return factorial(n)

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"

Categories