Python Forum
Where is "switch" statement ? Do nobody needs it ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Where is "switch" statement ? Do nobody needs it ?
#11
with and as should be used on every file operations with built-in open(). In fact it is preferred to do this

with open('output.txt', 'w') as f:
    f.write('Hi there!')
rather than the old

f = open('output.txt', 'w')
f.write('Hi there!')
f.close()
because people forget to close the file as well as you can do multiple files such as
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
So with and as are used quite often.

Quote:I really often use it. Maybe as often, as if-else construction...
When would you determine you need a switch over if/else or python dictionary method?

The Zen of Python
Quote:Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

You can fine more info on their reasoning to switch statement
switch statement
https://www.python.org/dev/peps/pep-3103/
Recommended Tutorials:
Reply
#12
Thanks =)
Reply
#13
I'm still not sure why you're using a switch, though.  Even in javascript, it's horribly underpowered.  If it was a language like haskell or rust, sure go nuts (rust calls it match instead of switch), as those languages use pattern matching, making it much more useful.

For example, if you wanted to convert something like this to a switch...
choice = int(input("give me a number!  "))

if choice >=0 and choice < 10:
    print("0-9")
elif choice > 0:
    print(">= 10")
else:
    print("negative")
...the switch would look like this:
choice = int(input("number?  "))

switch choice:
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:
    case 9:
        print("0-9")
        break
    default:
        if choice < 0:
            print("negative")
        else:
            print(">= 10")
        break
With pattern matching, which javascript doesn't support, it'd be simple:
choice = int(input("number: "))

match choice:
    range(0, 10) => lambda num: print("0-9"),
    lambda num: num > 0 => lambda num: print(">= 10"),
    _ => lambda num: print("< 0")
Reply
#14
It seems to me the cleanest and easiest method is a dictionary with function or method addresses that
can be executed directly from the key:
dictname[key]()
Reply
#15
I think the dict->function approach is fine for this, but it still misses the pattern matching aspect.  Check out this snippet from the Rust docs: https://rustbyexample.com/flow_control/match.html

fn main() {
    let number = 13;
    // TODO ^ Try different values for `number`

    println!("Tell me about {}", number);
    match number {
        // Match a single value
        1 => println!("One!"),
        // Match several values
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // Match an inclusive range
        13...19 => println!("A teen"),
        // Handle the rest of cases
        _ => println!("Ain't special"),
    }

    let boolean = true;
    // Match is an expression too
    let binary = match boolean {
        // The arms of a match must cover all the possible values
        false => 0,
        true => 1,
        // TODO ^ Try commenting out one of these arms
    };

    println!("{} -> {}", boolean, binary);
}
Reply
#16
Off subject, but:
let number = 13;
reminds me of Dartmouth Basic
but I see your point
Reply
#17
Javascript also uses let, lol. 

With newer versions, every variable should be either let, or const.  var should almost never be used for new code.
Reply
#18
@nilamo, seems, that's the same like in Coffeescript.
From reference:
switch day
  when "Mon" then go work
  when "Tue" then go relax
  when "Thu" then go iceFishing
  when "Fri", "Sat"
    if day is bingoDay
      go bingo
      go dancing
  when "Sun" then go church
  else go work
How I used it:
		switch current_json.message
			when "receive_and_answer_secret_question"
				do gatekeeper.ask___secret_question
			when "login_successful"
				alert "Login successfull.
					\nAsking main menu page"
				document.location = "/main_menu/main_menu_page/"
			when "login_failed"
				alert "Login failed.
					\nPlease, check username and password."
How I used it too:
	switch document.location.host
		when "vk.com"
			switch document.location.pathname
				when "/"
					report_to_server = "login_page_general without_anything_other"
				when "/login"
					if document.location.search.includes "act=mobile"
						report_to_server = "login_page_general after_logging_out"
					else if document.location.search.includes "act=blocked"
						report_to_server = "login_page_general_error account_blocked"
					else
						report_to_server = "login_page_general with_login_after_slash"
				when "/restore"
					if document.location.search.includes "act=cancel"
						report_to_server = "login_page_general_error login_data_changed"
					else
						report_to_server = "error_page"
				when "/login.php"  # can be redirected to news or to login_error page
					setTimeout main_function, 5000
					return null
				when "/feed"
					report_to_server = "news_page"
				when "/blank.html"
					setTimeout main_function, 5000
					return null
				else
					report_to_server = "other_page"
		when "oauth.vk.com"
			switch document.location.pathname
				when "/authorize", "/oauth/authorize"
					if document.getElementsByClassName("oauth_app_photo").length > 0
						# earlier was: document.body.innerHTML.includes "запрашивает доступ к Вашему аккаунту"
						report_to_server = "api_app_rights_request_page"
					else if document.getElementsByClassName("oauth_captcha").length > 0
						report_to_server = "captcha_asked"
					else
						report_to_server = "login_page_api"
				else
					report_to_server = "other_page"
		when "api.vk.com"
			if (document.location.pathname == "/blank.html") and (document.location.hash.includes "access_token=")
				report_to_server = "api_logined_page"
			else
				report_to_server = "other_page"
		else
			report_to_server = "other_page"
It's even more often-used statement than "if" =)

Here I writed my thoughts about good syntax and how to implement it: https://github.com/vlad1777d/pythonscript
If somebody interested - you can tell your opinion about it.
Readme is not finished, especially, I had not written about "switch", but I will =)
I think, that "switch" and "if" must be the same like in Coffeescript, to be able to do so:
a = switch b
    when 4
        8 + 8
    when 8, 9, 10
         somevar

a = if b > 0
    4
else
    8
Reply


Forum Jump:

User Panel Messages

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