<!DOCTYPE html>
    <html lang="vi" xmlns="http://www.w3.org/1999/xhtml" prefix="og: http://ogp.me/ns#">
    <head>
<title>Từ khóa global trong Python</title>
<meta name="description" content="Từ khóa global trong Python - Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;tu-khoa-global-trong-python-10295.html">
<meta name="author" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :.">
<meta name="copyright" content=".: Nguoicodonvn2008.info - Cõi lòng người cô đơn :. [admin@nguoicodonvn2008.info]">
<meta name="robots" content="index, archive, follow, noodp">
<meta name="googlebot" content="index,archive,follow,noodp">
<meta name="msnbot" content="all,index,follow">
<meta name="generator" content="NukeViet v4.5">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta property="og:title" content="Từ khóa global trong Python">
<meta property="og:type" content="website">
<meta property="og:description" content="Savefile - Tin Tức - https&#x3A;&#x002F;&#x002F;www.nguoicodonvn2008.info&#x002F;vi&#x002F;news&#x002F;savefile&#x002F;kien-thuc-may-tinh&#x002F;tu-khoa-global-trong-python-10295.html">
<meta property="og:site_name" content=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.">
<meta property="og:url" content="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/tu-khoa-global-trong-python-10295.html">
<link rel="shortcut icon" href="https://www.nguoicodonvn2008.info/favicon.ico">
<link rel="canonical" href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/tu-khoa-global-trong-python-10295.html">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/" title="Tin Tức" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/karaoke-dual/" title="Tin Tức - Karaoke Dual" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nhac-tre/" title="Tin Tức - Nhạc trẻ" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tru-tinh/" title="Tin Tức - Trữ tình" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/nuoc-ngoai/" title="Tin Tức - Nước ngoài" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/remix/" title="Tin Tức - Remix" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tam-su-tinh-yeu/" title="Tin Tức - Tâm sự tình yêu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tho-suu-tam/" title="Tin Tức - Thơ sưu tầm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/cuoc-song/" title="Tin Tức - Cuộc sống" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/phan-mem/" title="Tin Tức - Phần mềm" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/kien-thuc-may-tinh/" title="Tin Tức - Kiến thức máy tính" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/hoc-tap/" title="Tin Tức - Học tập" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/tai-lieu/" title="Tin Tức - Tài liệu" type="application/rss+xml">
<link rel="alternate" href="https://www.nguoicodonvn2008.info/vi/news/rss/de-thi/" title="Tin Tức - Đề thi" type="application/rss+xml">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css" type="text/css">
<link rel="preload" as="style" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css" type="text/css">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/language/vi.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/global.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/assets/js/site.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/news.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/main.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/custom.js" type="text/javascript">
<link rel="preload" as="script" href="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js" type="text/javascript">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/assets/css/font-awesome.min.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/bootstrap.non-responsive.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/style.non-responsive.css">
<link rel="StyleSheet" href="https://www.nguoicodonvn2008.info/themes/default/css/news.css">
<link rel="stylesheet" href="https://www.nguoicodonvn2008.info/themes/default/css/custom.css">
<style type="text/css">
	body{background: #fff;}
</style>
    </head>
    <body>
<div id="print">
	<div id="hd_print">
		<h2 class="pull-left">.&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.</h2>
		<p class="pull-right"><a title=".&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;." href="https://www.nguoicodonvn2008.info/">https://www.nguoicodonvn2008.info</a></p>
	</div>
	<div class="clear"></div>
	<hr />
	<div id="content">
		<h1>Từ khóa global trong Python</h1>
		<ul class="list-inline">
			<li>Thứ bảy - 03/05/2025 00:59</li>
			<li class="hidden-print txtrequired"><em class="fa fa-print">&nbsp;</em><a title="In ra" href="javascript:;" onclick="window.print()">In ra</a></li>
			<li class="hidden-print txtrequired"><em class="fa fa-power-off">&nbsp;</em><a title="Đóng cửa sổ này" href="javascript:;" onclick="window.close()">Đóng cửa sổ này</a></li>
		</ul>
		<div class="clear"></div>
		<div id="hometext">
		</div>
		<div id="bodytext" class="clearfix">
			<p><strong>Global trong Python là gì?&nbsp;</strong>Bài viết sẽ cho bạn biết mọi điều về<strong>&nbsp;cách dùng global Python</strong>.</p>
<br />
<br />
Advertisement
<p>Khi mã hóa hay lập trình bằng Python, bạn có thể gặp phải những tình huống cần hạn chế khả năng truy cập của một biến vào một khối mã cụ thể. Điều này đạt được bằng cách giới hạn phạm vi của biến. Python cung cấp hai loại phạm vi: Phạm vi cục bộ và Phạm vi toàn cục, mỗi loại xác định nơi các biến có thể nhìn thấy và truy cập được. Đây là lúc từ khóa Global xuất hiện.</p>

<p>Trong bài viết này, chúng ta sẽ đề cập đến khái niệm từ khóa Global trong Python cùng với một số ví dụ.</p>

<p>Biến toàn cục hay global trong Python cho phép một hàm sửa đổi các biến được định nghĩa bên ngoài phạm vi của nó, khiến chúng có thể truy cập được trên toàn cục. Nếu không có nó, các biến bên trong một hàm được coi là cục bộ theo mặc định. Nó thường được sử dụng khi chúng ta cần cập nhật giá trị của một biến toàn cục trong một hàm, đảm bảo các thay đổi vẫn tồn tại bên ngoài hàm.</p>

<h2>Quy tắc của từ khóa global trong Python</h2>

<ul>
	<li>Khi chúng ta tạo biến trong một hàm, nó mặc định là biến cục bộ.</li>
	<li>Khi chúng ta định nghĩa một biến bên ngoài hàm, nó mặc định là biến toàn cục. Bạn không cần phải sử dụng từ khóa global.</li>
	<li>Chúng ta sử dụng từ khóa&nbsp;<code>global</code>&nbsp;để đọc và viết biến toàn cục trong một hàm.</li>
	<li>Sử dụng từ khóa&nbsp;<code>global</code>&nbsp;bên ngoài một hàm thì không có tác dụng gì cả.</li>
</ul>

<h2>Cách sử dụng từ khóa global trong Python</h2>

<h3><strong>Ví dụ 1: Truy cập biến toàn cục từ trong một hàm</strong></h3>

<pre id="pre0">
a = 1 # Biến toàn cục

def them():
    print(a)

them()</pre>

<p>Khi chạy code trên chúng ta nhận được đầu ra là 1. Tuy nhiên, có vài trường hợp chúng ta cần chỉnh sửa biến toàn cục từ bên trong hàm, đó chính là trường hợp mình nhắc đến từ đầu, vậy phải làm sao?</p>
<iframe allow="autoplay" allowtransparency="true" aria-label="Advertisement" data-google-container-id="a!2" data-google-query-id="CLHYt4TCho0DFUyI6QUdouoM7g" data-load-complete="true" frameborder="0" height="280" hspace="0" id="aswift_1" marginheight="0" marginwidth="0" name="aswift_1" sandbox="allow-scripts allow-same-origin allow-forms allow-presentation allow-popups" scrolling="no" tabindex="0" title="Advertisement" vspace="0" width="694"></iframe>

<h3><strong>Ví dụ 2: Chỉnh sửa biến toàn cục trong một hàm</strong></h3>

<p>Giả sử ta cần sửa giá trị của a thành a + 9 trong hàm&nbsp;<code>them()</code>, nếu viết code sau:</p>

<pre id="pre1">
a = 1 # Biến toàn cục

def them():
    a = a + 9    
    print(a)

them()</pre>

<p>Bạn sẽ nhận được thông báo lỗi:</p>

<pre id="pre2">
<code>UnboundLocalError: local variable &#039;a&#039; referenced before assignment</code></pre>

<p>Đó là do chúng ta chỉ có thể truy cập vào biến toàn cục mà không thể chỉnh sửa nó trong một hàm. Giải pháp cho vấn đề này là sử dụng từ khóa&nbsp;<code>global</code>. Khi đó, đoạn code trên sẽ được viết lại như sau:</p>

<pre id="pre3">
a = 1 # Biến toàn cục

def them():
    global a 
    a = a + 9 
    print(&quot;Trong them():&quot;, a)

them()
print(&quot;Trong main:&quot;, a)</pre>

<p>Chạy code trên ta được kết quả đầu ra là:</p>

<pre id="pre4">
<code>Trong them(): 10
Trong main: 10 </code></pre>

<p>Ở đây, chúng ta định nghĩa a là một biến toàn cục trong hàm&nbsp;<code>them()</code>, sau đó tăng giá trị của&nbsp;<code>a</code>&nbsp;lên 9, tức là&nbsp;<code>a = a + 9</code>. Sau đó, chúng ta gọi hàm<code>&nbsp;them()</code>, cuối cùng, in biến toàn cục&nbsp;<code>a</code>. Kết quả là thay đổi được thực hiện cho biến a trong hàm&nbsp;<code>them()</code>&nbsp;cũng xảy ra trên biến toàn cục bên ngoài hàm, a = 10.</p>

<h3><strong>Ví dụ 3: Chia sẻ biến toàn cục global thông qua mô-đun trong Python</strong></h3>

<p>Trong Python, chúng ta tạo ra một mô-dun config.py để giữ các biến toàn cục và chia sẻ thông tin thông qua các mô-đun Python trong cùng một chương trình. Đây là cách chúng ta có thể chia sẻ biến toàn cục qua các mô-đun Python.</p>

<p>Tạo một file&nbsp;<strong>config.py</strong>&nbsp;để lưu trữ biến toàn cục:</p>

<pre id="pre5">
a = 0
b = &quot;rỗng&quot;</pre>

<p>Tạo một file&nbsp;<strong>update.py</strong>&nbsp;để thay đổi các biến toàn cục:</p>

<pre id="pre6">
import config

config.a = 10
config.b = &quot;Quantrimang.com&quot;</pre>

<p>Viết file&nbsp;<strong>main.py</strong>&nbsp;để kiểm tra sự thay đổi:</p>

<pre id="pre7">
import config
import update

print(config.a)
print(config.b)</pre>

<p>Khi chạy file&nbsp;<strong>main.py</strong>, đầu ra sẽ là:</p>

<pre id="pre8">
<code>10
Quantrimang.com </code></pre>

<p>Ở đây, ta đã tạo ra 3 file là config.py, update.py và main.py. Mô-đun config.py lưu trữ 2 biến toàn cục là&nbsp;<code>a</code>&nbsp;và&nbsp;<code>b</code>. Trong file update.py chúng ta nhập mô-đun config.py và sửa đổi giá trị của biến&nbsp;<code>a, b</code>. Tương tự trong file main.py, ta nhập cả 2 mô-đun config.py và update.py. Cuối cùng, chúng ta dùng lệnh in để kiểm tra xem giá trị của biến a và b đã được thay đổi hay chưa.</p>
<iframe allow="autoplay" allowtransparency="true" aria-label="Advertisement" data-google-container-id="a!3" data-google-query-id="CKnO54TCho0DFeeH6QUdEA09lg" data-load-complete="true" frameborder="0" height="280" hspace="0" id="aswift_2" marginheight="0" marginwidth="0" name="aswift_2" sandbox="allow-scripts allow-same-origin allow-forms allow-presentation allow-popups" scrolling="no" tabindex="0" title="Advertisement" vspace="0" width="694"></iframe>

<h3><strong>Ví dụ 4: Sử dụng biến toàn cục trong hàm lồng nhau</strong></h3>

<p>Trong ví dụ này bạn sẽ biết cách để sử dụng biến toàn cục trong hàm lồng nhau.</p>

<pre id="pre9">
def ham1():
    x = 20

    def ham2():
       global x
       x = 25
    print(&quot;Trước khi gọi ham2: &quot;, x)
    print(&quot;Đang gọi ham2&quot;)
    ham2()
    print(&quot;Sau khi gọi ham2: &quot;, x)

ham1()
print(&quot;x trong main: &quot;, x)</pre>

<p>Chạy code trên ta được:</p>

<pre id="pre10">
<code>Trước khi gọi ham2: 20
Đang gọi ham2
Sau khi gọi ham2: 20
x trong main: 25</code></pre>

<p>Ở đây, chúng ta khai báo biến toàn cục trong hàm lồng&nbsp;<code>ham2()</code>. Trong&nbsp;<code>ham1()</code>,&nbsp;<code>x</code>&nbsp;không bị ảnh hưởng bởi từ khóa&nbsp;<code>global</code>.</p>

<p>Trước và sau khi gọi hàm&nbsp;<code>ham2()</code>,&nbsp;<code>x</code>&nbsp;sẽ lấy giá trị của biến cục bộ là&nbsp;<code>20</code>. Bên ngoài hàm&nbsp;<code>ham1(), x</code>&nbsp;sẽ lấy giá trị toàn cục, được khia báo trong&nbsp;<code>ham2()</code>&nbsp;là&nbsp;<code>25</code>. Đây là do ta sử dụng từ khóa&nbsp;<code>global</code>&nbsp;trong&nbsp;<code>x</code>&nbsp;để tạo biến toàn cục trong&nbsp;<code>ham2()</code>. Nếu chúng ta thực hiện bất kỳ sự thay đổi nào cho&nbsp;<code>x</code>&nbsp;trong&nbsp;<code>ham2()</code>&nbsp;thì thay đổi sẽ xuất hiện bên ngoài phạm vi cục bộ.</p>

<p>Làm&nbsp;<a href="https://quantrimang.com/hoc/hon-100-bai-tap-python-co-loi-giai-code-mau-142456" title="Hơn 100 bài tập Python có lời giải (code mẫu)">bài tập Python có giải</a>&nbsp;để rèn luyện thêm bạn nhé.</p>
		</div>
				<div id="author">
						<p>
				<strong>Tác giả:</strong>
				<a href="https://www.nguoicodonvn2008.info/vi/news/author/admin/">admin</a>
			</p>
		</div>
	</div>
	<div id="footer" class="clearfix">
		<div id="url">
			<strong>URL của bản tin này: </strong><a href="https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/tu-khoa-global-trong-python-10295.html" title="Từ khóa global trong Python">https://www.nguoicodonvn2008.info/vi/news/savefile/kien-thuc-may-tinh/tu-khoa-global-trong-python-10295.html</a>

		</div>
		<div class="clear"></div>
		<div class="copyright">
			&copy; .&#x3A; Nguoicodonvn2008.info - Cõi lòng người cô đơn &#x3A;.
		</div>
		<div id="contact">
			<a href="mailto:admin@nguoicodonvn2008.info">admin@nguoicodonvn2008.info</a>
		</div>
	</div>
</div>
        <div id="timeoutsess" class="chromeframe">
            Bạn đã không sử dụng Site, <a onclick="timeoutsesscancel();" href="https://www.nguoicodonvn2008.info/#">Bấm vào đây để duy trì trạng thái đăng nhập</a>. Thời gian chờ: <span id="secField"> 60 </span> giây
        </div>
        <div id="openidResult" class="nv-alert" style="display:none"></div>
        <div id="openidBt" data-result="" data-redirect=""></div>
		</script>
		<div class="car-top">
  <span><img src="https://www.nguoicodonvn2008.info/themes/default/images/car.png" alt=""></span>
</div>
<script src="https://www.nguoicodonvn2008.info/assets/js/jquery/jquery.min.js"></script>
<script>var nv_base_siteurl="/",nv_lang_data="vi",nv_lang_interface="vi",nv_name_variable="nv",nv_fc_variable="op",nv_lang_variable="language",nv_module_name="news",nv_func_name="savefile",nv_is_user=0, nv_my_ofs=-4,nv_my_abbr="EDT",nv_cookie_prefix="nv4c_e856T",nv_check_pass_mstime=1738000,nv_area_admin=0,nv_safemode=0,theme_responsive=0,nv_recaptcha_ver=2,nv_recaptcha_sitekey="",nv_recaptcha_type="image",XSSsanitize=1;</script>
<script src="https://www.nguoicodonvn2008.info/assets/js/language/vi.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/DOMPurify/purify3.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/global.js"></script>
<script src="https://www.nguoicodonvn2008.info/assets/js/site.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/news.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/main.js"></script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/custom.js"></script>
<script type="application/ld+json">
        {
            "@context": "https://schema.org",
            "@type": "Organization",
            "url": "https://www.nguoicodonvn2008.info",
            "logo": "https://www.nguoicodonvn2008.info/uploads/angel.gif"
        }
        </script>
<script src="https://www.nguoicodonvn2008.info/themes/default/js/bootstrap.min.js"></script>
<script type="text/javascript">
var $scrolltop = $('.car-top');
$scrolltop.on('click', function () {
    $('html,body').animate({
        scrollTop: 0
    }, 800);
    $(this).addClass("car-run");
    setTimeout(function(){ $scrolltop.removeClass('car-run');}, 1000);
    return false;
});
$(window).on('scroll', function ()
{ 
    if($(window).scrollTop() >= 200)
    {
        $scrolltop.addClass("show");
        $scrolltop.addClass("car-down");
    }
    else
    {
       $scrolltop.removeClass("show");
       setTimeout(function(){ $scrolltop.removeClass('car-down');}, 300);
    }
});
</script>
</body>
</html>