[Tutor] Valid Username Program
Aliyan Navaid
aliyan.navaid at gmail.com
Thu Oct 8 10:44:17 EDT 2020
Since i'm a beginner could you please give examples for the last part ?
where you list all the possible scenarios.
On Thu, Oct 8, 2020, 6:17 PM Alan Gauld via Tutor <tutor at python.org> wrote:
> On 08/10/2020 12:29, Aliyan Navaid wrote:
> > def valid_username(username):
> > if len(username) < 3:
> > print("Username must be atleast 3 characters long")
> > elif len(username) > 15:
> > print("Username is too long")
> > else:
> > print("Valid Username")
>
> > I wanted to ask that instead of elif, I could’ve written another If
> > statement in this program right ?
>
> Not quite. Consider the else part. How would you have written that?
> You would need a third if statement that checked the inverse of
> both the previous conditions:
>
> if 3 <= len(username) <= 15:
> print("Valid Username")
>
> So you have to decide if the extra comparison is better or worse
> than the elif structure. In this case it doesn't make much difference,
> but what if you had several elif statements your "else" test would need
> to incorporate all of those tests negated.
>
> Also you have to be very careful not to double-process values. You are
> OK in this example but it can get more complex. consider the following:
>
> size = int(input("size"))
> if size > 50: print("Too big")
> if size > 30: print("That's a big one!")
> if size > 20: print("Normal")
> if size > 10: print("That's small!")
> is size <= 10: print("Too small")
>
> Now what happens if size is 60?
> The first 4 tests all print!
> But if we used elifs instead then only the first condition
> would be triggered.
>
> > And can you please also explain that when to use elif statement and
> when
> > to use multiple if statements.
>
> You can use multiple if statements
> a) if the tests are completely independent(and will always stay that
> way) or
> b) if, in a case like the example above, you actually want multiple
> cases to trigger.
>
> But those are the exception rather than the rule, in most scenarios
> elif is the safer option.
>
> The third scenario to use multiple ifs is inside a function
> where each 'if' triggers a 'return' statement that will exit
> the function. In that case the subsequent 'if' is only
> reached if the predecessors were not triggered.
> That will only make sense if you have studied functions already.
> If not just ignore it for now!
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list