Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
new to coding
#1
Hi, I am doing a basic exercise in python were I have to call the function with a string as the value for the argument mystring and will return the length of that string. If an integer is passed as an input, the function should output a message like "Sorry, integers don't have length".

Here is my code:
def string_length(mystring): string = len(mystring) return string mystring = input("Enter a String: ") if (mystring) == int: print("Sorry, integers don't have length!") else: print(string_length(mystring))
Here is one output when inputting a string:

Output:
Enter a String: hello 5
Here is another output when inputting an integer:

Output:
Enter a String: 100 3
Second output should be expecting to print "Sorry, integers don't have length!"

Hope you can help me with my concern.

Thank you.
Reply
#2
Several things:

- input() always returns string
- even if you have integer, this comparison doesn't work as you expect:

>>> 3 == int False
- your function doesn't output message as required in description
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Thank you for the response.
Reply
#4
The string method isdigit should do the trick here
>>> 'string'.isdigit() False >>> '12321'.isdigit() True
Recommended Tutorials:
Reply


User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.