📜  Python作为关键字

📅  最后修改于: 2022-05-13 01:54:24.431000             🧑  作者: Mango

Python作为关键字

在本文中,我们将看到“as”关键字。关键字“as”用于在Python创建别名。

'as' 关键字的优点:

  • 在我们不能使用赋值运算符的情况下很有用,例如在导入模块中。
  • 它使代码更容易被人类理解。
  • as 关键字用于为程序员选择的名称创建别名,它减少了模块名称与变量名称重合的机会。

演示“as”关键字的工作概念:

示例 1:为模块创建别名

关键字“as”总是在它作为别名的资源之后。 'as' 关键字与 import 语句一起使用,为它的资源分配一个别名:

Python3
# Python code to demonstrait
# 'as' keyword
  
# Import ramdom module with alias
import random as geek
  
# Function showing working of as keyword
def Geek_Func():
  
    # Using random module with alias
    geek_RandomNumber = geek.randint(5, 10)
    geek_RandomNumber2 = geek.randint(1, 5)
  
    # Printing our number
    print(geek_RandomNumber)
    print(geek_RandomNumber2)
  
  
Geek_Func()


Python3
# Python code to demonstrait
# 'as' keyword
  
def geek_Func():
    
    # With statement with geek alias
    with open('sample.txt') as geek:
        
        # reading text with aias
        geek_read = geek.read()
  
    # Printing our text
    print("Text read with alias:")
    print(geek_read)
  
  
geek_Func()


Python3
# Python code to demonstrait
# 'as' keyword
  
# Using alias with try statement
try:
    import maths as mt
except ImportError as err:
    print(err)
  
# Function showing alias functioning
  
def geek_Func():
    try:
        
        # With statement with geek alias
        with open('geek.txt') as geek:
            
            # reading text with aias
            geek_read = geek.read()
  
        # Printing our text
        print("Reading alias:")
        print(geek_read)
    except FileNotFoundError as err2:
        print('No file found')
  
  
geek_Func()


输出:



9
1

示例 2:与文件一样

关键字“as”由带有 open 语句的 用于为其资源创建别名。在 sample.txt 文件中有文本“Hello Geeks For Geeks”。

蟒蛇3

# Python code to demonstrait
# 'as' keyword
  
def geek_Func():
    
    # With statement with geek alias
    with open('sample.txt') as geek:
        
        # reading text with aias
        geek_read = geek.read()
  
    # Printing our text
    print("Text read with alias:")
    print(geek_read)
  
  
geek_Func()

输出:

Text read with alias:
Hello Geeks For Geeks

示例 3:如Except 子句

在这里,我们将使用 as in except 子句和 try。

蟒蛇3

# Python code to demonstrait
# 'as' keyword
  
# Using alias with try statement
try:
    import maths as mt
except ImportError as err:
    print(err)
  
# Function showing alias functioning
  
def geek_Func():
    try:
        
        # With statement with geek alias
        with open('geek.txt') as geek:
            
            # reading text with aias
            geek_read = geek.read()
  
        # Printing our text
        print("Reading alias:")
        print(geek_read)
    except FileNotFoundError as err2:
        print('No file found')
  
  
geek_Func()

输出:

No module named 'maths'
No file found