-2

newbie in coding. I Cant understand how this string works and why its only printing the last string letter instead of all of them.

The objective is to print all letters untill the first number in a string. if the string isdigit() == true, return print ("").

For example if i input like this: func("abc") I cant understand why it only prints "c" instead of "abc"

Thanks !

def func(s):

for i in s:
    if i.isdigit():
        print("")
        break 
else:
    print(i)
  • 1
    Python is a whitespace-sensitive language. Fix your indentation to properly include `else` at the same level as `if`. – esqew Nov 07 '19 at 14:24
  • Thank you it worked. can you please elaborate more with an example about what you said , that python is a whitespace-sensitive language. What should i know when i write the next codes ? and thanks again – Ron Golbstein Nov 07 '19 at 14:33
  • I've included a Stack Overflow link with more information in my answer below for your reference. – esqew Nov 07 '19 at 14:33

2 Answers2

0

Python is different than most programming languages in that it is whitespace-sensitive. Your indentations at the beginning of each line actually have a massive effect on how your script is interpreted and executed.

Since your if and else statements exist at different indentations, and thus different scopes, they aren't evaluated in the same context. Fix your indentations to properly include else in the same scope as if:

def func(s):
  for i in s:
    if i.isdigit():
        print("")
        break 
    else:
        print(i)

func('abc1d')

Returns:

a
b
c

Repl.it

esqew
  • 42,425
  • 27
  • 92
  • 132
0

The indentation levels do not match. Your "else" statement should be directly below your "if" statement.

for i in s:
if i.isdigit():
    print("")
    break 
else:
    print(i)