I'm a bit confused on the logic of doing this.
I want the user to be able to input the number of items they have, and then ask them at the end if they are done. Right now I'm asking after every single item, and I don't like it.
How should I modify this code to get what I want?
Input:
if next1 == "2":
next2=input("How many would you like to add? ")
val = int(next2)
print("")
count = 0
while count < int(next2):
count = count + 1
next3=input(str(count) + ". Input: ")
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
add(next3)
home()
elif check in ("NnNo"):
sort(numbers)
home()
Function:
def add(next2):
numbers.append(next2)
sort(numbers)
home()
Okay, well generally you might do something like this
def confirm_with_user():
user_data = ""
while user_data not in "YyYesNnNo":
user_data = input("Are you sure? (Y/N) ")
return user_data.lower() in "yes":
Then at the point in your code when you want to confirm with your user you just do
if confirm_with_user():
#proceed...
else:
#They don't want to proceed
Related
I am trying to make a shopping list, however every time I delete an item it leaves a big gap and looks very awkward, please can someone help, I am still very new to it all and I have only been learning a month or two so a simple answer would be very much appreciated:
def subtract(user):
x = 0
while x == False:
answer = input("What would you like to subtract?")
if answer in user:
user = user.replace(answer,"")
y = 0
print("your list is:" + user)
add_or_subtract(user)
x == True
break
else:
print ("sorry, I do not recognise this, please try again.")
def add(user):
x = 0
while x == False:
answer = input(str("what would you like to add?".lower()))
if answer in user:
print ("sorry, this is already in the list")
else:
user = user + "\n" + answer
print ("Your list is: " + user)
answer = input("are you finished adding?".lower())
if answer in ("yes", "yea", "ye"):
answer1 = input("do you want to subtract or finish?")
if answer1 in ("subtract"):
subtract(user)
x == True
break
elif answer1 in ("finish"):
print (user)
x == True
break
else:
print("Sorry I do not recognise this")
def add_or_subtract(user):
x = 0
while x == False:
answer = input ("do you want to add or subtract or finish?".lower())
if answer in ("add","addition"):
add(user)
x == True
break
elif answer in ("subtract","takeaway"):
subtract (user)
x == True
break
elif answer in ("complete", "finish"):
print ("your final list is: " + user)
x == True
break
else:
print ("sorry i do not recognise this")
def initial(user):
x = 0
while x == False:
user = input("please type out your first item:".lower())
content = input(str("your first item is "+ user + " are you content with that?".lower()))
if content in "no":
user = ""
continue
elif content in "yes":
add_or_subtract(user)
x == True
break
shopping = ""
initial(shopping)
Also is there a better way of doing this, I feel like there is, could I use a list to record all the items and is there a way I can store the existing list into a database and then re-use that when updating?
The reason why you have a gap is because you are forgetting the \n character (newline character), so when replacing put '\n' before answer:
def subtract(user):
x = 0
while x == False:
answer = input("What would you like to subtract?")
if answer in user:
user = user.replace('\n'+answer,"") # where it is edited
y = 0
print("your list is:" + user)
add_or_subtract(user)
x == True
break
else:
print ("sorry, I do not recognise this, please try again.")
I'm trying to make a basic coin flipping simulator. And ask the user for their name and greet them. Then ask if they want to play the game. But when they enter something other than "Y", it gives this error message: UnboundLocalError: local variable 'time_flip' referenced before assignment how can I fix that and instead it prints a goodbye message. And ask them again if they want to keep playing.
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
There is more code, but I shortened it to the part with errors
here's the full program: https://replit.com/#Blosssoom/coinpy?v=1#main.py
The assignment of time_flip may not complete if there is an error transforming the input to an integer.
To resolve, assign to time_flip before the try block:
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = None
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
else:
break
return time_flip
If people don't type y or Y, the while loop will never run. This cause that every variables in the while loop will never ba created. You want to return time_flip, but because it supposes to be made in the while loop (), it won't be created -> local variable 'time_flip' referenced before assignment (self-explained).
import random
def num_of_input():
userName = input("Please enter your name: ")
print("Hello " + userName + "!" + " This program simulates flipping a coin.")
userWantsToPlay = input("Do you want to play this game? (Y/N): ")
time_flip = 0 #None or anything
while userWantsToPlay in ("Y", "y"):
try:
time_flip = int(input("How many times of flips do you want? "))
except:
print("Please try again.")
continue
return time_flip
So I have an If-elif statement that I want to print some text and loop if the else condition is met. Here is the code:
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for specific user data\n3. kwin - Search a keyword in a specific user\n4. allin - Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
When people mess up and don't put one of the options properly, I want to loop back to the if statement so that when they put in the right one, the loop will end and the rest of the code will continue.
I tried a for loop and wrapped it all as a function but it would end up in an infinite loop of printing the error message. Is there a way to do it with a while loop? Do I need to block it ad a function to repeat it?
Thanks in advance!
In Python, the most idiomatic thing I see for this is while True:
while True:
search_mode = input("How would you like to search?: ")
if "s" in search_mode:
kwsearch = input("What Keyword do you want to use?: ")
elif "u" in search_mode:
username = input("What is the username?: ")
elif "kwin" in search_mode:
kwinuser = input("What is the username?: ")
kwinword = input("What is the keyword?: ")
elif "allin" in search_mode:
allinuser = input("What is the username?: ")
else:
print("Error. Please check spelling and capitalization")
continue
break
You can use a while loop and break statement. You can also reduce the elif statement as I see duplicate code.
Also, you can reduce the user error by converting the search_mode to lowercase.
print("Search Options:\n1. s - Search by keyword in general\n2. u - Search for
specific user data\n3. kwin - Search a keyword in a specific user\n4. allin -
Search for all data by and mentioning a user")
search_mode = input("How would you like to search?: ")
while True:
if "s" in search_mode.lower():
kwsearch = input("What Keyword do you want to use?: ")
break
elif search_mode.lower() in ('u','kwin','allin'):
username = input("What is the username?: ")
if "kwin" in search_mode.lower():
kwinword = input("What is the keyword?: ")
break
else:
print("Error. Please check spelling and capitalization")
search_mode = input("How would you like to search?: ")
The code enters the while loop after accepting value into variable search_mode.
If the value is 's', it asks for the keyword and breaks the loop.
if the value is not 's', then it checks if the value is 'u' or 'kwin' or 'allin'. If it is any of these, then it asks for the username. If the value is kwin, it also asks for keyword. Then it breaks the loop.
If the value is none of the above, it prints the error statement and asks the user the question again. It goes into the loop again with the new value from the user and checks the conditions again. It will exit only when the if or elif statement is true. Hope this helps.
Ok, I am creating a memory game. I have developed where the programme asks the user what word was removed, and have successfully developed the part that moves on if they get it right. However, I am struggling to find how to get it to only fail the user if they get it wrong three times. Here's what I have so far:
def q1():
qone + 1
print("\n"*2)
while qone <= 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
else:
print("Incorrect")
q1()
else:
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
`
My approach is to remove recursion and simply increase the counter of failed tries.
def q1():
qone = 0
print("\n"*2)
while qone < 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
return
else:
print("Incorrect")
qone += 1
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
When you do qone + 1, you need to assign it to something (so perhaps qone += 1)
What is the else outside the while loop linked to?
You seem to have a recursive definition going. Think carefully about the chain of calls that would be made and what your base case should be. Once you know these things, it would be easier for you to write the code. Also, think about whether you need recursion at all: in this case, it doesn't seem like you would.
You should not have the function calling itself, use range for the loop, if the user gets the question correct go to the next question, if they get it wrong print the output:
def q1(removed):
print("\n"*2)
for i in range(3):
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\nCorrect")
return q2()
print("\n\nIncorrect")
input("You're all out of guesses!\nPress enter to return to the menu")
return menu()
If the user has three bad guesses the loop will end and you will hit the "You're all out of guesses!\nPress enter to return to the menu"
I'm a beginner to Python, and am having problems with a function. I am making a program in which I have many parameters for the user to choose from and I need to allow them to confirm or deny their choices. Here is a simplified code section that represents my issue.
my code:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
print 'Congratulations! You have a name!'
break
your_name()
When running this program, it will print the congratulatory string the same amount of times that answer received an input.
my output:
What is your name? Bastion
Are you sure? no
What is your name? Artex
Are you sure? no
What is your name? Falcor
Are you sure? yes
Congratulations! You have a name!
Congratulations! You have a name!
Congratulations! You have a name!
My intention is for the congratulatory message to be printed just one time. How can I edit my function(s) in order to achieve this?
What I've tried:
I have attempted all of these, using the exact same input values I used in my output block above.
Within the section of confirm(function) that says:
if answer == 'no':
return function()
I've tried changing it to:
if answer == 'no':
function()
In the output, this will ask for the answer raw_input 3 times, posting the congratulatory message after each input. If I write the code in this way:
if answer == 'no':
print function()
It will print the congratulatory response 3 times and print None on a separate line below for each time. I am looking for an elegant, clean format so this will not do.
So your problem is you are creating a kind of recursive function without meaning to, you don't need to pass the function to be called again as you are already inside the function. I would suggest the following:
def confirm():
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
if answer == 'no':
return False
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
elif confirm():
print 'Congratulations! You have a name!'
break
your_name()
I think the cleanest way is to change your_name to:
def your_name(toplevel=False):
while True:
name = raw_input("What is your name? ")
if not name:
continue # to reprompt user if they do not enter anything
else:
confirm(your_name)
if toplevel: print 'Congratulations! You have a name!'
break
and the very first call from the top level to your_name(True).
There are other ways, but they require global variables (ecch:-) or even dirtier tricks to find out if the function has been called from the top level; telling it explicitly is way cleaner...
Because of the style recursion you're doing (kudos on that) you end up invoking the your_name() function once each time they fill an answer.
I'd try something more like this:
def confirm():
answer = ''
while answer == '':
answer = raw_input('Are you sure? ')
if answer == 'yes':
return True
elif answer == 'no':
return False
else:
answer = ''
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
if confirm():
print 'Congratulations! You have a name!'
else:
your_name()
your_name()
I think you don't have to use all those "recursive" calls, try this:
def your_name():
flag = True
while flag:
name = raw_input("What is your name? ")
if name:
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
flag = False
break
elif answer == 'no':
break
print 'Congratulations! You have a name!'
your_name()
Using an inner loop for asking if the user is sure. With the use of a flag to determine whenever or not the main "What is your name? " question cycle is over.
You can just put the print 'Congratulations! You have a name!' inside your confirmation() function instead of your_name() so it will be something like this:
def confirm(function):
while True:
answer = raw_input('Are you sure? ')
if answer == 'yes':
print 'Congratulations! You have a name!'
break
elif answer == 'no':
return function() # if the user wants to change their name, recall function
else:
continue # to reprompt user if the answer is not "yes" or "no"
def your_name():
while True:
name = raw_input("What is your name? ")
if not name:
continue
else:
confirm(your_name)
break
your_name()
BTW, I also modify your conditional syntax in the first function so that the program won't go through two if statements.
This solution is relatively succinct. It loops requesting your name while 'name' is an empty string. When requesting confirmation, it resets name to an empty string and thus continues the loop unless the user confirms 'yes'. It then prints the user's name to confirm its assignment.
def your_name():
name = ''
while name == '':
name = raw_input("What is your name? ")
answer = raw_input('Are you sure (yes or no)? ') if name != '' else 'no'
name = '' if answer != 'yes' else name
print 'Congratulations {0}! You have a name!'.format(name)