I've written a validation function that looks like this:
def validateFloat(self, text):
if (text == ''):
return True
try:
float(text)
return True
except ValueError:
return False
But I can still enter spaces after I enter a digit. I want to make it so that it doesn't allow spaces, only dots and digits.
Thanks in advance.
If you only want to catch spaces
def validateFloat(self, text):
if (text == ''):
return True
elif ' ' in text:
return False
try:
float(text)
return True
except ValueError:
return False
You can simply use
x=isinstance(text,float)
if text variable is float, this will return true.
To remove space from text use strip function as mentioned below.
text.strip()
If you want to check whitespace in text. Use below
if ' ' in text:
Related
Is it possible to assign a variable to an return result of an function ?
First I want to acquire the website from email like for e.g xxxxx#hotmail.com will return only hotmail.com. Then if that website is equal to 'hotmail.com' return 'Yes' if not equal return 'No'.
def mail(var):
x = return var.split('#')[1]
if x == 'hotmail.com':
return 'Yes'
else:
return 'No'
I know it's not the right code but I hope You get the idea. Thanks for your help !
I think what you want is this:
def mail(var):
return 'Yes' if var.split('#')[1] == 'hotmail.com' else 'No'
x = mail('foo#hotmail.com')
print(x)
Note:
If var does not contain '#' this will fail with IndexError
You have to remove your first return, beacause then your function immediately exits, then it works:
def mail(var):
x = var.split('#')[1]
if x == 'hotmail.com':
return 'Yes'
else:
return 'No'
print(mail('user#hotmail.com'))
print(mail('user#gmail.com'))
Output:
Yes
No
I suggest to validate the email in parameter to avoid exception by checking if it contains '#' in argument and checking for dot ('.') within index of '#' to the last char, if it's invalid then return 'is not valid email'. If it's a valid email then assign the value of variable x by indicing from next index of '#' (same result as split). And the last, check if x is fit to the condition that you want (in this example: 'hotmail.com')
def mail(var):
if '#' in var and '.' in var[var.index('#'):]:
x = var[var.index('#')+1:]
print(x)
return 'Yes' if x == 'hotmail.com' else 'No'
else:
return f'{var} is not valid email'
print(mail('xxxxx#gmailjp'))
print(mail('xxxxxgmail.com'))
print(mail('xxxxxgmailnl'))
print(mail('xxxxx#gmail.us'))
print(mail('xxxxx#hotmail.com'))
# xxxxx#gmailjp is not valid email
# xxxxxgmail.com is not valid email
# xxxxxgmailnl is not valid email
# gmail.us
# No
# hotmail.com
# Yes
But I prefer this:
def mail(var):
return 'Yes' if 'hotmail.com' in var else 'No'
print(mail('xxxxx#gmail.us'))
print(mail('xxxxx#hotmail.com'))
# No
# Yes
So here is the issue. I have a series of functions with which an inputString from the user gets checked to meet all of the set password criteria:
Passwords must be at least 5 characters long
Passwords must contain at least one upper case letter
Passwords must contain at least two numbers
Passwords may not contain the characters "E" or "e"
Passwords must include at least one non-alphanumeric character.
A password may not be a frequently used password: 'password', '12345',
'qwerty', 'letmein', 'trustno1', '000000', 'passw0rd,'Password'
My last function attempts to collect all of the functions defined into a single usable module function. There are no errors running the program but there is a bug which always prints, "Invalid! Password must contain special character." Why is that so? And what other bugs or fixed do you guys suggest to make this code more efficient or readable?
def isFiveCharacters(inputString):
while len(inputString) > 5:
return True #print('Contains at least 5 characters, ')
else:
print('Invalid! Password must cantain more than 5 characters')
return False
def hasUpperCase(inputString):
x = any(char.isupper() for char in inputString)
if x == True:
return True #print ('an uppercase letter, ')
if x == False:
print('Invalid! Password must contain an upper case letter')
return False
def hasNumbers(inputString):
count = 0
for char in inputString:
if char == char.isdigit():
count += 1
if count >= 2:
#print ('two numbers, ')
return True
elif count < 2:
print ('Invalid! Password must contain two numbers')
return False
def hasLetterE(inputString):
for char in inputString:
if 'E' and 'e' in inputString:
print('Invalid! Password cannot contain the letter "E"')
return False
else:
#print('does not contain the letter E, ')
return True
#if 'e' in inputString:
# print('Password cannot contain the letter "e"')
# return None
def nonAlphaNumChar(inputString):
special_char = ['!','#','$','%','#','^','&','*']
if inputString == special_char * 2:
#print('a special character, ')
return True
else:
print('Invalid! Password must contain a special character')
return None
def usedPasswords(inputString):
used_passwords = ('password','12345','qwerty','letmein','trustno1','000000','passw0rd','Password')
if used_passwords == inputString:
print('Invalid! Password must be original.')
return False
def passwordCriteria(inputString):
isFiveCharacters(inputString)
hasUpperCase(inputString)
hasNumbers(inputString)
hasLetterE(inputString)
nonAlphaNumChar(inputString)
usedPasswords(inputString)
while inputString == True:
print('Valid Password')
return True
if inputString == False:
print('Error, invalid password')
return False
return None
I am just going to point out the obvious mistake:
You should collect the values returned by the functions like this
valid = isFiveCharacters(inputString)
# then just use the boolean values with an `and`
valid = valid and hasUpperCase(inputString)
valid = valid and hasNumbers(inputString)
# and so on
# then use
if valid:
print("Valid Password")
else:
print("Invalid Password")
I suggest reading about functions the return statement and the while loop in detail and getting a clear understanding of how they work.
def check(text):
pattern = re.compile(r'\\')
rv = re.match(pattern, text)
if rv:
return True
else:
return False
print check('\mi') # True
print check('\ni') # False
Actually,I want text contains '\' is illegal.
But '\n', '\b',etc, python treats them specially,so I can not match them out.
Any solutions?
Why would you need or want to use a regex for this?
return '\\' in text
def check(text):
rv = re.search('(\\\\)|(\\\n)', string)
if rv:
return True
else:
return False
string = "\mi"
print check(string)
string = "\ni"
print check(string)
Result:
================================ RESTART ===============
True
True
\\\n includes newlines.
You can specifically search this way for \n by escaping \\ and adding \n. Works with \b etc...
I am supposed to write a script with the following criteria:
Write a function called validatePassword that takes a password string as a parameter and returns true or false. The function should only return true if:
The password is at least 8 characters
The password contains at least one number
The password contains at least one upper case letter. Hint: use the isupper() string function.
The password contains a symbol one of the symbols !##$%^&*()+=
I have this so far:
def validatePassword(pswd):
if len(pswd)> 8:
return True
else:
return False
for char in pswd:
if char in '01234567890':
return True
else:
return False
for char in pswd:
if char in '!##$%^&*()_+=':
return True
else:
return False
for char in pswd:
if char.isupper and char .islower:
return True
else:
return False
return True
while False:
print("There was an error with your password")
print (validatePassword(Herseuclds))
I know that print (validatePassword(Herseuclds)) has a syntax error because I am missing the variable but I just don't get how to do this.
def validatePassword(pswd):
if len(pswd) < 8:
return False
number_in_password = False
for char in pswd:
if char in '012356789':
number_in_password = True
if not number_in_password:
return False
symbol_in_password = False
for char in pswd:
if char in '!##$%^&*()_+=':
symbol_in_password = True
if not symbol_in_password:
return False
uppercase_in_password = False
for char in pswd:
if char.isupper():
uppercase_in_password = True
if not uppercase_in_password:
return False
#this only happens if nothing above has disqualified the password
return True
print (validatePassword("herseuc"))
print (validatePassword("herseuclds"))
print (validatePassword("herseuclds!"))
print (validatePassword("herseuclds!123"))
print (validatePassword("herseuclds!123A"))
The main issue with your code is in the last line.
print (validatePassword(Herseuclds))
Right now, the interpreter thinks Herseuclds is a variable, and not a string. If Herseuclds is the password, and not a variable describing the password, then you need quotes around it to make it a string literal.
print (validatePassword("Herseuclds"))
You obviously haven't defined a variable called Herseuclds anywhere in your program, but the program thinks Herseuclds is a variable and not a string, so it throws the error.
Best of luck, and happy coding!
First issue is that you are passing an undeclared variable to your function. See silentphoenix's answer for details.
Secondly, your program only check to see if AT LEAST ONE condition is met, not all.
If a password is 8 characters long, it will return true even if the password doesn't satisfy the other requirements.
I am not going to write your code for you, but I can pseudocode the issue:
def validatePassword(pswd):
if len(pswd) < 8:
return False
# if there isn't a number:
return False
# if there isn't a symbol:
return False
# if there isn't an upper and lowercase:
return False
return True
while True:
print("There was an error with your password")
print (validatePassword("Herseuclds"))
sidenote: watch your indentation :)
Since you can use is.upper() you can also utilize is.digit() to check for numbers instead of having to write down actual digits.
Another thing to speed it up, since they all have to be done at the same time, you can check if the password validates those requirements in one line with any()
def validatePassword(pswd):
l = []
if len(pswd)> 8:
for char in pswd:
l.append(char)
if any(l for x in l if x.isdigit()) and any(l for x in l if x.isupper()) and any(l for x in l if x in '!##$%^&*()_+='):
print('Success')
else:
print('Try again')
while True:
a = input('What is your password?')
validatePassword(a)
At the beginning there's an minimum check to see if the lengeth is greater than 8. If it is, the word gets broken up into a list. This allows any() to be used and checked against the remainding requirements.
def valid_password(password):
return (
# The password is at least 8 characters
len(password) >= 8 and
# The password contains at least one number
any(c in "0123456789" for c in password) and
# The password contains at least one upper case letter
any(c.isupper() for c in password) and
# The password contains a symbol one of the symbols !##$%^&*()+=
any(c in "!##$%^&*()+=" for c in password))
Example:
from getpass import getpass
while not valid_password(getpass('Enter password: ')):
print('invalid password. Try again')
Homework exercise:
Checking whether a text is a palindrome should also ignore punctuation, spaces and case. For example, "Rise to vote, sir." is also a palindrome but our current program doesn't say it is. Can you improve the above program to recognize this palindrome?
origin code:
def reverse(text):
return text[::-1]
def is_palindrome(text):
return text == reverse(text)
something = input('Enter text: ')
if (is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
my try:
import re
def reverse(text):
global words
words = text.split()
return words[::-1]
def is_palindrome(text):
return words==reverse(text)
something = input('Enter text: ')
if (is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
Error:
Enter text: jfldj
Traceback (most recent call last):
File "/Users/apple/PycharmProjects/Problem Solving/user_input.py", line 13, in <module>
print("Yes, it is a palindrome")
File "/Users/apple/PycharmProjects/Problem Solving/user_input.py", line 10, in is_palindrome
NameError: name 'words' is not defined
How should I change my code?
Latest code:
import string
def remove_punctuations(word):
return "".join(i.lower() for i in word if i not in string.ascii_letters)
def reverse(text):
return text[::-1]
def is_palindrome(text):
text = remove_punctuations(text)
return text == reverse(text)
something = input('Enter text: ')
if (is_palindrome(something)):
print("Yes, it is a palindrome"
else:
print("No, it is not a palindrome")
No matter what I input, output is Yes.
Enter text: hggjkgkkkk
Yes, it is a palindrome
What's wrong?
To ignore the punctuations, spaces and case of the given text you need to define a function remove_punctuations() which takes a word as parameter and returns a word with all lower case characters, remove punctuation marks and removed spaces.
To remove the unwanted characters we need to iterate over the given text, if the current character falls in strings.ascii_letters , then generate the character converting it to lower caps using str.lower() method. Finally using "".join() method to concatenate the generated str elements.
import string
def remove_punctuations(word):
return "".join(i.lower() for i in word if i in string.ascii_letters)
def reverse(text):
return text[::-1]
def is_palindrome(text):
text = remove_punctuations(text)
return text==reverse(text)
something = "Rise to vote, sir."
if (is_palindrome(something)):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
Since the hint says to use a tuple with forbidden punctuation marks, I created the following variant:
forbidden = (' ', ',', "'", '?', '!', '.', '’')
def reverse(text):
return text[::-1]
def cleaning(text):
clean_text = ''
for item in text:
if item not in forbidden:
clean_text += item
return clean_text
def is_palindrome(text):
lower_text = cleaning(text.lower())
return lower_text == reverse(lower_text)
example = input('Enter something: ')
if is_palindrome(example):
print("Yes, it is a palindrome")
else:
print("No, it is not a palindrome")
The cleaning function checks each character for belonging to a tuple of forbidden characters, if not, then concatenates it to the clean_text string
I started studying for python 2 days before so that is what i come up with.
It is not so much advanced but works like a charm. :D
It is pretty straight forward what i do there. I just make a tuple with the "legal" letters (abc=). Then I define a function that 1st change all letters to lower case and then checks every character in the string with the "legal" letters. Then after this "filtering" the rawtext contains only the "legal" ones. Then the 2nd function just reverses the results of the 1st one. Compare and da da..!
# Palindrome recognize
abc='abcdefghijklmnopqrstuvwxyz'
def rawtext(text):
rawtext=''
text=text.lower()
for j in text[::1]:
for i in abc[::1]:
if j==i:
rawtext=rawtext+j
return rawtext
def reverse(text):
rev= rawtext(text)[::-1]
return rev
text=str(input('Write text:'))
if reverse(text)==rawtext:
print('The text is palindrome')
else:
print('The text is not a palindrome')
from itertools import izip_longest
def is_palindrome(s):
l = len(s)
fi = (i for i in xrange(l) if s[i].isalpha())
bi = (i for i in xrange(l-1, -1, -1) if s[i].isalpha())
for f, b in izip_longest(fi, bi):
if f >= b: return True
if s[f].lower() != s[b].lower(): return False
return True
Hope that helps