Module 3 - Python Statements, Comments, Keywords, and Variables PDF
Document Details
Uploaded by Deleted User
Isabela State University
Roman Alex F. Lustro
Tags
Related
- Lecture 2.1_ Variables, Statements, and Comments.pdf
- Fundamentals of Python: First Programs - Chapter 3 Control Statements PDF
- Python Tutorial PDF
- SDU CSS 115 Programming Fundamentals 1 (Python) Fall 2024 Practice 4 PDF
- Introduction to Programming in Python: Conditionals I PDF
- CS 1400 Final Exam PDF
Summary
This document is a module on Python programming. It discusses Python statements, comments, and keywords. The document also covers the creation of variables and their usage.
Full Transcript
Module 3 - Python Statements, Comments, Keywords, and Variables 1 Module 3 - Python Statements, Comments, Keywords, and Variables Learning Outcomes Understand Python statements Differentiate simple and compound statement...
Module 3 - Python Statements, Comments, Keywords, and Variables 1 Module 3 - Python Statements, Comments, Keywords, and Variables Learning Outcomes Understand Python statements Differentiate simple and compound statements. Apply comments in Python code Understand the importance of comments Differentiate inline comments, block comments, and multi-line comments Apply docstring comments. Understand what each keyword is used for using the help() function Create Variables 3.1 Python Statements A statement is an instruction that a Python interpreter can execute. So, in simple words, we can say anything written in Python is a statement. Python statement ends with the token NEWLINE character. It means each line in a Python script is a statement. 3.1.1 Multi-Line Statements Python statement ends with the token NEWLINE character. But we can extend the statement over multiple lines using line continuation character (\). This is known as an explicit continuation. Example addition = 10 + 20 + \ 30 + 40 + \ 50 + 60 + 70 print(addition) # Output: 280 3.1.1.2 Implicit continuation: We can use parentheses () to write a multi-line statement. We can add a line continuation statement inside it. Whatever we add inside a parentheses () will treat as a single statement even it is placed on multiple lines. Example: addition = (10 + 20 + 30 + 40 + 50 + 60 + 70) print(addition) # Output: 280 As you see, we have removed the line continuation character (\) if we are using the parentheses (). We can use square brackets [] to create a list. Then, if required, we can place each list item on a single line for better readability. Same as square brackets, we can use the curly { } to create a dictionary with every key-value pair on a new line for better readability. Example: # list of strings names = ['Emma', 'Kelly', 'Jessa'] print(names) # dictionary name as a key and mark as a value # string:int students = {'Emma': 70, 'Kelly': 65, 'Jessa': 75} print(students) INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 2 Output: ['Emma', 'Kelly', 'Jessa'] {'Emma': 70, 'Kelly': 65, 'Jessa': 75} 3.1.2 Compound Statements Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. The compound statement includes the conditional and loop statement. if statement: It is a control flow statement that will execute statements under it if the condition is true. Also known as a conditional statement. while statements: The while loop statement repeatedly executes a code block while a particular condition is true. Also known as a looping statement. for statement: Using for loop statement, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple. Also known as a looping statement. try statement: specifies exception handlers. with statement: Used to cleanup code for a group of statements, while the with statement allows the execution of initialization and finalization code around a block of code. 3.1.3 Simple Statements Apart from the declaration and calculation statements, Python has various simple statements for a specific purpose. 3.1.3.1 Expression statements. are used to compute and write a value. An expression statement evaluates the expression list and calculates the value. Example: x = 5 # right hand side of = is a expression statement # x = x + 10 is a complete statement x = x + 10 3.1.3.2 The pass statement pass is a null operation. Nothing happens when it executes. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed. For example, you created a function for future releases, so you don’t want to write a code now. In such cases, we can use a pass statement. Example: # create a function def fun1(arg): pass # a function that does nothing (yet) 3.1.3.3 The del statement The Python del statement is used to delete objects/variables. Syntax: del target_list The target_list contains the variable to delete separated by a comma. Once the variable is deleted, we can’t access it. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 3 3.1.3.4 The return statement We create a function in Python to perform a specific task. The function can return a value that is nothing but an output of function execution. Using a return statement, we can return a value from a function when called. Example: # Define a function # function acceptts two numbers and return their sum def addition(num1, num2): return num1 + num2 # return the sum of two numbers # result is the return value result = addition(10, 20) print(result) 3.1.3.5 The import statement The import statement is used to import modules. We can also import individual classes from a module. Python has a huge list of built-in modules which we can use in our code. For example, we can use the built- in module DateTime to work with date and time. Example: Import datetime module import datetime # get current datetime now = datetime.datetime.now() print(now) 3.1.3.6 The continue and break statement break Statement: The break statement is used inside the loop to exit out of the loop. continue Statement: The continue statement skip the current iteration and move to the next iteration. We use break, continue statements to alter the loop’s execution in a certain manner. Statement Description Terminate the current loop. Use the break statement to break come out of the loop instantly. Skip the current iteration of a loop and move to the next continue iteration Do nothing. Ignore the condition in which it occurred and pass proceed to run the program as usual INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 4 3.2 Python Comments The comments are descriptions that help programmers to understand the functionality of the program. Thus, comments are necessary while writing code in Python. In Python, we use the hash (#) symbol to start writing a comment. The comment begins with a hash sign (#) and whitespace character and continues to the end of the line. Example: x = 10 y = 20 # adding two numbers z = x + y print('Sum:', z) # Output 30 3.2.1 Single-line Comment single-line comments are indicated by a hash sign(#). The interpreter ignores anything written after the # sign, and it is effective till the end of the line. Example: Writing single-line Comments # welcome message print('Welcome to PYnative...') 3.2.2 Multi-Line Comments There is no separate way to write a multi-line comment. Instead, we need to use a hash sign at the beginning of each comment line to make it a multi-line comment. Example # This is a # multiline # comment print('Welcome to PYnative...') 3.2.3 Inline Comments An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Example: def calculate_bonus(salary): salary = salary * 7.5 # yearly bonus percentage 7.5 3.2.4 Block Comments Block comments are used to provide descriptions of files, classes, and functions. We should add block comments at the beginning of each file and before each method. Example: # Returns welcome message for a customer by customer name and location # param name - Name of the customer # param region - location # return - Welcome message def greet(name, region): message = get_message(region) return message + " " + name INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 5 3.2.5 Add Sensible Comments A comment must be short and straightforward, and sensible. A comment must add value to your code. You should add comments to give code overviews and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. Let’s take the following example. # Define list of student names names = ['Jess', 'Emma', 'Kelly'] # iterates over name list and prints each name for student in names: print(student, end=' ') As you can see, the code is self-explanatory, and adding comments for such code is unnecessary. It would be best if you avoided such scenarios. Now, let’s take the second example where we have demonstrated the correct way to write comments. # Returns welcome message for a customer by customer name and location # param name - Name of the customer # param region - location # return - Welcome message def greet(name, region): message = get_message(region) return message + " " + name # Returns welcome message by location # param region - location def get_message(region): if (region == 'USA'): return 'Hello' elif (region == 'India'): return 'Namaste' print(greet('Jessa', 'USA')) 3.2.6 Inline Comments We can add concise comments on the same line as the code they describe but should be shifted enough to separate them from the statements for better readability. It is also called a trailing comment. An inline comment is a comment on the same line as a statement. Inline comments should be separated by at least two spaces from the statement. They should start with a # and a single space. Inline comments are useful when you are using any formula or any want to explain the code line in short. If one or more lines contain the short comment, they should all be indented to the same tab setting. Example: def calculate_bonus(salary): salary = salary * 7.5 # yearly bonus percentage 7.5 3.2.7 Block Comments Block comments are used to provide descriptions of files, classes, and functions. We should add block comments at the beginning of each file and before each method. Add a black line after the block comment to set it apart from the rest of the code. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 6 Example: # Returns welcome message for a customer by customer name and location # param name - Name of the customer # param region - location # return - Welcome message def greet(name, region): message = get_message(region) return message + " " + name 3.2.8 Docstring Comments Docstring comments describe Python classes, functions, constructors, methods. The docstring comment should appear just after the declaration. Although not mandatory, this is highly recommended. Conventions for writing good documentation strings The docstring comment should appear just after the declaration. A docstring can be a single line or a multi-line comment. Docstring should begin with a capital letter and end with a period. Example: docstring in function def bonus(salary): """Calculate the bonus 10% of a salary.""" return salary * 10 / 100 3.2.9 Using String Literals for Multi-line Comments We can use multi-line strings (triple quotes) to write multi-line comments. The quotation character can either be ‘ or “. Python interpreter ignores the string literals that are not assigned to a variable. Example ''' I am a multiline comment! ''' print("Welcome to PYnative..") INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 7 3.3 Python Keywords Python keywords are reserved words that have a special meaning associated with them and can’t be used for anything but those specific purposes. Each keyword is designed to achieve specific functionality. Python keywords are case-sensitive. All keywords contain only letters (no special symbols) Except for three keywords (True, False, None), all keywords have lower case letters 3.3.1 Get the List of Keywords We can use the following two ways to get the list of keywords in Python keyword module: The keyword is the built-in module to get the list of keywords. Also, this module allows a Python program to determine if a string is a keyword. help() function: Apart from a keyword module, we can use the help() function to get the list of keywords Example: keyword module import keyword print(keyword.kwlist) Output ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] 3.3.2 How to Identify Python Keywords Keywords are mostly highlighted in IDE when you write a code. This will help you identify Python keywords while you’re writing a code so you don’t use them incorrectly. 3.3.3 Keyword Module Python keyword module allows a Python program to determine if a string is a keyword. iskeyword(s): Returns True if s is a keyword Example: import keyword print(keyword.iskeyword('if')) print(keyword.iskeyword('range')) Output: True False As you can see in the output, it returned True because ‘if’ is the keyword, and it returned False because the range is not a keyword (it is a built-in function). Also, keyword module provides following functions to identify keywords. keyword.kwlist: It return a sequence containing all the keywords defined for the interpreter. keyword.issoftkeyword(s): Return True if s is a Python soft keyword. keyword.softkwlist: Sequence containing all the soft keywords defined for the interpreter. 3.3.4 Types of Keywords All 36 keywords can be divided into the following seven categories. 3.3.4.1 Value Keywords: True, False, None. True and False are used to represent truth values, known as boolean values. It is used with a conditional statement to determine which block of code to execute. When executed, the condition evaluates to True or False. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 8 Example: x = 25 y = 20 z = x > y print(z) # True 3.3.4.2 Operator Keywords: and, or, not, in, is The logical and keyword returns True if both expressions are True. Otherwise, it will return. False. The logical or keyword returns a boolean True if one expression is true, and it returns False if both values are false. The logical not keyword returns boolean True if the expression is false. Example: x = 10 y = 20 # and to combine to conditions # both need to be true to execute if block if x > 5 and y < 25: print(x + 5) # or condition # at least 1 need to be true to execute if block if x > 5 or y < 100: print(x + 5) # not condition # condition must be false if not x: print(x + 5) Output: 15 15 The is keyword returns return True if the memory address first value is equal to the second value. Example: is keyword # is keyword demo x = 10 y = 11 z = 10 print(x is y) # it compare memory address of x and y print(x is z) # it compare memory address of x and z Output: False True The in keyword returns True if it finds a given object in the sequence (such as list, string). Example: in Keyword my_list = [11, 15, 21, 29, 50, 70] number = 15 if number in my_list: print("number is present") else: print("number is not present") INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 9 3.3.4.3 Conditional Keywords: if, elif, else Condition keywords act depending on whether a given condition is true or false. You can execute different blocks of codes depending on the outcome of a condition. Example: x = 75 if x > 100: print('x is greater than 100') elif x > 50: print('x is greater than 50 but less than 100') else: print('x is less than 50') 3.3.4.4 Iterative and Transfer Keywords: for, while, break, continue, else Iterative keywords allow us to execute a block of code repeatedly. We also call it a loop statements. while: The while loop repeatedly executes a code block while a particular condition is true. for: Using for loop, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple. Example: print('for loop to display first 5 numbers') for i in range(5): print(i, end=' ') print('while loop to display first 5 numbers') n = 0 while n < 5: print(n, end=' ') n = n + 1 Output: for loop to display first 5 numbers 0 1 2 3 4 while loop to display first 5 numbers 0 1 2 3 4 break, continue, and pass: Transfer statements are used to alter the program’s way of execution in a certain manner. 3.3.4.5 Structure Keywords: def, class, with, as, pass, lambda The def keyword is used to define user-defined function or methods of a class Example: def keyword # def keyword: create function def addition(num1, num2): print('Sum is', num1 + num2) # call function addition(10, 20) Output: Sum is 30 Jessa 19 The pass keyword is used to define as a placeholder when a statement is required syntactically. Example: pass keyword INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 10 # pass keyword: create syntactically empty function # code to add in future def sub(num1, num2): pass class keyword is used to define class in Python. Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects“. An object-oriented paradigm is to design the program using classes and objects Example: class keyword # create class class Student: def __init__(self, name, age): self.name = name self.age = age def show(self): print(self.name, self.age) # create object s = Student('Jessa', 19) # call method s.show() Output: Jessa 19 with keyword is used when working with unmanaged resources (like file streams). It allows you to ensure that a resource is “cleaned up” when the code that uses it finishes running, even if exceptions are thrown. Example: Open a file in Python using the with statement # Opening file with open('sample.txt', 'r', encoding='utf-8') as fp: # read sample.txt print(fp.read()) 3.3.4.6 Import Keywords: import, from, as In Python, the import statement is used to import the whole module. Example: Import Python datetime module import datetime # get current datetime now = datetime.datetime.now() print(now) Also, we can import specific classes and functions from a module. Example: # import only datetime class from datetime import datetime # get current datetime now = datetime.now() print(now) 3.3.4.7 Returning Keywords: return, yield In Python, to return value from the function, a return statement is used. yield is a keyword that is used like return, except the function will return a generator. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 11 Example: def addition(num1, num2): return num1 + num2 # return sum of two number # call function print('Sum:', addition(10, 20)) Output: Sum: 30 3.3.4.8 Exception-Handling Keywords: try, except, raise, finally, else, assert An exception is an event that occurs during the execution of programs that disrupt the normal flow of execution (e.g., KeyError Raised when a key is not found in a dictionary.) An exception is a Python object that represents an error. Variable Handling Keywords: del, global, nonlocal The del keyword is used to delete the object. The global keyword is used to declare the global variable. A global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file. Nonlocal variables are used in nested functions whose local scope is not defined. This means that the variable can be neither in the local nor the global scope. Example: price = 900 # Global variable def test1(): # defining 1st function print("price in 1st function :", price) # 900 def test2(): # defining 2nd function print("price in 2nd function :", price) # 900 # call functions test1() test2() # delete variable del price 3.3.4.9 Asynchronous Programming Keywords: async, await The async keyword is used with def to define an asynchronous function, or coroutine. async def (): Also, you can make a function asynchronous by adding the async keyword before the function’s regular definition. The await Keyword await keyword is used in asynchronous functions to specify a point in the function where control is given back to the event loop for other functions to run. You can use it by placing the await keyword in front of a call to any async function: await # OR = await INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 12 3.4 Python Variables A variable is a reserved memory area (memory address) to store value. For example, we want to store an employee’s salary. In such a case, we can create a variable and store salary using it. Using that variable name, you can read or modify the salary amount. In other words, a variable is a value that varies according to the condition or input pass to the program. Everything in Python is treated as an object so every variable is nothing but an object in Python. A variable can be either mutable or immutable. If the variable’s value can change, the object is called mutable, while if the value cannot change, the object is called immutable. We will learn the difference between mutable and immutable types in the later section of this article. Creating a variable Python programming language is dynamically typed, so there is no need to declare a variable before using it or declare the data type of variable like in other programming languages. The declaration happens automatically when we assign a value to the variable. 3.4.1 Creating a variable and assigning a value We can assign a value to the variable at that time variable is created. We can use the assignment operator = to assign a value to a variable. The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable’s value. variable_name = variable_value Example name = "John" # string assignment age = 25 # integer assignment salary = 25800.60 # float assignment print(name) # John print(age) # 25 print(salary) # 25800.6 3.4.2 Changing the value of a variable Many programming languages are statically typed languages where the variable is initially declared with a specific type, and during its lifetime, it must always have that type. But in Python, variables are dynamically typed and not subject to the data type restriction. A variable may be assigned to a value of one type, and then later, we can also re-assigned a value of a different type. Let’s see the example. Example var = 10 print(var) # 10 # print its type print(type(var)) # # assign different integer value to var var = 55 print(var) # 55 # change var to string var = "Now I'm a string" print(var) # Now I'm a string # print its type print(type(var)) # # change var to float INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 13 var = 35.69 print(var) # 35.69 # print its type print(type(var)) # 3.4.3 Create Number, String, List variables We can create different types of variables as per our requirements. Let’s see each one by one. 3.4.3.1 Number A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric values. 1. Int 2. float 3. complex 3.4.3.1.1 Integer variable The int is a data type that returns integer type values (signed integers); they are also called ints or integers. The integer value can be positive or negative without a decimal point. Example # create integer variable age = 28 print(age) # 28 print(type(age)) # Note: We used the built-in Python method type() to check the variable type. 3.4.3.1.2 Float variable Floats are the values with the decimal point dividing the integer and the fractional parts of the number. Use float data type to store decimal values. Example # create float variable salary = 10800.55 print(salary) # 10800.55 print(type(salary)) # In the above example, the variable salary assigned to value 10800.55, which is a float value. 3.4.3.1.3 Complex type The complex is the numbers that come with the real and imaginary part. A complex number is in the form of a+bj, where a and b contain integers or floating-point values. Example a = 3 + 5j print(a) # (3+5j) print(type(a)) # 3.4.3.2 String variable A string is a set of characters represented in quotation marks. Python allows us to define a string in either pair of single or double quotation marks. For example, to store a person’s name we can use a string type. To retrieve a piece of string from a given string, we can use to slice operator [] or [:]. Slicing provides us the subset of a string with an index starting from index 0 to index end-1. To concatenate the string, we can use the addition (+) operator. Example # create a variable of type string str = 'PYnative' # prints complete string print(str) # PYnative INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 14 # prints first character of the string print(str) # P # prints characters starting from 2nd to 5th print(str[2:5]) # nat # length of string print(len(str)) # 8 # concatenate string print(str + "TEST") # PYnativeTEST 3.4.3.3 List type variable If we want to represent a group of elements (or value) as a single entity, we should go for the list variable type. For example, we can use them to store student names. In the list, the insertion order of elements is preserved. That means, in which order elements are inserted in the list, the order will be intact. The list can be accessed in two ways, either positive or negative index. The list has the following characteristics: 1. In the list insertion order of elements is preserved. 2. Heterogeneous (all types of data types int, float, string) elements are allowed. 3. Duplicates elements are permitted. 4. The list is mutable (can change). 5. Growable in nature means based on our requirement, we can increase or decrease the list’s size. 6. List elements should be enclosed within square brackets []. Example # create list my_list = ['Jessa', 10, 20, 'Kelly', 50, 10.5] # print entire list print(my_list) # ['Jessa', 10, 20, 'Kelly', 50, 10.5] # Accessing 1st element of a list print(my_list) # 'Jessa' # Accessing last element of a print(my_list[-1]) # 10.5 # access chunks of list data print(my_list[1:3]) # [10, 20] # Modifying first element of a list my_list = 'Emma' print(my_list) # 'Emma' # add one more elements to list my_list.append(100) print(my_list) # ['Emma', 10, 20, 'Kelly', 50, 10.5, 100] 3.4.4 Get the data type of variable No matter what is stored in a variable (object), a variable can be any type like int, float, str, list, tuple, dict, etc. There is a built-in function called type() to get the data type of any variable. The type() function has a simple and straightforward syntax. Syntax of type() : type() INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 15 Example a = 100 print(type(a)) # class 'int' b = 100.568 print(type(b)) # class 'float' str1 = "PYnative" print(type(str1)) # class 'str' my_list = [10, 20, 20.5, 100] print(type(my_list)) # class 'list' my_set = {'Emma', 'Jessa', 'Kelly'} print(type(my_set)) # class 'set' my_tuple = (5, 10, 15, 20, 25) print(type(my_tuple)) # class 'tuple' my_dict = {1: 'William', 2: 'John'} print(type(my_dict)) # class 'dict' If we want to get the name of the datatype only as output, then we can use the__name__ attribute along with the type() function. See the following example where __name__ attribute is used. Example my_list =[10,20,20.5,'Python',100] # It will print only datatype of variable print(type(my_list).__name__) # list 3.4.5 Delete a variable Use the del keyword to delete the variable. Once we delete the variable, it will not be longer accessible and eligible for the garbage collector. Example var1 = 100 print(var1) # 100 Now, let’s delete var1 and try to access it again. Example var1 = 100 del var1 print(var1) Output: NameError: name 'var1' is not defined 3.4.5 Variable’s case-sensitive Python is a case-sensitive language. If we define a variable with names a = 100 and A =200 then, Python differentiates between a and A. These variables are treated as two different variables (or objects). Example a = 100 A = 200 # value of a print(a) # 100 # Value of A print(A) # 200 a = a + A print(a) # 300 INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 16 3.4.5 Constant Constant is a variable or value that does not change, which means it remains the same and cannot be modified. But in the case of Python, the constant concept is not applicable. By convention, we can use only uppercase characters to define the constant variable if we don’t want to change it. Example MAX_VALUE = 500 It is just convention, but we can change the value of MAX_VALUE variable. 3.4.5.1 Assigning a value to a constant in Python As we see earlier, in the case of Python, the constant concept is not applicable. But if we still want to implement it, we can do it using the following way. The declaration and assignment of constant in Python done with the module. Module means Python file (.py) which contains variables, functions, and packages. So let’s create two modules, constant.py and main.py, respectively. In the constant.py file, we will declare two constant variables, PI and TOTAL_AREA. import constant module In main.py file. To create a constant module write the below code in the constant.py file. PI = 3.14 TOTAL_AREA = 205 Constants are declared with uppercase later variables and separating the words with an underscore. Create a main.py and write the below code in it. Example import constant print(constant.PI) print(constant.TOTAL_AREA) Output 3.14 205 Note: Constant concept is not available in Python. By convention, we define constants in an uppercase letter to differentiate from variables. But it does not prevent reassignment, which means we can change the value of a constant variable. 3.4.5 Rules and naming convention for variables and constants A name in a Python program is called an identifier. An identifier can be a variable name, class name, function name, and module name. There are some rules to define variables in Python. In Python, there are some conventions and rules to define variables and constants that should follow. Rule 1: The name of the variable and constant should have a combination of letters, digits, and underscore symbols. Alphabet/letters i.e., lowercase (a to z) or uppercase (A to Z) Digits(0 to 9) Underscore symbol (_) Example total_addition TOTAL_ADDITION totalAddition Totaladdition INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 17 Rule 2: The variable name and constant name should make sense. Note: we should always create a meaningful variable name so it will be easy to understand. That is, it should be meaningful. Example x = "Jessa" student_name = "Jessa" It above example variable x does not make more sense, but student_name is a meaningful variable. Rule 3: Don’t’ use special symbols in a variable name For declaring variable and constant, we cannot use special symbols like $, #, @, %, !~, etc. If we try to declare names with a special symbol, Python generates an error Example ca$h = 1000 Output ca$h = 11 ^ SyntaxError: invalid syntax Rule 4: Variable and constant should not start with digit letters. You will receive an error if you start a variable name with a digit. Let’s verify this using a simple example. 1studnet = "Jessa" print(1studnet) Here Python will generate a syntax error at 1studnet. instead of this, you can declare a variable like studnet_1 = "Jessa" Rule 5: Identifiers are case sensitive. total = 120 Total = 130 TOTAL = 150 print(total) print(Total) print(TOTAL) Output 120 130 150 Here, Python makes a difference between these variables that is uppercase and lowercase, so that it will create three different variables total, Total, TOTAL. Rule 6: To declare constant should use capital letters. MIN_VALUE = 100 MAX_VALUE = 1000 Rule 7: Use an underscore symbol for separating the words in a variable name If we want to declare variable and constant names having two words, use an underscore symbol for separating the words. current_temperature = 24 3.4.6 Multiple assignments There is no restriction to declare a variable before using it in the program. Python allows us to create a variable as and when required. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 18 We can do multiple assignments in two ways, either by assigning a single value to multiple variables or assigning multiple values to multiple variables. 3.4.6.1. Assigning a single value to multiple variables We can assign a single value to multiple variables simultaneously using the assignment operator =. Now, let’s create an example to assign the single value 10 to all three variables a, b, and c. Example a = b = c = 10 print(a) # 10 print(b) # 10 print(c) # 10 3.4.6.2. Assigning multiple values to multiple variables Example: roll_no, marks, name = 10, 70, "Jessa" print(roll_no, marks, name) # 10 20 Jessa In the above example, two integer values 10 and 70 are assigned to variables roll_no and marks, respectively, and string literal, “Jessa,” is assigned to the variable name. 3.4.7 Variable scope Scope: The scope of a variable refers to the places where we can access a variable. Depending on the scope, the variable can categorize into two types local variable and the global variable. 3.4.7.1 Local variable A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. So it is not accessible from outside of the method. If we try to access it, we will get an error. Example def test1(): # defining 1st function price = 900 # local variable print("Value of price in test1 function :", price) def test2(): # defining 2nd function # NameError: name 'price' is not defined print("Value price in test2 function:", price) # call functions test1() test2() In the above example, we created a function with the name test1. Inside it, we created a local variable price. Similarly, we created another function with the name test2 and tried to access price, but we got an error "price is not defined" because its scope is limited to function test1(). This error occurs because we cannot access the local variable from outside the code block. 3.4.7.2 Global variable A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file. Example price = 900 # Global variable def test1(): # defining 1st function print("price in 1st function :", price) # 900 def test2(): # defining 2nd function INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 19 print("price in 2nd function :", price) # 900 # call functions test1() test2() In the above example, we created a global variable price and tried to access it in test1 and test2. In return, we got the same value because the global variable is accessible in the entire file. Note: You must declare the global variable outside function. 3.4.8 Object/Variable identity and references Whenever we create an object, a number is given to it and uniquely identifies it. This number is nothing but a memory address of a variable’s value. Once the object is created, the identity of that object never changes. No two objects will have the same identifier. The Object is for eligible garbage collection when deleted. Python has a built-in function id() to get the memory address of a variable. For example, consider a library with many books (memory addresses) and many students (objects). At the beginning (when we start The Python program), all books are available. When a new student comes to the library (a new object created), the librarian gives him a book. Every book has a unique number (identity), and that id number tells us which book is delivered to the student (object) Example n = 300 m = n print(id(n)) # same memory address print(id(m)) # same memory address It returns the same address location because both variables share the same value. But if we assign m to some different value, it points to a different object with a different identity. See the following example m = 500 n = 400 print("Memory address of m:", id(m)) # 1686681059984 print("Memory address of n:", id(n)) # 1686681059824 For m = 500, Python created an integer object with the value 500 and set m as a reference to it. Similarly, n is assigned to an integer object with the value 400 and sets n as a reference to it. Both variables have different identities. 3.4.8.1 Object Reference When we assign a value to a variable, we create an object and reference it. For example, a=10, here, an object with the value 10 is created in memory, and reference a now points to the memory address where the object is stored. Suppose we created a=10, b=10, and c=10, the value of the three variables is the same. Instead of creating three objects, Python creates only one object as 10 with references such as a,b,c. We can access the memory addresses of these variables using the id() method. a, b refers to the same address in memory, and c, d, e refers to the same address. See the following example for more details. Example a = 10 b = 10 print(id(a)) print(id(b)) INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 20 c = 20 d = 20 e = 20 print(id(c)) print(id(d)) print(id(e)) Output 140722211837248 140722211837248 140722211837568 140722211837568 140722211837568 Here, an object in memory initialized with the value 10 and reference added to it, the reference count increments by ‘1’. When Python executes the next statement that is b=10, since it is the same value 10, a new object will not be created because the same object in memory with value 10 available, so it has created another reference, b. Now, the reference count for value 10 is ‘2’. Again for c=20, a new object is created with reference ‘c’ since it has a unique value (20). Similarly, for d, and e new objects will not be created because the object ’20’ already available. Now, only the reference count will be incremented. We can check the reference counts of every object by using the getrefcount function of a sys module. This function takes the object as an input and returns the number of references. We can pass variable, name, value, function, class as an input to getrefcount() and in return, it will give a reference count for a given object. import sys print(sys.getrefcount(a)) print(sys.getrefcount(c)) See the following image for more details. Python object id references In the above picture, a, b pointing to the same memory address location (i.e., 140722211837248), and c, d, e pointing to the same memory address (i.e., 140722211837568 ). So reference count will be 2 and 3 respectively. 3.4.9 Unpack a collection into a variable Packing In Python, we can create a tuple (or list) by packing a group of variables. Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 21 Example a = 10 b = 20 c = 20 d = 40 tuple1 = a, b, c, d # Packing tuple print(tuple1) # (10, 20, 20, 40) Here a, b, c, d are packed in the tuple tuple1. Tuple unpacking is the reverse operation of tuple packing. We can unpack tuple and assign tuple values to different variables. Example tuple1 = (10, 20, 30, 40) a, b, c, d = tuple1 print(a, b, c, d) # 10 20 30 40 Note: When we are performing unpacking, the number of variables and the number of values should be the same. That is, the number of variables on the left side of the tuple must exactly match a number of values on the right side of the tuple. Otherwise, we will get a ValueError. Example a, b = 1, 2, 3 print(a,b) Output a, b = 1, 2, 3 ValueError: too many values to unpack (expected 2) KEY TERMS statement is an instruction that a Python interpreter can execute. if statement: It is a control flow statement that will execute statements under it if the condition is true. Also kown as a conditional statement. while statements: The while loop statement repeatedly executes a code block while a particular condition is true. Also known as a looping statement. for statement: Using for loop statement, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple. Also known as a looping statement. try statement: specifies exception handlers. with statement: Used to cleanup code for a group of statements, while the with statement allows the execution of initialization and finalization code around a block of code. Expression statements. are used to compute and write a value. An expression statement evaluates the expression list and calculates the value. The pass statement. pass is a null operation. Nothing happens when it executes. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed. keywords are reserved words that have a special meaning associated with them and can’t be used for anything but those specific purposes. Each keyword is designed to achieve specific functionality. keyword.kwlist: It return a sequence containing all the keywords defined for the interpreter. keyword.issoftkeyword(s): Return True if s is a Python soft keyword. keyword.softkwlist: Sequence containing all the soft keywords defined for the interpreter. INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected] Module 3 - Python Statements, Comments, Keywords, and Variables 22 while: The while loop repeatedly executes a code block while a particular condition is true. for: Using for loop, we can iterate any sequence or iterable variable. The sequence can be string, list, dictionary, set, or tuple. with keyword is used when working with unmanaged resources (like file streams). A number is a data type to store numeric values. The int is a data type that returns integer type values (signed integers); they are also called ints or integers. Floats are the values with the decimal point dividing the integer and the fractional parts of the number. A string is a set of characters represented in quotation marks. Constant is a variable or value that does not change, which means it remains the same and cannot be modified. A name in a Python program is called an identifier. An identifier can be a variable name, class name, function name, and module name. A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file. REFERENCES Books: Chaudhuri, A.B. (2020). Flowchart and Algorithms Basic: The Art of Programming. Mercury Learning and Information Gaddis, T. (2019). Starting Out with Python. Fourth Edition, Global Edition. Pearson Matthes, E. (2019). Python Crash Course: a Hands – on Project – based Introduction to Programming. 2nd Edition. No Starch Press. Halterman, R. (2018). Fundamentals of Python Programming. Busbee, K. L. and Braunschweig, D. Programming Fundamentals A Modular Structured Approach, 2nd Edition. Online: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=116s https://www.tutorialspoint.com/python/index.htm https://www.youtube.com/watch?v=WW-NPtIzHwk https://www.youtube.com/watch?v=OjWmVCG8PLA INFORMATION AND COMMUNICATION TECHNOLOGY DEPARTMENT Isabela State University – City of Ilagan Campus ROMAN ALEX F. LUSTRO, LPT, DIT [email protected]