How to display a message when a prompted input isn't entered? - python

I'm getting back into programming, so I started a project that rolls a die based on the amount of side's a user inputs, and the amount of times the user wants the die to be rolled. I'm having trouble with a part of the program involving time. When the user doesn't input within ten seconds of being prompted, I want a message to be displayed. If nothing is entered in another ten seconds a message should be displayed, so on and so forth. I'm using python.
Right now most of the program is working, but time is only checked after an input is taken. Thus a user could sit on the input screen infinitely and not get prompted. I'm really stuck on how to simultaneously wait for an input, while checking the amount of time elapsed since being prompted for the input.
def roll(x, y):
rvalues = []
while(y > 0):
y -= 1
rvalues.append(random.randint(1, x))
return rvalues
def waitingInput():
# used to track the time it takes for user to input
start = time.time()
sides = int(input("How many sides does the die have? "))
times = int(input("How many times should the die be rolled? "))
tElapsed = time.time() - start
if tElapsed <= 10:
tElapsed = time.time() - start
rInfo = roll(sides, times)
print("Each side occurs the following number of times:")
print(Counter(rInfo))
waitingInput()
else:
print("I'm waiting...")
waitingInput()
Any advice would be appreciated. I'm looking to improve my coding any way I can, so constructive criticism about unrelated code is welcome.

Situations like this call for a threaded timer class. The python standard library provides one:
import threading
...
def waitingInput():
# create and start the timer before asking for user input
timer = threading.Timer(10, print, ("I'm waiting...",))
timer.start()
sides = int(input("How many sides does the die have? "))
times = int(input("How many times should the die be rolled? "))
# once the user has provided input, stop the timer
timer.cancel()
rInfo = roll(sides, times)
print("Each side occurs the following number of times:")
print(Counter(rInfo))

Related

How to make countdown timer in Python without input?

Iv'e been trying to create a countdown timer for a game in python however i'm not sure how to code it without including the input question for the time at the beginning of the code.
So far the code looks like this
import time
import datetime
# Create class that acts as a countdown
def countdown(s):
# Calculate the total number of seconds
total_seconds = s
# While loop that checks if total_seconds reaches zero
# If not zero, decrement total time by one second
while total_seconds > 0:
# Timer represents time left on countdown
timer = datetime.timedelta(seconds = total_seconds)
# Prints the time left on the timer
print(timer, end="\r")
# Delays the program one second
time.sleep(1)
# Reduces total time by one second
total_seconds -= 1
print("You have been caught.")
# Inputs for hours, minutes, seconds on timer
s = input("Enter the time in seconds: ")
countdown(int(s))
exit()
I want to make the code so it has an automatic countdown for 10 seconds as soon as the user presses enter. Any ideas?
If I understand your question correctly you just want the user to press the enter key instead of actually inputing a number? then you can just hard code the time value and call the function with that value, while using an empty input call to wait for a keypress.
input("Press enter to continue...")
countdown(10)
exit()
here you're not storing the value from input anywhere and just using the input function to block until the user presses enter.
You could do it this way:
import time
def countdown(time_sec):
while time_sec:
minutes, secs = divmod(time_sec, 60)
time_format = f'{minutes}:{secs}'
print(time_format, end='\r')
time.sleep(1)
time_sec -= 1
print("stop")
countdown(5)

Creating a multiple user countdown counter (Python)

I was wondering if someone can point me in the right direction of a basic script.
This is for a game I created and wanted to create a countdown script to go along with it.
I want be able to have 4 users in which the program will first will ask for their name. After that each user will take turns entering their score starting at 100 and decreasing based on their input. Once they hit zero they win. Once the first person hits 0 the others will have a chance to as well until the end of the round. Each 4 inputs will be considered 1 round.
There will be a lot more to the game but I just need the start. I am new to Python but the easiest way for me to learn is to start off on a working script
Thanks!
Are you looking for something like this?
import cmd
number_users = 4
number_rounds = 10 # or whatever
user_names = [None]*number_users
user_scores = [None]*number_users
for i in range(number_users):
print("Enter name for user #{}: ".format(i+1))
user_names[i] = input()
user_scores[i] = 100
for round_number in range(number_rounds):
print(" --- ROUND {} ---".format(round_number+1))
for i in range(number_users):
print("{}, Enter your score: ".format(user_names[i]))
user_scores[i] = input()
print("--- Scores for Round {} ---".format(round_number+1))
for i in range(number_users):
print("{} : {}".format(user_names[i], user_scores[i]))
print("Done")

python dice rolling restart script

i want to restart my script automatically i have a dice rolling script and i don't want to have to reset my script manually between each roll this is my script.
import random
from random import randrange
from random import randint
r = randint
min = 1
max = 6
rolls = int(float(input('how menny times do you want to roll:')))
for x in range(rolls):
print ('Rolling the dices...')
print ('The value is....')
print (r(min, max))
i have tried a few ways to do it but none of them worked
I'm not 100% sure what you were actually trying to do, but here is a program that I wrote that will roll 2 die at a time, and will generate however many rolls you would like to roll. -not the best practice to use recursive (main calls main from within itself), but it's not really an issue with something this basic.
*replace raw_input with input if you are using Python 3+. I use 2.7 so I use raw_input
import time
import random
def roll_multiple():
#honestly this is all you need to do what you want to do, the rest just turns it into a game and allows multiple runs
roll_number = int(raw_input("How Many Times Would You Like to Roll?\n"))
for i in range(roll_number):
print"You Rolled A ", random.randrange(1,6,1), " and a ", random.randrange(1,6,1)
#that's it! if you do these 3 lines, it will ask for how many times, and for each item in range of roll_number (whatever you input) it will run the print below and generate new numbers for each roll.
def main():
print("Welcome to Craps 2.0")
playing = raw_input("Press Enter to Roll or Q to quit")
if playing == 'q':
print("Thanks for Playing")
time.sleep(2)
quit()
elif playing != 'q':
roll_multiple()
main()
main()

My life calculater project

I'm currently working on a life calculator that i have programmed in python. I need ideas of what to add to it and examples on how to add it and also how do i add a end control so i can just input end and the program stops. I'm trying to make this better because i plan to take it to a technology fair im going to. Here is my code.
print("The Life Calculator")
name = input("What is you're name? ")
age = int(input("age: "))
months = age * 12 #This equals to how many months you have been alive.
days = age * 365 #This equals to how many days you have been alive.
hours = age * 8765.81 #This equals to how many hours you have been alive.
minutes = age * 31556926 #This equals to how many minutes you have been alive.
seconds = age * 3.156e+7 #This equals to how many seconds you have been alive.
miliseconds = age * 3.15569e10 #This equals to how many miliseconds you have been alive.
microseconds = age * 3.156e+13 #This equals to how many microseconds you have been alive.
nanoseconds = age * 3.156e+16 #This equals to how many nanoseconds you have been alive.
print("This is how many months you have been alive.")
print (months) #This shows how many months you have been alive.
print("This is how many days you have been alive.")
print (days) #This shows how many months you have been alive.
print("This is how many hours you have been alive.")
print (hours) #This shows how many hours you have been alive.
print("This is how many minutes you have been alive.")
print (minutes) #This shows how many minutes you have been alive.
print("This is how many seconds you have been alive.")
print (seconds) #This shows how many seconds you have been alive.
print("This is how many miliseconds you have been alive.")
print (miliseconds) #This shows how many miliseconds you have been alive.
print("This is how many microseconds you have been alive.")
print (microseconds) #This shows how many microseconds you have been alive.
print("This is how many nanoseconds you have been alive.")
print (nanoseconds) #This shows how many nanoseconds you have been alive.
lastline = ("this is how long you have been alive, so what are you going to do with the rest of your life?")
print (name)
print (lastline)
Here is a spiffed-up version.
I took a lot of the repetitive statements and converted them to data:
from collections import namedtuple
TimeUnit = namedtuple("TimeUnit", ["name", "per_year"])
units = [
TimeUnit("decade", 0.1 ),
TimeUnit("month", 12.0 ),
TimeUnit("fortnight", 26.09),
TimeUnit("day", 365.25),
TimeUnit("hour", 8765.81),
TimeUnit("minute", 31556926),
TimeUnit("second", 3.156e+7),
TimeUnit("millisecond", 3.15569e10)
]
def get_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
pass
def main():
print("The Life Calculator")
name = input("What is your name? ")
years = get_float("What is your age? ")
print("You have been alive for:")
for unit in units:
print(" {} {}s".format(years * unit.per_year, unit.name))
print("what are you going to do with the rest of your life, {}?".format(name))
if __name__ == "__main__":
main()
Your program is running once, not multiple times so actually you don't have to ask to user for end. However, if you want to run your program until user types end, you have to put that codes in a while loop.
If you want to stop running your program when user types end, just add this line to your program;
while True:
#your codes here
#end of your codes add this line
ask=input("Want to end it?")
if ask.lower()=="end":
break
Using lower() so even user types END or eND or EnD etc. it will be ok.

How do you make python read a random value it printed and insert it into an array?

I have written a small coin flipping program for Home work Python, it will choose one of two values; Heads or Tails at random and print them, the loop iterates 10 times then stops. As I understand it the only way to count the number of repetitions of some words is to place the words in an array or a split variable string and then run a pre-written cnt. Click Here to see that discussion.
I need to know how you get Python to take the random value it produced and then save it into an array according to the number of iterations of the for loop(in this case x number of iterations).
Here is the variable name and the two options:
coin = ["Heads", "Tails"]
Here is the code for the coin flipper core:
#Flipping core :)
def flipit(random, flip, time, comment, repeat):
time.sleep(1)
print("It begins...")
print("\n")
for x in range(0, 10):
print("Flip number", x + 1)
print(random.choice(comment))
time.sleep(1)
print(random.choice(coin),"\n")
time.sleep(2)
print("\n")
from collections import Counter
counting = []
cnt = Counter(counting)
cnt
print("Type startup(time) to begin flipping coins again")
If you do feel like refining the code please do if you have the time, but all I need is a method that I can put into the overall program that will make it run properly.
Please don't worry about the random comment, that was for a bit of fun.
I have pasted the whole program on PasteBin, Click Here for that.
Thank you for reading this and my gratitude to those who respond or even fix it.
Edit:
Just for reference I am a bit of a newbie to Python, I know some things but not even half of what the people who answer this will know.
Solution:
I have managed to make Python "read" the random value using a per-iteration if statement in my for loop, using if statements I have added 1 to the respective variable according to the random.choice.
Here is the flip core code:
def flipit(random, time, comment, headcount, tailcount, side):
time.sleep(1)
print("It begins...")
print("\n")
for x in range(0, 10):
print("Flip number", x + 1)
side = random.choice(coin) # get the random choice
print(random.choice(comment))
time.sleep(1)
print(side) # print it
if side == "Heads":
headcount += 1
else:
tailcount += 1
time.sleep(2)
print("\n")
print("You got", headcount, "heads and", tailcount, "tails!")
print("Type start() to begin flipping coins again")
resetheadtail()
resetheadtail() is the new function I have added to reset the variables at the end of the program running.
For the full code click Here!
Thanks all who helped, and those who persevered with my newbieness :)
#comment necessary for edit, please ignore
I think what you want to do is:
flip = random.choice(coin) # get the random choice
print(flip) # print it
counting.append(flip) # add it to the list to keep track
Note that you will need to move counting = [] to before your for loop.

Categories

Resources