(Solved) I'm trying to ask the user if they want to continue by typing in either Y/y for yes or N/n for no. If i type Y twice it sends me to my print(Thank you for playing). What did I do wrong here?
def dmg ():
import random
damage = random.randint(1,12)
longSword(damage)
def longSword(damage):
cont = input("Would you like to attack? (Type Y or y for yes and N or n for N)")
while cont == "y" or "Y":
print('Your longsword hit for', damage, "damage")
cont = input("Would you like to attack again?")
if cont == "n" or "N":
print('Thank you for playing')
break
dmg ()
Hi! I'm making a grade converter which is the code attached above. The whole point of my project is to figure out how to make (I think they're called) while loops. With that said, I'm confused on how to make a conditional statement saying "Continue? Y/N" with Y or yes continuing the program from the users input and N or no would "break" the code. My confusion is WHERE I would put the *while TRUE loop. Does it go BEFORE my main code and THEN I put the yes no question. Furthermore, would my "Continue y/n" question be coded as a boolean? If someone can show me how this should look when integrated with the CURRENT code, I would be so thankful, bc Khan Academy is confusing me...
(PS This isn't for a grade or class assignment, but to learn how this loop stuff works)
print("Letter Grade Converter")
grade = int(input("Enter your grade "))
if grade >= 88:
print("Your letter grade is an A")
elif grade >= 80:
print("Your letter grade is a B")
elif grade >= 67:
print("Your grade is a C")
elif grade >= 60:
print("Your grade is a D")
elif grade < 60:
print ("Your grade is an F")
Videos
So I have a program that calculates compound interest, and now I need to add a question at the end of my program that asks the user if they would like to run the program again, if they answer with Y or y the program will restart to the beginning, if they answer “N” or “n” the program is over. And if they answer with anything other than y or n it should repeat the question until the user finally enters y or n
What I have so far:
I have my entire program in a while loop and was able to get it to reset while Var == Y or y. But I can’t get it to repeat the question if the user answers with let’s say “q” or “618” or “L”. Does anyone know how to do something like this, please let me know… thank you
This is a simple one:
while True:
a = input("Enter yes/no to continue")
if a=="yes":
gameplay()
continue
elif a=="no":
break
else:
print("Enter either yes/no")
Where gameplay function contains the code to be executed
I would do it the following way:
while True:
# your code
cont = raw_input("Another one? yes/no > ")
while cont.lower() not in ("yes","no"):
cont = raw_input("Another one? yes/no > ")
if cont == "no":
break
If you use Python3 change raw_input to input.
Hello anyone, I'm trying to write a program that asks the user if he/she wants to play a game. The user has the option of only entering 'yes' or 'no' and if it's anything other than that, the program should enter a while loop that asks the user to "please enter a valid answer of either 'yes' or 'no'. So far I have this:
print("would you like to play a game?")
answer = raw_input()
if answer == "yes":
print("Let's play!!")
elif answer == "no":
print("Ok, another day...")
else:
answer = False
But where to put the while loop??
Update: Ok guys, thanks for your help. I got!
print("would you like to play a game?")
answer = None
while answer != 'yes' or answer != 'no':
answer = raw_input("Please enter yes or no: ")
if answer == "yes":
print("Let's play!!")
else:
print("Ok, another day...")
I was also trying write a program that has a definition. So far I have this
def game(answer):
if answer == 'yes':
print("Ok, let's begin!")
elif answer == 'no':
print("Ok, another time then...")
print("Would you like to play a game?")
answer = input()
while True:
if answer != 'yes' or answer != no:
answer = input("Please enter a valid response ")
continue
else:
break
game(answer)
but I don't know what I'm doing wrong in block 5.
(I'm going to try not to give you the answer, but to push you towards it)
You want the while loop to run over and over again until the user inputs neither yes or no, right? So you'd want to break out of the loop if the answer is yes, break out of the loop if the answer is no, else try again, so you need to set up the condition for exit, for entry, and the logic in between.
As for where you'd put the while loop, you want to put it on the global line, then all your logic indented inside.
Remember you can use 'or' when evaluating.
Not sure why I’ve never heard about this, but apparently you can use else with a while loop. I’ve always used a separate flag variable
This will execute when the while condition is false but not if you break out of the loop early.
For example:
Using flag
nums = [1, 3, 5, 7, 9]
target = 4
found = False
i = 0
while i < len(nums):
if nums[i] == target:
found = True
print("Found:", target)
break
i += 1
if not found:
print("Not found")Using else
nums = [1, 3, 5, 7, 9]
target = 4
i = 0
while i < len(nums):
if nums[i] == target:
print("Found:", target)
break
i += 1
else:
print("Not found")Hi!
Sorry if this question has been answered somewhere, I just couldn't find a thread that would help me solve my problem. This little program is supposed to ask a question and if it gets yes/no answer, then print something. If it doesn't get yes or no, it should ask the question again until the user's input is yes/no. However I get stuck in infinite loop then I get asked "Wrong imput! Answer yes or no please: " - this question repeats even if I answer yes/no.
Thanks for any help!
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello " + name + "! You are " + age + " years old, right? ")
answer = input ("Answer yes or no please: ")
while answer != "yes" or answer != "no":
answer = input ("Wrong imput! Answer yes or no please: ")
if answer == "yes":
print("Haha, I knew it!")
elif answer == "no":
print("Liar!")
while answer != "yes" or answer != "no":
or isn't the right thing here. The only way for this condition to not be true is if answer is both "yes" and "no" at the same time, which isn't possible. If the answer is "yes", then answer != "no" and you'll prompt again. If the answer is "no", the answer != "yes", and you'll prompt again. You only want to prompt if the answer isn't "yes" and the answer isn't "no".
Change the ‘or’ to ‘and’
I personally had some really bad experiences with memory leaks, forgotten stop condition, infinite loops… So I only use ‘for’ loops.
Then I was wondering: do some of you actually use ‘while’ loops ? if so, what are the reasons ?
EDIT : the main goal of the post is to LEARN the main while loop use cases. I know they are used in the industry, please just point out the real-life examples you might have encountered instead of making fun of the naive question.
I’ve written a lot of python code over the last few months, but I can’t think of a single time I’ve ever used a while loop. I mean, I use for loops pretty often, but not while loops.
Is this just down to personal preference, and I’m just using what I’m comfortable with? Or can you guys think of some situations where a while loop would be the easiest way to do things, but it’s possible to do it with a for loop? Maybe I’m using for loops in situations that I should be using while loops.
EDIT: Thanks for the suggestions. I found a few places in my code where a while loop makes sense.
First, I check if a folder has any files in it, and while it does, I delete the first one in the list:
useless_files = os.listdir("MGF_HR_Data") # I think these are files it creates when downloading the MGF data but they are extra and don't do anything
while len(useless_files)>0:
os.remove(f"MGF_HR_Data/{useless_files[0]}")
useless_files = os.listdir("MGF_HR_Data")
print("Deleting useless file from MGF_HR_Data") I also used a while loop to check if the data has been downloaded, and if it hasn't prompt the user to download it and then press enter to check again. This way, the code doesn't break if the user forgot to download the file first:
# Check if you downloaded the file in Matlab already. If not, ask the user to download it and try again.
while os.path.exists(file1)==False:
print(f"{file1} not found. Please open Matlab and run the following code to download the MGF data:" )
print(f"download({wstime.year}, {wstime.month}, {wstime.day})")
input("Press enter to try again after downloading the MGF data. \n") (Okay, I know this isn't the most efficient way to do this. There must be a way to use python to open matlab and run a matlab command, rather than asking the user to do it themselves. However, I don't know how to do that, so this works for now.)
While loops is kinda frustrating I'm 20 days into python and I'm stuck on loops since last 4 days
Edit: Got the answer I was looking for. People want these keywords because actually having these keywords haven't created as many complications but solve many as they increase the readability.
Also, for anyone saying that all the provided examples (1&3) do the same thing. That's what my point was.
It seems to me that both loops can perform like the other one in any language and there's not much restriction
Yes some languages have special syntax for 'for' loops such as Rust, JS, Python have 'for-in'.
But I wonder, what if a language just has 'loop'
Examples below:
loop x in (range()/a..b/a..=b) {
}
loop x < y {
}
loop x in iterable {
}I don't know if people would prefer this more but it seems like the simpler thing to do.
I used to often think whether I should use while, for or do-while and they actually don't have that much performance difference so it just seems they create confusions and don't help beginners.
Thoughts?
I want to ask, whats the difference between looping using the while and the for function? I know both of these functions loops through stuff but what exactly is the difference between them? I have trouble understanding so I decide to ask this question on here
I'm using solelearn for learning python, and I just cannot figure out why my while loop isn't working.
I am aware that it's probably an oversight on my behalf.
Any help / explanation would be much appreciated.
For these lines of code I have to make it count down to 0.
(# take the number as input) number = int(input())
(# use a while loop for the countdown) while number > 0: print(number) number = number -1
You are first calling yes_or_no, which outputs a value but you throw it away and are calling the function again instead of testing on the output of the first call.
Try storing the output in a variable.
# Store the output in a variable
answer = yes_or_no()
# Conditional on the stored value
if answer == 1:
print("You said yeah!")
else:
print("You said nah!")
Side notes
It is considered bad practice to use capitalized names for variables, those should be reserved for classes.
Also, a user-prompt loop is better implemented with a while-loop to avoid adding a frame to your call-stack every time the user enters a wrong input. This is unless you use an interpreter which implements tail-call optimization, which cPython does not.
Here is what an improved version of your function could look like.
def yes_or_no():
while True:
answer = input("Yes or No?").lower()
if answer == "yes":
return 1
elif answer == "no":
return 0
You can use break and continue statements like this:
def yes_or_no():
YesNo = input("Yes or No?")
YesNo = YesNo.lower()
if(YesNo == "yes"):
return 1
elif(YesNo == "no"):
return 0
else:
return -1
while(True):
inp = yes_or_no()
if(inp == -1):
continue
elif(inp == 1):
print("You said yeah!")
elif(inp == 0):
print("You said nah!")
break
Is for and while statement completely interchangeable in Python? Are there scenarios where one statement cannot be converted to another?
Hey guys, brand new to programming. Literally. Only about a week in. Used this forum to get me started, so thanks for all the resources so far.
I'm using the Jump Start Learn Programming book and it uses python as its into language. Just got to the section regarding while loops. I can't even get the first example to properly run :/ I don't know what the problem is, as far as I can tell my code is identical to the books. I had this problem last week when using a different training material. Seems to always happen when I am trying to create a while loop for text that includes a n input. Here is the code.....
answer = "no"
while answer == "no":
answer = input("Are we there yet? ")
print ("We're here!") Not sure if it matters but I'm writing the code in IDLE. Here is the error message it spits out: Traceback (most recent call last): File "C:/Python27/vb", line 3, in <module> answer = input("Are we there yet? ") File "<string>", line 1, in <module> NameError: name 'no' is not defined
BTW is there any formatting etiquette for pasting lines of code? Sorry if I'm breaking rediquette, first time poster in this subreddit. Thanks in advance for the help guys!!
edit: formatting
I am teaching a group Python and several students are struggling to earn when to use a for loop and when to use a while loop. How do you explain it in a way that will help them understand?
I'm still learning how to code in python and I decided to experiment on a number of conditional and loop statements. The program should be simple: Request the user to input a positive integer value and correct their behavior if a string is introduced. If the user types '0' it asks the user if he wants to exit the program and is supposed to exit upon confirming the user's request or is supposed to repeat the input request until the user requests and confirms his request to leave.
Problem is even though I reset the 'i' variable to initial conditions the while loop does not trigger again as expected. I need to find a way to trigger this loop indefinitely upon declining the request to leave but instead the while loop ends after the else is triggered and the program terminates. Where did I go wrong?
Note: The code is properly indented. Reddit just displayed it like that.
#This is the following code:
i = 1
while i != "0":
try:
i = input('Enter a positive integer: ')
a = int(i)
except:
a = -1
if a > 0:
print(a)
elif a < 0:
print("Not a positive integer, don't ruin my program!")
else:
try:
a = input("Do you want to exit?\n")
if a == "yes" or a == "y":
print("Ok, shutting down now, goodbye!")
exit()
elif a == "no" or a == "n":
print("Well I'm shutting down anyway. Bye!")
i = 1
else:
print("Hey, buddy, you're supposed type 'y' or 'n'.")
exit()
except:
print("Hey, buddy, you're supposed to type 'y' or 'n'")
exit()My initial assumption was that if you typed 'no' or 'n' the while loop would trigger again. Now I am ata loss as to how to trigger that same while loop.
Another error: I added a try/except condition in case the user types something that might cause a traceback error but instead it prints two error messages printed out on the final else and except if the user types n or no and still prints one error message from the except condition. From my understanding the except is supposed to trigger in case we get a Python error from the try statement, right?
EDIT: SOLVED, I'M SO HAPPY. MY EXPERIMENT WAS A SUCCESS:
i = 0
ii = 0
def positive_int(): #Requests a positive integer
global i #references global i inside function
global ii #references global ii inside function
while i != "0":
try: #Checks for any str input instead of numbers
i = input('Enter a positive integer: ')
a = int(i)
except:
a = -1 #Triggers built-in error message by converting str input into a negative integer instead of crashing the program, thus continuing operation.
if a > 0:
print(a) #Shows positive input value
elif a < 0:
print("Not a positive integer, don't ruin my program!") #Built-in error message
else:
a = input("Do you want to exit (y for yes, n for no)?\n") #Asks for confirmation to exit program
if a == "yes" or a == "y":
ii = 1 #Cancels the loop and exits the program with a goodbye message
elif a == "no" or a == "n":
i = 0 #Resets the loop, resetting user input to 0
else:
print("Hey, buddy, you're supposed type 'y' or 'n'.") #Built-in error message, scolds user for inputting nonsense.
a = 0 #Asks for confirmation again.
while ii == 0:
positive_int() #loops user input request
else:
print("Shutting down now, goodbye!") #terminates loop and exits program upon confirmation of user input
exit()