Python Forum
Assistance with making functions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Assistance with making functions
#1
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()
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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")
Reply
#4
@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 None
In use:
Output:
>>> contains_digit('abc 123') True >>> contains_digit('abc one two three') False
Reply
#5
You're right :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calling functions by making part of their name with variable crouzilles 4 833 Nov-02-2023, 12:25 PM
Last Post: noisefloor

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020