I want to make a function which checks whether a string starts with "Yes" or "No" but I'm not sure how.
If string begins with "Yes"
return "Yes"
Try startswith function:
if myStr.startswith("Yes"):
return "Yes"
elif myStr.startswith("No"):
return "No"
Note that there is also endswith function to check that your string is ending with the text expected.
If you need to check that string is not starts with:
if not myStr.lower().startswith("yes"):
return "Not Yes"
elif not myStr.lower().startswith("no"):
return "Not No"
Possibly more flexible is good
if s.lower().startswith("yes"):
return "Yes"
elif s.lower().startswith("no"):
return "No"
Have you tried:
yourString.startsWith("Yes")
All you need is
String.startswith("yes")
if the string doesn't start with yes it will return false and if it does, true.
name = "Yes? test"
if name.index('Yes') == 0:
print 'String find!!'
This may be the best solution:
def yesOrNo(j):
if j[0].lower() == 'y':
return True
elif j[0].lower() == 'n':
return False
else:
return None
def untilYN():
yn = input('Yes or no: ')
j = yesOrNo(yn)
while j == None:
yn = input('Please insert yes or no again; there may have been an error: ')
j = yesOrNo(yn)
return j
print(untilYN())
For example:
print(untilYN())
>> Yes or no: Maybe
>> Please insert yes or no again; there may have been an error: yeah then
True
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
I keep getting an error when I run this functions. Everything goes through and then it shows this error. I have tried adding .items() to the end when I print the dictionary and still throws this error.
CLARIFICATION just realized. Not getting any type errors or anything. It prints fine but when doesn't add the second variable to the dictionary. Instead it prints this..
{'Frappe': ('small', function type_of_milk at 0x000002BE2BCD2F78>)}
def order():
ready_to_order = True
while ready_to_order != False:
ordering_q = input(
"""Do you know what you would like to order or do you need to see the menu?
[M]enu or [R]eady to order or [Q]uit: """)
if ordering_q.upper() == "Q":
sys.exit()
elif ordering_q.upper() == "M":
print(Menu())
elif ordering_q.upper() == "R":
ready_to_order = False
else:
print("Please enter valid letters only, try again.")
print(" ")
print(" ")
add_cart = True
while add_cart != False:
order1 = input("What would you like to order?")
if order1.upper() == "Done":
add_cart = False
elif order1 == 'a1':
print("Frappe added to cart")
global total_order
total_order += 3
drink_size()
type_of_milk()
order_dict['Frappe'] = (drink_sizes, type_of_milk)
add_cart = False
print(order_dict)
This line:
order_dict['Frappe'] = (drink_sizes, type_of_milk)
is adding the function type_of_milk to your dict, which is why you see function type_of_milk at 0x000002BE2BCD2F78> when you print the dict out. Maybe you meant to say type_of_milk()?
I want to see if I can find 2 successive letters in a taken string without overlapping .
for example : if there are "HP" and "PH" in the string answer is "YES" and if not answer is "NO" .
e.g :
input -----> PHHP
output ----> YES
or :
input -----> HPPH
output ----> YES
and :
input -----> PHP
output ----> NO
or :
input -----> PHAP
output ----> NO
I guess this should work with still scope for optimization.
s = 'phhp'
def validate():
for i in range(len(s)):
if len(s[i:i+2]) != 2:
break
if 'ph' == s[i:i+2]:
if 'hp' in s[0:i] or 'hp' in s[i+2:i+4]:
return True
return False
print ('Found' if validate() else 'Not Found')
You can use re.
Demo:
import re
def validate(string):
return 'YES' if re.search(r'(PH.*HP)|(HP.*PH)', string) else 'NO'
inputs = ['PHHP', 'HPPH', 'PHP', 'PHAP']
for inp in inputs:
print(inp, validate(inp))
Output:
PHHP YES
HPPH YES
PHP NO
PHAP NO
Try checking if 'hp' is in s and if it is replace it with ' ' now check if 'ph' is in s if it is return 'YES':
def func(s):
s = s.lower()
if 'hp' in s:
s = s.replace('hp',' ')
if 'ph' in s:
return 'YES'
else:
return 'NO'
else:
return 'NO'
print(func('HPHP'))
Output:
NO
This will work for any pair of char, not just PHHP
def validator(mystr):
for i in range(len(mystr) - 2):
Yo=''.join(reversed(mystr[i+2:i+4]))
return mystr[i:i+2] == Yo
validator ('PHHP')
#True
def specificChecker(someThing, checker):
if checker == None:
return someThing
elif checker == True:
return not someThing
else:
return None
def whatDoesTheCheckerSay(someThing):
if specificChecker(someThing) == someThing:
return 'The checker value was False on that one.'
elif specificChecker(someThing) == not someThing:
return 'The checker value was True on that one.'
elif specificChecker(someThing) == None:
return 'Something irregular happend. The checker value wasn\'t None or True.'
else:
return 'Something went really wrong. This doesn\'t even not work.'
reallySomeThing = input('Type in really some thing: ')
theChecker = input('Set the checker to something: ')
print(specificChecker(reallySomeThing, theChecker))
print(whatDoesTheCheckerSay(reallySomeThing)) # This can be made more efficient, right?
def one(someShit):
return someShit + ' AWWW YEAH!'
def two(someShit):
return one(someShit)
print(two(input('Type in some kind of stuff: ')))
I'm a self-taught beginner, so surely it's something awkwardly basic. I'm using the IDLE shell and have repeatedly gotten a syntax error at the second definition statement of my codes. Please help?
You cannot use the line:
elif specificChecker(someThing) == not someThing:
This must be written
elif specificChecker(someThing) != someThing:
to be valid Python.
This is also valid but is perhaps less readable:
elif (specificChecker(someThing)) == (not someThing):
After OP edit:
The new error is the mismatch in arguments (always 1) to a function that requires 2 arguments. You have to pass two arguments to specificChecker not one
Line 12: elif specificChecker(someThing) == not someThing:
If you want to check if some variable is not some variable, used is not for boolean or != for values and strings
I'm new to programming, and I was wondering how I can repeat an input section, if the user types in invalid data.
I want the application to just repeat the input section, instead of having to run the function all over again and making the user type everything all over again.
My guess is that I would have to change the "return main()" into something else.
condition = input("What is the condition of the phone(New or Used)?")
if condition not in ["New", "new", "Used", "used"]:
print("Invalid input")
return main()
gps = input("Does the phone have gps(Yes or No)?")
if gps not in ["Yes", "yes", "No", "no"]:
print("Invalid input")
return main()
You can make a method to check it in a loop:
def check_input(values, message):
while True:
x = input(message)
if x in values:
return x
print "invalid values, options are " + str(values)
You can generalise the code to use a message prompt and a validating function:
def validated_input(prompt, validate):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = validate(value)
return value
eg:
>>> def new_or_used(value):
... return value.lower() in {"new", "used"}
>>> validate_input("New, or used?", new_or_used)
Or, simpler, but less flexible, pass in the valid values:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt)
valid_input = value.lower() in valid_values
return value
And use:
>>> validate_input("New, or used?", {"new", "used"})
You could even use the valid values to create the input prompt:
def validated_input(prompt, valid_values):
valid_input = False
while not valid_input:
value = input(prompt + ': ' + '/'.join(valid_values))
valid_input = value.lower() in valid_values
return value
Which gives a prompt:
>>> validate_input("What is the condition of the phone?", {"new", "used"})
What is the condition of the phone?: new/used
Here is a good reading about Control Flows.
Also in your case, you can use strip() and lower() for user inputs.
>>> 'HeLLo'.lower()
'hello'
>>> ' hello '.strip()
'hello'
Here is the solution for Python 3:
while True:
condition=input("What is the condition of the phone(New or Used)?")
if condition.strip().lower() in ['new', 'used']:
break
print("Invalid input")
while True:
gps=input("Does the phone have gps(Yes or No)?")
if gps.strip().lower() in ['yes','no']:
break
print("Invalid input")