While loop if condition is not met - python

I want to break out of the loop if y or n is set. In my head this is the way to do it, but it seems to get stuck in the while loop even when 'str1' is set to both n and y.
I have also tried to do: while str1 != "y" or str1 != "n": without luck.
str1 = ""
while not str1 == "y" or not str1 == "n":
str1 = input('setting [y/n] => ')
str1 = str1.lower()

Your condition while str1 != "y" or str1 != "n" is always True, if you enter n it'll be different of y and vice-versa.
You want to stop if both condition aren't met
while str1 != "y" and str1 != "n"
Or easier
while str1 not in "yn":

Related

Having trouble with a simple while loop

I've been trying to create a simple program in python in which the user is asked for their postcode until it contains both letters and numbers.
This is the code I have so far:
num = False
letter = False
while num == False and letter == False:
postcode = input("what is your postcode? ")
for i in postcode:
if i.isalpha:
letter = True
if i.isdigit:
num = True
When I run the program it doesn't ask me for my postcode even when it is wrong. How can I fix this?
Took me a while to see all the problems.
num = False
letter = False
while not(num and letter):
num = False
letter = False
user_input = input("What is your postcode? ")
x = user_input[0]
y = user_input[1]
print(x.isalpha())
print(y.isdigit())
if x.isalpha():
letter = True
if y.isdigit():
num = True
print(num, letter)
print("You are in")
You don't reset the values of num and letter each time.
In your original you are changing a string you are iterating over.
And as someone else pointed out, you need to call functions with ().
A good attempt though. There are many ways this could be done. Mine is just one "fix".
You have to call the methods!
if i.isalpha(): # note the ()
# ...
if i.isdigit():
# ...
i.isalpha is just the method object (which is always truthy). Only calling it will produce the real bool you are looking for.
You could actually make this more concise, all the while not manually calling the methods and not having to maintain/reset all those variables:
while True:
postcode = input("what is your postcode? ")
if any(map(str.isalpha, postcode)) and any(map(str.isdigit, postcode)):
break

Python, How do I use a string in a while loop and then an if statement?

I cannot figure out why this won't work, I have gone as far as to apply integer variables, I would prefer to keep it purely to strings. I'm new, what am I doing wrong?
x = int(2)
y = int(1)
while userinput != (1,2):
userinput = input("Do you wish to continue, to start from scratch?")
if input == 1:
print("y")
if input == 2:
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
I presume you want to check directly on the "y" and "n" characters, note that, among the other things, in your code you are checking the wrong input, you should check the variable userinput that you assign in the loop with the user input.
Here is a working example, note that i convert to lowercase in order to accept both "y\n" and "Y\N" with a single if statement.
userinput = ""
while (userinput !="y" and userinput !="n"):
userinput = input("Do you wish to continue, to start from scratch?").lower()
if userinput == "y":
print("y")
elif userinput == "n":
print ("n")
else:
print("Try y or n, they mean yes or no respectively.")
EDIT: if statement fixed as suggested by #Kumar

While Loops (And, Not, Or)

I need help with this simple question. I'm starting to learn more about while loops and I'm not sure what I'm doing wrong.
There are 3 criteria:
1) The string must start with "b" or "B"
2) The string must have 6 characters
3) The last letter of the string must be "z" or "Z"
It will print "Error" and prompt the user again if any of the conditions are not met. It will print "Nice!" if it meets the criteria.
This is my code:
string = input("Enter a string: ")
length = len(string)
while (not(string[0] == "b" or string[0] == "B" or string[length-1] == "z" or string[length-1] == "Z" and length < 6)):
print("Error!")
string = input("Enter a string: ")
print("Nice! ")
If I enter "1000", the output will be "Error!"
If I enter "bz", the output will be "Nice!". It should print the error message as the length is less than 6.
You can do something as simple as using str.startswith and str.endswith to test the boundary characters:
s = input("Enter a string: ")
while True:
if len(s) == 6 and s.startswith(('b', 'B')) and s.endswith(('z', 'Z')):
print('Nice')
break
else:
print('Error, try again!')
s = input("Enter a string: ")
The length is checked first so that the conditionals short-circuit once the len expression (an O( 1 ) operation) fails.
One of the most important python idioms is to keep your code easily readable. This helps yourself to spot mistakes very fast and other people can understand your code without a lot of effort. Therefore I suggest to code your problem as follows:
string = input("Enter a string: ")
def conditions_satisfied(string):
cond1 = string[0] == "b" or string[0] == "B"
cond2 = string[-1] == "z" or string[-1] == "Z"
cond3 = len(string) == 6
return cond1 and cond2 and cond3
while (not conditions_satisfied(string)):
print("Error!")
string = input("Enter a string: ")
print("Nice! ")
prints:
Enter a string: 1000
Error!
Enter a string: bz
Error!
Enter a string: b1234z
Nice!
As already mentioned:
you don't update lengh inside the while loop
you say the string length has to equal 6 but you write the condition "it has to be smaller than 6": <6
Another way to write the condition (looks more readable to me):
string = input("Enter a string:")
while string[0] not in ["b", "B"] or string[-1] not in ["z", "Z"] or len(string) != 6:
print("Error!")
string = input("Enter a string:")
print("Nice!")
import re
string = input("Enter a string: ")
length = len(string)
if length == 8:
if (re.match(r'(b|B).*.(z|Z)$', string)):
print("Nice! ")
else:
print("Error!")
change this
string = input("Enter a string: ")
length = len(string)
while (not(string[0] == "b" or string[0] == "B" or string[length-1] == "z"
or string[length-1] == "Z" and length < 6)):
print("Error!")
string = input("Enter a string: ")
print("Nice! ")
to
string = input("Enter a string: ")
length = len(string)
while (not( (string[0] == "b" or string[0] == "B") and (string[length-1]
== "z" or string[length-1] == "Z") and (length == 6))):
print("Error!")
string = input("Enter a string: ")
print("Nice! ")

While statment loop in python

I am learning python, and I am stuck in an infinite while loop in the following code.
A = input("Hello what is your name? ")
D = input("What is today's date? ")
B = input("Did you have a good day [y/N]")
while B != "y" or B != "Y" or B != "N" or B != "n":
B = input("Did you have a good day [y/N]")
else:
if B == "Y" or B == "y":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a good day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
elif B == "N" or "n":
print(A + ", ")
C = input("Tell me about your day ")
with open("Start.txt", "a") as infile:
infile.write("\n")
infile.write(A)
infile.write(" ran Start.py and said he had a bad day on ")
infile.write(D)
infile.write(".")
infile.write("\n He reports today:\n ")
infile.write(C)
The problem happens when B is compared to see if it is equal to Y, y, N, or n
but it still no matter what input I give it for B sticks me into the while statement and keeps me there.
The problem is here:
while B != "y" or B != "Y" or B != "N" or B != "n":
B is always not equal to one of those. If it's "y" it is not equal to the other three, and so on. And since you are using or to combine these conditions, the loop continues if any one is true, which, as we've seen, is always the case.
Rewrite using and:
while B != "y" and B != "Y" and B != "N" and B != "n":
Or apply DeMorgan's law (factor the not out of the expression and swap and/or):
while not (B == "y" or B == "Y" or B == "N" or B == "n"):
Or best of all, write it the Python way:
while B.lower() not in "yn":
(This also accepts an empty answer, which according to your prompt is equivalent to "N". To handle this, just convert your elif to a plain else, without a condition.)
Lets use a simplified version of your while loop.
while B != "Y" or B != "y":
# ...
There is no way that this will ever evaluate to False.
If B was set to Y then B != "Y" would be False, but B != "y" would be True.
I think, in this case, it might be cleaner to do something like
while B not in ["y", "Y", "n", "N"]:
# ...
Which will then repeat until the input is one of the characters in your list.
EDIT: Some other answers have suggested using while B not in "yYnN" or equivalents. This works here because all of your expected responses are one character. If you decide later to accept "yes" as a response, then you will have to use a list like I have shown above.
The issue is that you are doing while B != "y" or B != "Y" or B != "N" or B != "n":
With or it returns true if either of its options are true. So if B="N"
b!="N" or b!=n" is true because b still isn't "n"
You can solve this by replacing all the ors with ands to get this
while B != "y" and B != "Y" and B != "N" and B != "n":
This line
elif B == "N" or "n":
Should be
elif B == "N" or B == "n":
You should use condition, simply "n" (non empty string) means true
This is the simplest solution!
while B not in "YNyn":

Changing loop conditions to repurpose a number guessing game

I am a new programmer with experience with Visual Basic for Applications and have recently changed to python.
I'm working on a number guessing game and so far progress has been great. The user enters 4 digits into the program. The program also generates a 4 digit number and the program returns Ys or Ns to show whether any digits are correct or not. EG 1357 as a user guess and 1358 as the programs number shows YYYN as output.
I'm trying to rework the program to make it simpler for users by showing H or L to suggest that they need to guess higher or lower IF the digit guessed is incorrect. If it's correct, then a Y should be shown as per normal. I am aware that it's a condition in the loop I need to change or another loop I need to add but I am struggling to see where to add this and how to write it. Does anybody have a solution for this?
Here is part of my code for the section of the program which returns the result for the guesses.
lives = 10
while lives > 0:
number = input("Enter your guess: ")
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else 'N'
if letter == 'Y' * len(numToGuess):
print("Good job!")
break
print(letter)
lives -= 1
else:
print("Game over! You used up all of your tries.")
Does anybody have a solution for this?
I prefer to use lists for this. Meaning, I'd convert both the correct answer and the user guess into separate digits saves in two lists and then compare them.
Let's say the correct answer is '1234':
lives = 10
correct_answer = 1234
correct_answer = [int(char) for char in str(correct_answer)]
while lives > 0:
letter = ''
number = input("Enter your guess: ")
number = [int(char) for char in str(number)]
if number == correct_answer:
print("Correct!")
break
for i in range(len(correct_answer)):
if correct_answer[i] == number[i]:
letter += 'Y'
elif correct_answer[i] > number[i]:
letter += 'H'
else:
letter += 'L'
print("Your guess is wrong: ", letter)
lives -= 1
print("Game over!")
Now for example:
Enter your guess: 1111
Your guess is wrong: YHHH
Enter your guess: 1235
Your guess is wrong: YYYL
Enter your guess: 1234
Correct!
Game over!
>>>
You can use zip function for compare the letters :
>>> a='1357'
>>> b='1358'
>>> l=[]
>>> for i,j in zip(a,b):
... if i==j :l.append('Y')
... else :l.append('N')
...
>>> ''.join(l)
'YYYN'
And for check the answer you can use a generator expression within all :
>>> all(i=='Y' for i in l)
False
You don't need to change your loop condition. Just change the logic of your if expression.
letter = ''
for i in range(len(numToGuess)):
if int(number[i]) == numToGuess[i]:
letter += 'Y'
elif int(number[i]) > numToGuess[i]:
letter += 'H'
else:
letter += 'L'
Or, in one line:
letter = ''
for i in range(len(numToGuess)):
letter += 'Y' if int(number[i]) == numToGuess[i] else ('H' if int(number[i]) > numToGuess[i] else 'L')

Categories

Resources