Skip to content Show Fungsi utama python. adalah titik awal dari program apa pun. Ketika program dijalankan, interpreter Python menjalankan kode secara berurutan. Fungsi utama hanya dijalankan ketika dijalankan sebagai program Python. Ini tidak akan menjalankan fungsi utama jika diimpor sebagai modul. Apa fungsi utama DEF () dalam python? Untuk memahami ini, pertimbangkan kode contoh berikut Di sini, kami mendapat dua potong cetak – satu didefinisikan dalam fungsi utama yaitu “Hello World!” Dan yang lainnya independen, yaitu “CodeWithAden”. Ketika Anda menjalankan fungsi Def Main ():
Itu karena kami tidak menyatakan panggilan Fungsi “if__name __ ==” __main__ “. Adalah penting bahwa setelah mendefinisikan fungsi utama, Anda memanggil kode dengan if__name __ == “__main__” dan kemudian jalankan kode, hanya dengan kemudian Anda akan mendapatkan output “Hello World!” di konsol pemrograman. Pertimbangkan kode berikut def main () Contoh 2def main(): print("Hello World!") if __name__ == "__main__": main() print("CodeWithAden")CodeWithAden dicetak dalam kasus ini. Ini penjelasannya,
Modul variabel __name__ dan pythonUntuk memahami pentingnya __name__ variabel dalam metode fungsi utama Python, pertimbangkan kode berikut: def main(): print("hello world!") if __name__ == "__main__": main() print("CodeWithAden") print("Value in built variable name is: ",__name__)Sekarang pertimbangkan, kode diimpor sebagai modul import MainFunction print("done")Di sini, apakah penjelasan kode: Seperti C, Python menggunakan == untuk perbandingan sementara = untuk penugasan. Interpreter Python menggunakan fungsi utama dalam dua cara Jalankan langsung:
Impor sebagai modul
Ketika kode dijalankan, itu akan memeriksa nama modul dengan “jika.” Mekanisme ini memastikan, fungsi utama dijalankan hanya sebagai jalan langsung bukan bila diimpor sebagai modul. Contoh di atas adalah kode Python 3, jika Anda ingin menggunakan Python 2, silakan pertimbangkan kode berikut def main(): print "Hello World!" if __name__== "__main__": main() print "CodeWithAden"Di Python 3, Anda tidak perlu menggunakan if__name. Kode berikut juga berfungsi def main(): print("Hello World!") main() print("CodeWithAden")Catatan: Pastikan setelah mendefinisikan fungsi utama, Anda meninggalkan beberapa indentasi dan tidak mendeklarasikan kode tepat di bawah fungsi DEF (): jika tidak, itu akan memberikan kesalahan indentasi. Artikel ini berasal dari website Guru99, dan kemudian diterjemahkan ke bahasa indonesia, baca artikel asli disini
FUNGSI UTAMA PYTHON adalah titik awal dari setiap program. Ketika program dijalankan, interpreter python menjalankan kode secara berurutan. Fungsi utama dijalankan hanya ketika dijalankan sebagai program Python. Itu tidak akan menjalankan fungsi utama jika diimpor sebagai modul. Untuk memahami ini, perhatikan kode berikut: [ Di sini, kami mendapat dua bagian cetakan- satu didefinisikan dalam fungsi utama yaitu Hello World dan yang lainnya independen, yaitu Guru99. Saat Anda menjalankan fungsi def main (): harga axie slp hari ini
Itu karena kami tidak mendeklarasikan panggilan fungsi 'if__name__== utama . Penting bahwa setelah mendefinisikan fungsi utama, Anda memanggil kode dengan if__name__== utama dan kemudian jalankan kodenya, barulah Anda akan mendapatkan output hello world! di konsol pemrograman. Perhatikan kode berikut def main(): print('hello world!') if __name__ == '__main__': main() print('Guru99')Guru99 dicetak dalam kasus ini. [ Berikut penjelasannya,
NS nama variabel dan Modul PythonUntuk memahami pentingnya nama variabel, perhatikan kode berikut: tutorial fungsi cloud firebasedef main(): print('hello world!') if __name__ == '__main__': main() print('Guru99') print('Value in built variable name is: ',__name__) [ Sekarang pertimbangkan, kode diimpor sebagai modul import MainFunction print('done')[ Berikut penjelasan kodenya : vs kode tema gelap Seperti C, Python menggunakan == untuk perbandingan while = untuk penugasan. Interpreter Python menggunakan fungsi utama dalam dua cara lari langsung:
impor sebagai modul
Ketika kode dieksekusi, ia akan memeriksa nama modul dengan if. Mekanisme ini memastikan, fungsi utama dijalankan hanya sebagai direct run bukan saat diimpor sebagai modul. Contoh di atas adalah kode Python 3, jika Anda ingin menggunakan Python 2, pertimbangkan kode berikut: def main(): print 'Hello World!' if __name__== '__main__': main() print 'Guru99'Di Python 3, Anda tidak perlu menggunakan if__name. Kode berikut juga berfungsi contoh kode python sederhanadef main(): print('Hello World!') main() print('Guru99') Catatan: Pastikan bahwa setelah mendefinisikan fungsi utama, Anda meninggalkan beberapa indentasi dan tidak mendeklarasikan kode tepat di bawah fungsi def main(): jika tidak, itu akan memberikan kesalahan indentasi. #python #pengembangan web
If you are a beginner, probably the only answer you need right now is that this code is unnecessary for a simple script. It is only useful if you want to be able to import your script (or unpickle etc; see the other answers here for some other non-beginner scenarios). In slightly different words, the if __name__ guard is a mechanism for hiding code from other code. If you don't have a specific reason to hide something, don't: If you don't need to hide some code from import, don't put it behind this guard, and if you do, hide as little as possible. In slightly more detail, let's say you have a simple script fib.py (adapted from this answer): Now, if you simply run python fib.py it works fine. But __name__ will always be "__main__" in this scenario, so the condition is actually unnecessary. The script could be simplified to just n = int(input('Write a number: ')) a, b = 0, 1 while b < n: a, b = b, a+b print('Fibonacci number %i: %i' % (n, b))Now, you can't import fib with the new version, but if you didn't plan to do that in the first place, this version is actually better, because it's simpler and clearer. If you do want to be able to import fib, the first version is useless, too, because the useful code is in a section which will not run when you import this file (in which case __name__ will not be "__main__"). The proper design in that case would be to refactor the code so that the useful parts are in a function you can run when you want to after you have imported it. def main(): n = int(input('Write a number: ')) a, b = 0, 1 while b < n: a, b = b, a+b print('Fibonacci number %i: %i' % (n, b)) if __name__ == "__main__": main()Now, if you import fib, the call to main() will not be executed; but when you run python fib.py, it will. Actually, a better design still would be to isolate the reusable part (the actual calculation) from the user-visible input/output: def fibn(n: int) -> int: a, b = 0, 1 while b < n: a, b = b, a+b return b def main() -> None: n = int(input('Write a number: ')) print('Fibonacci number %i: %i' % (n, fibn(n))) if __name__ == "__main__": main()Now, you can from fib import fibn and call the fibn() function from the code which performs this import. (I called the function fibn() just to make it clearer what is what in this example. In real life, you might call it fib() and do from fib import fib.) Similarly, you could import and call the main function if you wanted to reuse it. Returning to the code in the question, I would similarly move the code from the if into a function as well, so that callers can invoke that function if they want to. def main(): lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock)) if __name__ == "__main__": main()This changes the scope of the lock variable; if the surrounding code needs access to it, you will need to make it global (or, perhaps, better, refactor main to return lock, and have the caller capture the value in a local variable of its own). (Unlike in languages like C, the name main has no specific meaning to Python; but it's a common convention to use it as the name of the thing which will be run. You still have to actually explicitly call it, like main(), unlike in C.) Page 2
Suppose I wrote functions and classes for web scraping on Wikipedia. Of course, this may not be a good example. I want to use those functions in another program without rewriting it. Well, I import them, but at the end of that file I put __name__ == '__main__' When we import a module, all the code inside it is executed from start to end. But when it reaches the condition, it does not run func, func2, etc., which is the Wikipedia __scrape__. Well, in the global scope a Python __name__ is defined to '__main__' for the current program. When we import a module, it is defined as a variable in the name space of our current program and current program __name__ is '__main__': File test.pydef func(): # Do something pass def func2(): # Do something pass print('The program name is set to ', globals()['__name__']) if __name__=='__main__': # In the current program, __name__ is equal to '__main__' func('https://www.wikipedia.org') func2('https://www.wikipedia.org') # Or do more jobs import test1 print('inside of current program') print('name is current program', __name__) print(globals()['test1']) test1.func('another site') test1.func2('another site')Outputinside of test 1 name of program is set to test1 end of module inside of current __main__ <module 'test1' from 'C:\\users\\ir\\appdata\\local\\programs\\python\\python38\\lib\\test1.py'> |