I'm very new to programming, and more new to Python, and I'm having a hard time figuring this out. I'm trying to make a simple text hangman game, and I'm trying to validate player1's input. Here's what I have so far.
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
d = list(d)
print(d)
if any(int) == any(d):
print("Invalid input. Please choose a non-number with no spaces or special characters.")
I can't figure why, whether I include a number in my response or not, it always meets my any(int) == any(d) condition. I know I must just be misunderstanding how any() works.
You are right: the issue is with how you use the any() function. any() returns either True or False depending on whether or not any of the elements in its iterable argument are True, in other words if they exist and are not False or an empty list or empty string or 0. This will always evaluate as True for int because int does contain an element that is True and the same will happen for d unless you do not give any input when the input() function prompts you (you hit return without typing anything). What your conditional is basically asking is the following:
if True==True
To fix this, just change your code to the following:
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
print(d)
for letter in d:
if letter in int:
print("Invalid input. Please choose a non-number with no spaces or special characters.")
break
The easiest solution, however, does not involve the int list at all. There is actually a special method in python that can gauge whether or not a string has a number (or special character) in it, and this method, .isalpha() can be used to streamline this process even further. Here's how to implement this solution:
while True:
d = input("Please choose any word by typing it here: \n")
print(d)
if not d.isalpha():
print("Invalid input. Please choose a non-number with no spaces or special characters.")
Try this:
a = 0
ints = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
word = input()
word_list = list(word)
if any(letter in ints for letter in word_list):
print("Invalid input. Please choose a non-number with no spaces or special characters.")
Related
I'm making a basic text-based hangman game, and I'm stumped as to why inpLetter is returning None from letterVerify()? It's expected to return a string response so I'm unsure why it isn't.
def letterVerify(prompt):
try:
inp = input(prompt)
verify = str.count(inp)
if (verify > 1) or (verify < 1):
print("Please enter one character.")
if inp not in alphabet or alphabetCaps:
print("Please enter a letter from the English alphabet.")
else:
return inp
except:
print("Please enter a letter from the English alphabet.")
inpLetter = letterVerify("Enter a letter you think is in this word. ")
The problem is in line 4, verify = str.count(inp). count() function returns the number of times a particular character has appeared in a string. It is used as
string = 'abcabcabcabcabc'
string.count('a')
This returns 5. Your code could not find this error because of the try-except block. Whenever this error was raised, it was caught by the exception block, and hence made it difficult to debug. You can rather try using the len() function. This will do the same work you want. It will check if the length of input is 1 or not. Modifications to your code are as
def letterVerify(prompt):
inp = input(prompt)
verify = len(inp)
if verify > 1 or verify < 1:
print('Please enter 1 character')
elif not inp.isalpha():
print('Please enter a letter from English alphabet')
else:
return inp
inpLetter = letterVerify('Enter a letter you think is in this word')
Also, you did not specify what alphabet and alphabetCaps are. I have used isalpha() method, that checks only for alphabetical characters (what you needed). Hope this resolves your issue.
I made your function a little terse for better readability.
First, you should avoid naming your function in camelCase, this violates PEP8. Rather you should use snake_case while naming functions and variables.
Also, simple length checking will do the verify trick. str.count returns the number of times a letter appears in a string, you don't want that here.
You don't need the exception handler here. Python will internally make your inputs str type.
You can lower your string and make comparison with the built in string.ascii_lowercase property. This will eliminate redundant control flow logic.
Here is the function, refactored:
def letter_verify(prompt):
inp = input(prompt)
# remove extra whitespace
inp = inp.strip()
# simple length checking with len function will do the trick
if len(inp) != 1:
print("Please enter one character.")
# just make your input to lowercase and then compare
# this will help you avoid comparison with two cases
elif inp.lower() not in string.ascii_lowercase:
print("Please enter a letter from the English alphabet.")
else:
return inp
I'm trying to make sure that every word that is typed is uppercased as in ABC. The code I'm working with is this
abbreviate=input("Abbreviation: ")
words=abbreviate[0:6]
numbers = abbreviate[6:8]
if len(abbreviate)==9:
if words.isalpha: #I think it's also possible to use.if str(words)?
if words.isupper: #(i did upper first, what is the difference?)
if int(numbers):
print("correct")
else:
print("wrong, you need numbers")
else:
print("wrong, all words are supposed to be uppercase")
else:
print("wrong, it needs to be words(alphabet)")
else:
print("wrong, the length needs to be 8")
QWERTY567 should be correct.
qwerty567 should be incorrect.
How do I go on doing this?
qwerty333
012345678
IIUC In order to just verify, whether first 5 characters are uppercase letters, and next 4 are digits, you can do:
import re
abbreviate=input("Abbreviation: ")
if(re.match(r"^[A-Z]{5}\d{4}", abbreviate)):
print("correct!")
else:
print("wrong!")
If moreover you want to ensure it's only 9 characters in total (i.e. input consists of exactly 5 uppercase letters first, then 4 digits) you can do:
import re
abbreviate=input("Abbreviation: ")
if(re.match(r"^[A-Z]{5}\d{4}$", abbreviate)):
print("correct!")
else:
print("wrong!")
str.isalpha and str.isupper are methods. You need to call them to get a result:
if words.isalpha():
if words.isupper():
About your comments
I think it's also possible to use if str(words)?
No, str(words) would do nothing. input() returns a string, so words is already a string.
I did upper first, what is the difference?
str.upper converts a string to uppercase, e.g. 'a'.upper() == 'A'
By the way
int() doesn't return a Boolean. It might be better to use str.isnumeric to check if numbers is numeric instead.
It's simpler to use guard clauses than nested conditionals:
if len(abbreviate) != 9:
print("wrong, the length needs to be 9")
elif not words.isalpha():
print("wrong, the abbreviation must be alphabetic")
...
else:
print("correct")
Use a regular expression:
^[A-Z0-9]+$
See a demo on regex101.com.
If you have all letters and then at a certain index, you have all numbers, I would suggest:
abbreviation=input("Abbreviation: ")
i = len(abbreviation)
for n, char in enumerate(abbreviation):
if char.isalpha() and char.isupper():
pass
else:
i = n
break
for char in abbreviation[i:]:
if char.isnumeric():
pass
else:
print('Wrong')
https://www.geeksforgeeks.org/python-string-isnumeric-application/
https://www.geeksforgeeks.org/isupper-islower-lower-upper-python-applications/
You find the first non-lowercase letter, and then everything after it should be all numeric. If you need at least 1 uppercase letter, you can also modify that. Please tell me if you have questions!
If the value of abbreviate is 'QWERTY567', then you should edit your code with words = abbreviate[0:6] , numbers = abbreviate[6:8] , isalpha() and isupper() for it to work.
How would I go about telling the user when they've got the correct letter in a list? Only way I know of is to insert the index, but that doesn't feel very flexible, especially when the words vary in length.
import random
possibleWords = [["apple"], ["grapefruit"], ["pear"]]
randomWord = random.choice(possibleWords)
anotherWord = ''.join(randomWord)
finalWord = list(anotherWord)
maxTries = list(range(0, 11))
attemptsMade = 0
triesLeft = 10
print("Hangman!")
print("\nYou got {} tries before he dies!".format(maxTries[10]))
print("There's {} possible letters.".format(len(finalWord)))
for tries in maxTries:
userChoice = input("> ")
if userChoice == finalWord[0]:
print("You got the first letter correct! It is {}.".format(finalWord[0]))
else:
print("Ouch! Wrong letter! {} tries remaining.".format(triesLeft))
attemptsMade += 1
triesLeft -= 1
Talking about characters in lists, or - what i think is more likely in your case - chars in words you can just check for
if userChoice in finalWord:
# [...] do stuff here
and further on use the index function to determine the position (or positions if multiple occurence).
finalWord.index(userChoice)
You could sure also go the way using index() function directly and work your way using the return values.
Use Python's "in" keyword to check if something is within a list/iterable.
if userChoice in finalWord:
Though for this, I'd just use regex or list comprehension to get the indexes while you are at it, since you might want them for the game.
char_indexes = [i for (i, l) in enumerate(finalWord) if l == userChoice]
if len(char_indexes):
Use a set for the letters that are in the word, and whenever the player guesses a letter, check if the letter is still in the set. If it’s not, it was a wrong letter; if it is, then remove that letter and just continue. If the set is empty at some point, then the player guessed all letters of the word.
Something to get you started:
def hangman (word):
letters = set(word.lower())
attempts = 5
while attempts > 0:
guess = input('Guess a character ')
if guess[0].lower() in letters:
print('That was correct!')
letters.remove(guess[0])
else:
print('That was not correct!')
attempts -= 1
if not letters:
print('You solved the word:', word)
return
hangman('grapefruit')
import re
def check_input():
while True:
try:
sequence = raw_input("Please input:")
if sequence = [a,t,c,g]: # checking for valid input
continue
else:
print("invalid input, sequence coule only contain the "
"following letters (a,t,c,g)"):
check_input()
I basically want the script to check the user's input whether it contains only these four letters (a,t,c,g). If their input contains anything other than that four letters, it could print that second statement and prompt the user to input again. I saw there are similar questions and I already tried to change my script according to those posts but it still gives me the invalid syntax error at the if < sequence position. Anyone knows what's wrong here?
You need to iterate over every letter in the input and check if it is in the set of allowed letters, like this:
sequence = raw_input("Please input:")
for letter in sequence:
if letter not in "atcg":
print("invalid input, sequence coule only contain the following letters (a,t,c,g)")
When you discover that the sequence is invalid, you could choose to end the check by using a break statement after the print, or you could count how many invalid letters are allowed.
Your function must check and give user whether True or False:
def check_input(word):
result = True
for letter in sequene:
if letter in 'atcg':
continue
else:
result = False
break
return result
check_input('atgc')
Error Message:
if check_input('agct'):
continue
else:
print "error message"
You could also use the filter command:
def checkInp():
seq = raw_input("Please input sequence:")
if not filter(lambda m: m not in 'ATGC', seq) == '':
print 'Invalid input characters in sequence: ' + filter(lambda m: m not in 'ATGC', seq)
print 'Pleas'
check_input()
else: return seq
sequence, once input by the user will be a string, so you would need to iterate over each character in the sequence and use in to verify the existence of the character in the accepted characters string. String comparisons in Python are also case sensitive, so you need to match the case of the input to your expected string. I've used uppercase based on your sample input.
def check_input():
sequence = input("Please input:")
sequence.upper()
for letter in sequence:
if letter in 'ATCG':
continue
else:
print("invalid input, sequence could only contain the
following letters: a, t, c or g.")
I am trying to write a simple password checker for homework assignment, looking for at least one capital, one lower case, one digit, and it needs to be 6 or more chars.
I have searched and searched on here and elsewhere, but either what I read doesn't match our instruction, or the replies are more advanced than myself. Any help I get will be cited as a comment in my assignment.
This is just the part of my code which checks for caps, it only looks at the whole string, not the individual characters and I can't seem to find the solution.
passwd = input('enter password: ') ## we are actually using (sys.agrv)
## but I am using this for testing
character = passwd[0:]
lcase_bad = False
for character in passwd:
if not character.islower() > 1:
lcase_bad = True
if lcase_bad:
print('Password must include lowercase letters ')
else:
print('password accepted')
for character in passwd:
Here you're iterating through each letter of the input.
When you do if not character.islower() > 1:, it will always be True. .islower() returns either True or False, depending on if the string is a capital letter or not. not False == 1, because boolean is a subclass of int. not True == 0. Both are not greater than one.
You can just do something like:
capital = False
lowercase = False
number = False
if len(passwd) < 6:
print 'That was not more than 6 characters'
else:
for character in passwd:
if character.islower():
lowercase = True
elif character.isupper():
capital = True
elif character.isdigit():
number = True
if capital and lowercase and number:
break
else:
print 'That did not have a capital letter, lowercase letter, and a digit'
Of course this is useful if you want to tell the person what the password didn't have. However, you can also just do one test instead.
Just check for all those conditions one after another:
mystring = input("enter password: ")
if any(c.isupper() for c in mystring) \ # There is an uppercase letter
and any(c.islower() for c in mystring) \ # There is a lowercase letter
and any(c.isdigit() for c in mystring) \ # There is a number
and len(mystring) > 5: # The length is 6 or greater
# string passed all tests
else:
# One or more tests failed--input is bad.
You've almost got it! If you remove the > 1 from your code (which won't really do anything useful), you get this:
lcase_bad = False
for character in passwd:
if not character.islower():
lcase_bad = True
It just happens that this will test to see if the entire string is made of lowercase letters. If it is, lcase_bad will remain False; otherwise, it will become True. It should not be an extreme leap of faith to see that if you flip the False and True around and call it lcase_good, you can see whether at least one character is lowercase.
As iCodez notes, you can also rewrite it using any with a generator comprehension. It reads fairly easily:
if any(character.islower() for character in passwd):
However, you probably haven't gotten to generator comprehensions, so it might be best to stay with a for loop for clarity's sake.