I am trying to write code to find the length of a string, and to return "invalid entry" when an integer is entered.
def length_of_string(mystring):
if type(mystring) == int:
return "invalid entry"
else:
mystring = input("enter the string ")
return len(mystring)
When I try to execute this function it doesn't give me an error, nor does it produce any solution.
You should move out mystring = input("enter the string ") from else and call the function from main or other place.
def length_of_string(mystring):
if type(mystring) is int:
return "invalid entry"
else:
return len(mystring)
mystring = input("enter the string ")
print(length_of_string(mystring))
If you want the string to be always requested from the user:
def length_of_string():
mystring = input("enter the string ")
try:
int(mystring)
return "invalid entry"
except ValueError:
return len(mystring)
print(length_of_string())
If you want to use the function with a parameter:
def length_of_string(mystring):
try:
int(mystring)
return "invalid entry"
except ValueError:
return len(mystring)
print(length_of_string("a string")) # prints 8
print(length_of_string(1)) # prints invalid entry
print(length_of_string(input("enter the string "))) # prints [input length]
The problem is that you have not called the function. Functions (similar to classes) do not run until you execute them.
Calling them is easy. You just have to call the function name. You also have to pass the necessary parameters to the function (here it is mystring).
length_of_string('Hello World')
To get what is returned you will need to pass it to a variable or print it/perform some other action.
print(length_of_string('Hello World'))
Also if type(mystring) == int: will not work input() is always a string. The thing to do is to test it and see if it can be made into an integer:
try:
int(mystring)
return "invalid entry"
except ValueError:
mystring = input("enter the string ")
return len(mystring)
Entire code:
def length_of_string(mystring):
try:
int(mystring)
return "invalid entry"
except ValueError:
mystring = input("enter the string ")
return len(mystring)
print(length_of_string('Hello World'))
If you pass a string by parameter, it does not make sense to overwrite it again.
I think the solution is:
def length_of_string(mystring):
if (isinstance(mystring, str)):
print "Length of the string: ", len(mystring)
else:
print "Type invalid"
Related
I'm trying to make a program that tests the strength of a password. Right now, everything else works, however the numbers doesn't. I can't test whether a string is a number without it not returning the last print statement. I probably haven't explained it well, but how can I make it so that it tests if a characer in a string is a number?
error_list = ['']
errors = ''
password = str(input('Enter in your password to test: '))
for char in password:
if type(char) == int:
safe_unsafe.append('y')
else:
safe_unsafe.append('n')
if 'y' in safe_unsafe:
pass
else:
errors = errors + 'No instance of a number was found.\n'
error_list.append('number')
safe_unsafe.clear()
print(errors)
You are looking for isdigit() API
https://docs.python.org/3.8/library/stdtypes.html#str.isdigit
Example
str = "1"
str.isdigit() #this return True
"a".isdigit() #return False
Updates in your code
error_list = ['']
errors = ''
password = str(input('Enter in your password to test: '))
for char in password:
if char.isdigit(): #changed line
safe_unsafe.append('y')
else:
safe_unsafe.append('n')
if 'y' in safe_unsafe:
pass
else:
errors = errors + 'No instance of a number was found.\n'
error_list.append('number')
safe_unsafe.clear()
print(errors)
I want to check a string and confirm it only has upper or lowercase alphabetical characters aswell as underscores.
I have this so far but I am getting errors
import re
def addPlayer():
print("\nEnter the players name:")
playerName = input()
for x in range(len(playerName)):
if re.match("[a-zA-Z_]", x):
return
else:
print("Error: Please enter a valid name.")
addPlayer()
Traceback (most recent call last):
File "player.py", line 9, in addPlayer
if re.match("[a-zA-Z_]", x):
File "c:.....Python\Python38-32\lib\re.py", line 189, in match
return _compile(pattern, flags).match(string)
TypeError: expected string or bytes-like object
You can check your entire username at once by checking that all the characters in the string are in the character class [A-Za-z_] i.e.
import re
def addPlayer():
print("\nEnter the players name:")
playerName = input()
if not re.match(r'^[A-Za-z_]+$', playerName):
print("Error: Please enter a valid name.")
addPlayer()
x is number and you passed it to re.match
Your for loop should be like this:
for char in playerName:
if re.match("[a-zA-Z_]", char):
return
else:
print("Error: Please enter a valid name.")
addPlayer()
or event better
regex = re.compile(r'[^a-zA-Z_]')
print(not bool(regex.search("abs123"))) # does not match
print(not bool(regex.search("abs"))) # match
So, the literal cause of that error is that x in an integer. So re.match(pattern, str(x)) fixes the error message. With that said, here is another (perhaps simpler) way to do this:
valid_chars = set([*string.ascii_uppercase, *string.ascii_lowercase, "_"])
for char in string:
if char not in valid_chars:
# Error Condition
## Acceptance Condition
You dont nee
import re
def addPlayer():
playerName='testT_'
m = re.match("[\w_]", playerName)
if m:
print("Success")
else:
print("Error: Please enter a valid name.")
for x in range(len(playerName)):
if re.match("[a-zA-Z_]", x):
return
x's type is int, not string.
you can use
for x in playerName:
if re.match("[a-zA-Z_]", x):
pass
or
for x in playerName:
if not x in string.ascii_letters+'_':
print("Error: Please enter a valid name.")
addPlayer()
i wrote an script , i want to know how to prevent when user enter number i show a message 'number is not OK! just string') .
Thanks.
#! /usr/bin/ipython3
a=input('Please enter your Name : ')
if a=='mohammadreza':
print(" ")
print ('i found you finally')
print(" ")
elif a=='':
print ('Null name is not ok!')
else:
print ('No you are not that person')
You have a string. And if you want to check if it is a number, you can use the following code:
a.replace('.','',1).isdigit()
So you can create a new elif like this:
elif a.replace('.','',1).isdigit():
print("number is not OK! just string")
problem here is input always return a string. isdigit handle this for you but it fails with floats (this is the reason behind "replace . solution").
Another approach could be:
#!/usr/bin/env python
def is_a_number(s):
'''try to convert a string to int and float'''
try:
int(s)
return True
except:
pass
try:
float(s)
return True
except:
pass
return False
def main():
a=input('Please enter your Name : ')
if a=='foo':
print ('i found you finally')
elif is_a_number(a):
print('number is not OK! just string')
elif a=='':
print ('Null name is not ok!')
else:
print ('No you are not that person')
if __name__ == '__main__':
main()
I created the following python code for an exercise in Python for informatics. The code will run, but will not recognize an input form the user that is larger than 1 as numeric. Any assistance would be appreciated.
def isfloat(string):
try:
float(string)
if float(string) == True:
return True
except ValueError:
return False
user_input = input('Please enter a real number. Type \"done\" to exit and tally your entries \n> ')
data = 0
count = 0
while isfloat(user_input) == True:
data = data + float(user_input)
count = count + 1
user_input = input("Please enter another value \n> ")
isfloat(user_input)
else:
if (isfloat(user_input) == False) and (user_input == "done"):
print("The sum of your entries is: " + str(data))
print("The number of entries was: " + str(count))
exit()
else:
print("The entry was not a numeric value \n")
print("The sum of your valid entries is: " + str(data))
print("The number of valid entries was: " + str(count))
exit()
This is ridiculous:
if float(string) == True:
That's checking if the float converted value is equal to True (which is numerically 1).
Just check for the exception and go:
def isfloat(string):
try:
float(string)
except ValueError:
return False
else:
return True
The problem lies in the fact that float(string) will never return True; it will always return a number of type float or it will raise a ValueError if the input cannot be converted to a float.
To fix this, you'll need to remove your if statement, and simply return True after calling float(string) in your isfloat function. If float(string) raises a ValueError, isfloat returns False as you would expect; otherwise, it will proceed and return True.
def isfloat(string):
try:
float(string)
return True
except ValueError:
return False
The problem is with your isfloat. You shouldn't compare the result of float with True. Instead do something like:
def isfloat(string):
try:
float(string)
return True
except ValueError:
return False
You don't need to actually do anything with the return value of float. If that call doesn't trigger an error -- you have a float, so just return True.
It might be tempting to use the line
if float(string): return True
That would almost work but would misclassify "0"
I am trying to create a function that receives input from a user, re-prompts until one character is entered. Strip() is used to removed whitespace so only characters are counted.
Here is my current code:
def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
while True:
value = (prompt)
Response = value.strip()
if len(Response) >=1:
print ('Valid')
else:
print(errorMessage)
continue
inputSomething(input('Enter str: '))
The problem I'm having is with the loop. Right now it loops the result infinitely. Should I not be using if else?
The problem is that the input is outside the loop:
import sys
def inputSomething(prompt, errorMessage = 'Atleast one character must be used'):
while True:
value = input(prompt)
Response = value.strip()
if Response:
print ('Valid')
return Response
else:
print(errorMessage, file=sys.stderr)
something = inputSomething('Enter str: ')
Note that an empty string equates to False.
I was confused with recursion, because of the indentation used in your question.
Change:
inputSomething(input('Enter str: '))
To:
inputSomething(lambda : input('Enter str: '))
And:
value = (prompt)
To:
value = prompt()
This way you pass a function and then call it, instead of passing the result of a called function.
For future references, another way that also includes retries:
import sys
def inputSomething(prompt, retries = 2, errorMessage = 'Atleast one character must be used'):
while retries > 0:
value = input("Enter str: ")
Response = value.strip()
if Response:
print ('Valid')
retries -= 1
continue
#return Response
else:
print(errorMessage, file=sys.stderr)
retries -= 1
inputSomething('prompt')