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! ")
Related
Link to the flowchart i made
I want to make a program that accepts a string of 1’s and 0’s. It should output ‘ is valid’ if and only if the string starts with 1, the second with 0, and the last be 1. The string can be of any length. If the string does not follow the conditions and is composed of letters or special characters, the program should state that is invalid. This is my coded version of this and it prints invalid when i type 101 and when i typed 10 it is valid.
x = str(input('Enter numbers: '))
if x == '10':
print('string is valid')
else:
print('Invalid Input')
This is checking that first characters are 1 and 0, checking last one is 1 and the string does contain only 0 or 1 characters.
x = str(input('Enter numbers: '))
if x.startswith('10') and x.endswith('1') and all(letter in '01' for letter in x):
print('string is valid')
else:
print('Invalid Input')
You can use regex and suit the pattern to your exact needs:
import re
pattern = "10[01]*1$"
s = "101101"
match = re.match(pattern=pattern, string=s)
if match:
print("valid")
else:
print("not valid")
Here:
x = str(input('Enter numbers: '))
if x.startswith("10") and x.endswith("1"):
print('string is valid')
else:
print('Invalid Input')
or
x = str(input('Enter numbers: '))
if x[0] == "1" and x[1] == "0" and x[-1] == "1":
print('string is valid')
else:
print('Invalid Input')
Problem
I'm trying to write a program where (1) the user inputs lines until he enters a line that has "A" in position 0 of the input, (2) then the program will print the line that had greater length.
The desired output is:
Enter a string: Faces all glow.
Enter a string: Time for summer fun
Enter a string: As the happy faces show.
Longest string: "As the happy faces show."
Attempt
This is what I tried at first but it doesn't work at all.
a, b, c, d, e, f, g = input("Enter seven values: ").split()
print("Enter a String: ", a)
print("Enter a String: ", b)
print("Enter a String: ", c)
print("Enter a String: ", d)
print("Enter a String: ", e)
print("Enter a String: ", f)
print("Enter a String: ", g)
print()
I must say what you are expecting and your sample code are not relevant at all. However, I think you are asking something like the following code can do
longestString = ""
a = " "
while a[0].capitalize() != 'A':
a = input("Enter a String: ")
if not a:
a = " "
if len(a) > len(longestString):
longestString = a
print(longestString)
Use a while loop and a flag (boolean variable) to achieve this:
#initialize
stringWithA = False #a flag, will be set to True if user enters string starting with A
currentMaxLength = 0
currentLongestStr = ''
while stringWithA == False: #haven't seen a string starting with A so far
x = input("Enter a string: ")
if x[0] == 'A':
stringWithA = True
if len(x) > currentMaxLength:
currentMaxLength = len(x)
currentLongestStr = x
print('"' + currentLongestStr + '"')
Your wording seems quite confusing and other comments seem to agree with me, but from what I understand the following code should give you the desired output:
inp = " "
longestString = ""
while inp[0] != 'A':
inp = input("Enter a String: ")
if len(inp) > len(longestString):
longestString = inp
# To make sure empty input does not break code
if len(inp) == 0:
inp+=" "
continue
print("Longest string: ", longestString)
A similar solution but with consideration to lines with the same length that it is the longest length.
inp = " "
longest = list()
length = 0
while inp[0] != 'A':
inp = input("Enter a String: ")
if len(inp) > length:
longest.clear()
length = len(inp)
# append will happen in the next if
if len(inp) == length:
longest.append(inp)
inp += " " # to avoid empty input
print("Longest :")
for x in longest:
print(x)
Notes
Most of the answers stop getting input after 'A' or 'a' when the question says only 'A'.
I have created a hangman type game and it all works apart from if the user enters a capital letter it does not register it. The game should be case insensitive. This is the code I have tried for that part of the game.
def game():
total = len(''.join(set(myword)))
wrong_guess = 0
correct_letters = 0
while wrong_guess <= 7:
print_output()
letter = input("Guess:")
if len(letter) >= 1:
if letter.isalpha():
if letter.lower() in myword:
correct_letters += 1
for i,x in enumerate(myword):
if x is letter.lower():
output[i] = letter
else:
wrong_guess += 1
else:
print("Invalid input, please enter a guess")
else:
print("Invalid input, please enter a guess")
python has a built in function called string.lower()
do this
letter = input("Guess: ").lower()
The following code is not the proper way to compare strings or characters:
if x is letter.lower():
The is operator compares whether two instances are the same or not, it does not compare equality. You want to use the equality operator, ==:
if x == letter.lower():
I'm an absolute beginner at python and I need to write a code which can differentiate between 2 lists. Overall code works yet, consistently the last element of the list is not being taken into account and lists such as "AT, AC" are being considered the same. I would love some help. Thanks !
Seq1 = input( " Enter first sequence ")
Seq2 = input(" Enter second sequence ")
seq1 = list(Seq1)
seq2 = list(Seq2)
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print(" The sequences differ by their length ")
exit()
else:
for i in range(len(seq1)) :
if seq1[i] == seq2[i]:
print(" The sequences are the same ")
exit()
else :
print(" Sequences differ by a/mulitple nucleotide ")
exit()
compare_seq(seq1,seq2)
You exit the loop too early which is a common mistake:
for i in range(len(seq1)) :
if seq1[i] == seq2[i]:
print(" The sequences might be the same ") # note "might"
# exit() # <- leave this one out
else:
print(" Sequences differ by a/mulitple nucleotide ")
exit()
print(" The sequences are the same ") # now you know
There is a built-in shortcut for this pattern (all) which you can combine with zip to make this more concise:
# ...
else:
if all(x == y for x, y in zip(seq1, seq2)):
print(" The sequences are the same ")
else:
print(" Sequences differ by a/mulitple nucleotide ")
for lists, you can also just check equality:
if seq1 == seq2:
print(" The sequences are the same ")
elif len(seq1) != len(seq2):
print(" The sequences differ by their length ")
else:
print(" Sequences differ by a/mulitple nucleotide ")
you are only checking for the first element and exiting.
Seq1 = input( " Enter first sequence ")
Seq2 = input(" Enter second sequence ")
seq1 = list(Seq1)
seq2 = list(Seq2)
flag = False
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print(" The sequences differ by their length ")
exit()
else:
for i in range(len(seq1)) :
if seq1[i] == seq2[i]:
continue
else :
flag = True
break
if flag == False:
print(" The sequences are the same ")
else:
print(" Sequences differ by a/mulitple nucleotide ")
exit()
compare_seq(seq1,seq2)
the above code should help you. It check for the whole list instead of just and changes the flag to True if the elements don't match
Nearly had it but a few issues:
Seq1 = input( " Enter first sequence ")
Seq2 = input(" Enter second sequence ")
seq1 = list(Seq1)
seq2 = list(Seq2)
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print(" The sequences differ by their length ")
#exit() No need for this exit as it quits python and makes you have to reopen it everytime you run your function
else:
if seq1 == seq2: #the original loop structure was comparing everysingle item in the list individually, but was then exiting python before completion. So in reality only the first element of each sequence was being compared
print(" The sequences are the same ")
else :
print(" Sequences differ by a/mulitple nucleotide ")
compare_seq(seq1,seq2)
This should do the trick.
You can just check if any of the values at an index of the two lists are not equal, otherwise return true.
Example:
def compare_seq(seq1,seq2):
if len(seq1) != len(seq2):
print("sequences dont share the same length")
return false
for i in range(len(seq1)):
if seq1[i] != seq2[i]:
print("sequences are not the same")
return false
return true
Specifically: We are to print out how many of the guess character are exactly right (correct character in the
correct position) and
and how many of the guess characters are correct values but are not in the correct
position.
Here's my code:
key = input("Input your secret key (RYBGWO):")
print("You are playing Mastermind whose purpose is to guess the secret key.")
print("Six colors are to be inputed with no repeats (RYBGW0).")
Answer = input("Please enter your 4-letter guess (RYBGWO):")
Answer_count = 0
my_string = "RYBGWO"
history = ''
while Answer.upper() != key:
ANSWER = Answer.upper()
if Answer.count("R") > 1:
Answer = input("You can not have repeating characters, try again:")
continue
elif Answer.count("Y") > 1:
Answer =input("You can not have any repeating characters, try again:")
continue
elif Answer.count("B") > 1:
Answer = input("You can not have any repeating characters, try again:")
continue
elif Answer.count("G") > 1:
Answer = input("You can not have any repeating characters, try again:")
continue
elif Answer.count("W") > 1:
Answer = input("You can not have any repeating characters, try again:")
continue
elif Answer.count("O") > 1:
Answer = input("You can not have any repeating characters, try again:")
continue
elif not(Answer.isalpha()):
Answer = input("Error, guess must be letters only, try again: ")
continue
elif len(Answer) !=4:
Answer=input("Your guess must contain 4 letters (rybgwo).Try again:")
continue
if 'R' and 'Y' and 'B' and 'G' and 'W' and 'O' not in Answer:
Answer = input("ERROR: Only letters RYBGWO allowed. Try again:")
continue
for i, ch in enumerate(Answer):
correct_count = 0
correct_position = 0
wrong_position = 0
i = 0
if key[i] == Answer[i] and key[ch] == Answer[ch]:
correct_count += 1
correct_position +=1
i = [len(Answer)-1]
print("Correct color and position count:", correct_count)
elif key[ch] == Answer[ch] and key[i] != Answer[i]:
correct_count += 1
wrong_position += 1
i = [len(Answer)-1]
print("Correct color, wrong position:", )
else:
print("Congratulations! You won!")
Answer_count = Answer_count + 1
print("(",Answer_count,"of 8 guesses)")
history += "\n" + Answer
print("History:", history)
The line
if key[i] == Answer[i] and key[ch] == Answer[ch]:
does not make all that much sense. Using enumerate, i is the position, that's fine, but ch is the character at that position. key[ch] does not make sense. Did you mean key.count(ch)? But even then there is no easy way to get the "correct value at incorrect position" part easily with enumerate. Consider the case of "abcd" and "baca": Here, a has different count in both strings, and yet that should be +1 for correct_count
Instead, let me suggest this: For "correct value at correct position", just zip the two strings and compare the characters. The "correct value at incorrect position" case is a bit more difficult, but can be done by creating two Counter objects and &-ing those together.
>>> x = "abcd"
>>> y = "baca"
>>> Counter(x) & Counter(y)
Counter({'a': 1, 'c': 1, 'b': 1})
>>> [a == b for a, b in zip(x, y)]
[False, False, True, False]
When calculating the totals, remember that the correct_count number includes the correct_position number, so you need to subtract those:
>>> correct_position = sum(a == b for a, b in zip(x, y))
>>> correct_count = sum((Counter(x) & Counter(y)).values()) - correct_position
Down votes are coming because your criteria is not well defined, but I think that you are asking for a basic master-mind type problem. It is easy enough if you define your problem such that the hidden values do not repeat. If your hidden value, as I define it below can have repeating values than the problem gets more complex. It can be made to work - it just takes a bit more thought.
Anyway, here is a basic implementation that I've tested on my box.
hidden = ["red", "blu", "grn", "ylw", "gold", "ora"]
def check_answer(answer):
guess_num = 0
correct_position = 0
correct_location = 0
for guess in answer:
text = "value not found"
if (len(hidden) <= guess_num):
break
if guess == hidden[guess_num]:
correct_position += 1
text = "correct value and position"
elif guess in hidden:
correct_location += 1
text = "correct value, wrong position"
guess_num += 1
print("guess {} = {} ; {}".format(guess_num, guess, text))
ans1=["red", "grn", "blu", "ylw"]
ans2=["red"]
check_answer(ans1)