![]() |
Assistance with making functions - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Assistance with making functions (/thread-22226.html) |
Assistance with making functions - edwdas - Nov-04-2019 Howdy, this is not homework rather I want to know if its possible regardless of how inefficient the process is. Im attempting to create a function that checks if a string contains a digit and if it does prints out saying "Has no Digits: False" and allows to user to indefinitely. I just cant quite work out how to loop back so the "s" input to make in indefinite def strchk(): s = input(("Enter a string: ")) x = str.isdigit(s) while x == True: print(("Has no Digits: False")) if x == False: print(("Has no Digits: True")) strchk() RE: Assistance with making functions - ichabod801 - Nov-04-2019 Loop over the characters in the string (for char in s:). Check each character to see if it is a digit. If it is, return True. If you get to the end of the loop, none of the characters are digits. So just return False after the loop. RE: Assistance with making functions - bobfat - Nov-04-2019 Hello, You mean that you need something like the following code? def strchk(): s = input(("Enter a string: ")) dig = False for x in s: if x.isdigit(): dig=True return dig while True: if strchk()== True: print("Has no Digits: False") else: print("Has no Digits: True") RE: Assistance with making functions - micseydel - Nov-14-2019 @bobfat that's different from ichabod's suggestion because ichabod's will short-circuit. You see how you complete the whole loop even if the first character is a digit? What you can do instead is to just return True within your if, and return False if the loop exits without the inner return. Also, this looks like homework, so even though the OP says it isn't, I'd recommend not providing a full function to do what they're looking for, unless it's trivial... And if the OP isn't doing this as homework, and they can use whatever module they want, they can have a one-liner: import re def contains_digit(string): return re.match(r'.*\d', string) is not NoneIn use:
RE: Assistance with making functions - bobfat - Nov-23-2019 You're right :) |