So this is my code, I am a beginner not sure what I did wrong.
CodePudding user response:
Maybe unrelated to your problem, but you do not need to put break statements after a return statement, the return will immediately exit the method. Also from your code I can't see where you are checking to see what the method returns. I see that you are calling the method with x(input1, input2)
, but if you are not setting that equal to something and printing out its contents you will not be able to see the result.
You could do print(x(input1, input2))
to see the result.
CodePudding user response:
If your goal is to compare two strings "input1" and "input2", this piece of code is sufficient:
def compar_strings(string1, string2):
if len(string1) > len(string2):
print("First string is longer")
elif len(string1) == len(string2):
print("Both strings have the same length")
else:
print("Second string is longer")
Regarding your initial function, several points:
- Your first loop is actually looping on each character composing "input1" which does not seem relevant here. If you are not sure your inputs are strings (which should not happens if your are using
input
function) you can just doinput1.isdigit()
- Same applies for second loop
- At the end, you are using
return
followed by a string. Hence the function will return the string, not display it. If you want to display it, either useprint
in the function, or doy = x(input1, input2)
ad thenprint(y)
- The
break
statement is useless after areturn
because function will already have exited at this point
CodePudding user response:
def bigger(word1, word2):
w1 = isinstance(word1, str)
w2 = isinstance(word2, str)
if w1 & w2:
if len(word1)>len(word2):
ans = word1
elif len(word1)<len(word2):
ans = word2
else:
ans = 'The size of two words are equal.'
else:
if w1:
ans = 'The second input is not a string.'
elif w2:
ans = 'The first input is not a string.'
else:
ans = 'The two inputs are not strings.'
return ans
bigger('wrd1', 'word2')