Loop Input until Parameter is met or User Input - python

I want my program to either wait 10 seconds before moving on, or break the loop by user input
try:
while True:
afkseconds = 0
time.sleep(1)
afkseconds +=1
if afkseconds == 10:
Timer()
except KeyboardInterrupt:
pass
newTaskIO = input('Y/N: ')
newTaskIO = newTaskIO.lower()
if newTaskIO == 'y':
taskName = input('Enter the name of the task: ')
taskDescription = input('Enter a brief description, or press enter to continue: ')
The program enters the while Loop, adding a second to the "afksecond" variable. The idea is once the afksecond variable = 10, the loop breaks and performs the specified function.
Either that or the user enters "y" or "n" to break the loop and continue with the next phase of the program. I cannot figure out the logic to get this to work. Please advicse

Related

while loop, asking user if he wants to repeat the program problem

So I have this while loop which asks user if he/she wants to repeat the program. All works good but I was trying it out and found out that after user repeats the program and when asked second time if he/she wants to repeat, I choose no. But the program still repeats although it prints that program is closing, how can I fix this?
edit: I've fixed it with changing break with return and adding return after main()
def main():
endFlag = False
while endFlag == False:
# your code here
print_intro()
mode, message=get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
while True:
if ui == "Y":
print(" ")
main()
elif ui == 'N':
endFlag = True
print("Program is closing...")
break
else:
print("wrong input, try again")
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
This is because main() function is being called recursively & endFlag is a local variable.
So when you first put 'y' , then another main() is recursively called from the first main() function.
After you put 'n' which ends this second main() and return to the first main which still in a loop with endFlag (local variable) with value as false.
So, need to change,
Either
endFlag variable as global ( i.e. defined outside main function )
Or,
some program exit function in place of break
The thing is that you're doing recursion over here, i.e. you're calling method main() inside main() and trying to break out of it the way you've done is not gonna work (well, you're know it :) )
Second - you don't need a forever loop inside a first loop, you can do it with one simple loop and break.
Here it is:
def print_intro():
intro = "Welcome to Wolmorse\nThis program encodes and decodes Morse code."
print(intro)
def get_input():
return 'bla', 'bla-bla-bla'
def main():
while True:
# your code here
print_intro()
mode, message = get_input()
ui = str.upper(input("Would you like to repeat the program again? Y/N: "))
if ui == "Y":
print(" ")
elif ui == 'N':
print("Program is closing...")
break
else:
print("wrong input, try again\n")
main()
this is what you should do:
(BTW this is a piece of example code)
while True
name = input('Enter name:')
print ('Hi '+ name)
exit = input('Do you want to exit?(Y/N)')
if exit == 'N' or 'n':
break
(Im not sure if i put the indents correctly )
You can apply this concept into your code.

User prompt to Continue or Clear a time duration calculator

I am very inexperienced with any programming language. I decided for my first for-fun/leaning project to be creating a calculator to add different durations of time (ex. add the length of several songs to find how long an album is).
So far the user input method is pretty basic, and I'll work to fix that once the basics work, so bear with me on that. The calculator is currently capable of adding two times together and printing the correct answer.
My main problem is creating a functional Continue/Clear user prompt. I have a loop asking if the user wants to continue, clear, or exit. User input works correctly, but I don't know how to actually "continue or clear".
My idea: Upon hitting continue, the previous total will become firstNumber, and the user will only be prompted for the second number (nextNumber) and will be given a new sum and receive the same continue/clear/exit prompt. If the user hits clear, it will start at the very beginning and the user will be prompted for a new firstNumber.
Any help is greatly appreciated.
Below is the code:
import datetime
# holds first entry
print("Enter the first number")
seconds_1 = int(input("Seconds: "))
minutes_1 = int(input("Minutes: "))
hours_1 = int(input("Hours: "))
# holds second entry
print("Enter another number")
seconds_2 = int(input("Seconds: "))
minutes_2 = int(input("Minutes: "))
hours_2 = int(input("Hours: "))
# calculation
duration_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)
duration_2 = datetime.timedelta(hours=hours_2, minutes=minutes_2, seconds=seconds_2)
total = duration_1 + duration_2
print(total)
# continue, clear, or exit
contClear = input("Continue: Y | Clear: N | Exit: X: ")
cont = False
while cont == False:
if contClear.upper() == "Y" or contClear.upper() == "YES":
print("Next")
cont = True
elif contClear.upper() == "N" or contClear.upper() == "NO":
print("Cleared")
cont = True
elif contClear.upper() =="X" or contClear.upper() == "EXIT":
print("Exiting")
cont = True
else:
print("Invalid Entry")
contClear = input("Continue: Y | Clear: N | Exit: X: ")
print("DONE")

How do I run one def function inside of a different def function in python?

I'm trying to run a timer inside of a function of my code. I need to start the timer slightly before the user starts typing, then stop the timer when the user has entered the alphabet correctly.
Here is my code:
import time
timec = 0
timer = False
print("Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed")
timer = True
attempt = input("The timer has started!\nType here: ")
while timer == True:
time.sleep(1)
timec = timec +1
if attempt == "abcdefghijklmnopqrstuvwxyz":
timer = False
print("you completed the alphabet correctly in", timec,"seconds!")
else:
print("There was a mistake! \nTry again: ")
The issue is that it will not let me enter the alphabet. In previous attempts of this code (Which I do not have) i have been able to enter the alphabet, but the timer would not work. Any help is appreciated
import time
start = time.time()
attempt = input("Start typing now: ")
finish = time.time()
if attempt == "abcdefghijklmnopqrstuvwxyz":
print "Well done, that took you %s seconds.", round(finish-start, 4)
else:
print "Sorry, there where errors."
Think carefuly about that you are dong
You ask for a user-entered string
While timer equals True, you sleep for one second and increase the count. In this loop, you do not change the timer.
Obviously, once user stopped entering the alphabet and pressed enter, you start an infinite loop. Thus, nothing seems to happen.
As other answers suggested, the best solution would be to save the time right before prompting user to enter the alphabet and compare it to the time after he finished.
you could do something like:
import datetime
alphabet = 'abcdefghijklmnopqrstuvwxyz'
print('Type the alphabet as fast as possible.\nYou MUST be accurate!\nYou will be timed"')
init_time = datetime.datetime.now()
success_time = None
while True:
user_input = input('The timer has started!\nType here: ')
if user_input == alphabet:
success_time = datetime.datetime.now() - init_time
break
else:
continue
print('you did it in %s' % success_time)

Continuous results from a single function call

I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...

python -- Crash when trying to deal with unexpected input

So, I'm just fooling around in python, and I have a little error. The script is supposed to ask for either a 1,2 or 3. My issue is that when the user puts in something other than 1,2 or 3, I get a crash. Like, if the user puts in 4, or ROTFLOLMFAO, it crashes.
EDIT: okay, switched it to int(input()). Still having issues
Here is the code
#IMPORTS
import time
#VARIABLES
current = 1
running = True
string = ""
next = 0
#FUNCTIONS
#MAIN GAME
print("THIS IS A GAME BY LIAM WALTERS. THE NAME OF THIS GAME IS BROTHER")
#while running == True:
if current == 1:
next = 0
time.sleep(0.5)
print("You wake up.")
time.sleep(0.5)
print("")
print("1) Go back to sleep")
print("2) Get out of bed")
print("3) Smash alarm clock")
while next == 0:
next = int(input())
if next == 1:
current = 2
elif next == 2:
current = 3
elif next == 3:
current = 4
else:
print("invalid input")
next = 0
Use raw_input() not input() the latter eval's the input as code.
Also maybe just build a ask function
def ask(question, choices):
print(question)
for k, v in choices.items():
print(str(k)+') '+str(v))
a = None
while a not in choices:
a = raw_input("Choose: ")
return a
untested though
since the input() gives you string value and next is an integer it may be the case that crash happened for you because of that conflict. Try next=int(input()) , i hope it will work for you :)

Categories

Resources