
Basics of Python Programming Language | CBSE Class 11| Computer Science
Dear Class 11th STUDENTS, ! Welcome to this tutorial of Basics of Python programming Language from your CBSE class 11 of Computer Science Syllabus .
In this tutorial, we shall be learning our chapter-2: Basics of Python programming Language from Unit 2: Programming and Computational Thinking (PCT-1) as CBSE BOARD suggested to learn about computer system and its organisation to complete this section.
Unit 2: Programming and Computational Thinking (PCT-1)
Chapter 2: Basics of Python programming Language:
- Introduction to Python Programming Language
- Features of Python Programming Language
- executing a simple “hello world” Python program
- execution modes: interactive mode and script mode
- Character set in Programming Language.
- Tokens (keyword, identifier, literal, operator, punctuator) in Python Programming Language
- variables in Python Programming Language
- concept of l-value and r-value in python Programming Language
- Use of comments in Python Programming Language
I advice you to check the latest syllabus given by CBSE Board at its Official website: www.cbseacademic.nic.in
Also, in this tutorial we will covers all necessary topics/concepts required to complete your exams preparations in CBSE classes 11th.
NOTE:
- We are also giving some important Questions & Answers for better understanding as well as preparation for your examinations.
- You may also download PDF file of this tutorial from our SHOP for free.
- For your ease and more understanding, we are also giving the video explanation class of each and every topic individually, so that you may clear your topics and get success in your examinations.
Python is a high-level programming language that anyone can learn. Guido van Rossum created it in 1991, designing it to be easy to read and write. Think of Python as a tool that lets you give instructions to a computer in a way that feels almost like writing plain English. For example, you can tell a computer to print “Hello, World!” with just one line of code.
Why does this matter? Because Python’s simplicity makes it perfect for beginners and professionals alike. Whether you want to build a website, analyze data, or create a game, Python can do it all.
INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE
Anywhere and everywhere, where you want to transform some kind of input to certain output, you have some kind of input to certain output, you have to have a program. a programmed is a set of instruction that govern the processing. in other words, a programmer forms the base for processing.
In this tutorial, we shall we talking about all basics and elements that a python program can contain. you will be learning about python’s basic like character set, tokens, expression, statement, simple, input and output etc. so, are we all ready to take our first sincere step towards python programming?.
Every component of a python program is created using the character set, be it statement or expression or other components of a program.
Features of Python Programming Language
Python’s popularity keeps growing. According to recent surveys, it’s one of the top programming languages in 2025, especially for data science and AI. Companies are hiring Python developers, and the demand is high. So, learning Python now is a smart move for your career.
What’s next? As you get comfortable, explore advanced topics like machine learning or web frameworks. Python’s vast ecosystem means you’ll never run out of things to learn.
- General-purpose Object-Oriented Programming language.
- High-level language
- Developed in late 1980 by Guido van Rossum at National Research Institute for Mathematics and Computer Science in the Netherlands.
- It is derived from programming languages such as ABC, Modula 3, small talk, Algol-68.
- It is Open-Source Scripting language.
- It is Case-sensitive language (Difference between uppercase and lowercase letters).
- One of the official languages at Google.
Let’s discuss some important points to be remember while learning python
Characteristics of Python Programming Language
- Interpreted programming Language.
- Interactive programming Language.
- Object Oriented Programming Language.
- Easy & Simple programming Language.
- Portable programming Language.
- Scalable programming Language:
- Integrated programming Language.
- Expressive programming Language.
Benefits of Python Programming Language
Python stands out because it’s powerful yet easy to use. Let’s look at some reasons why millions of people love Python:
- Easy to Learn: Python’s syntax is clear and straightforward. You don’t need to be a tech genius to start coding.
- Versatile: You can use Python for web development, data science, artificial intelligence, automation, and more.
- Huge Community: Python has a massive global community. If you get stuck, thousands of tutorials, forums, and experts are ready to help.
- Free and Open-Source: Anyone can download and use Python for free. Plus, you can customize it to suit your needs.
Because of these benefits, companies like Google, NASA, and Instagram use Python. Exciting, right? Now, let’s see what you can build with it.
What Can You Do with Python Programming Language ?
Python is like a Swiss Army knife for coding. Here are some cool things you can create:
- Websites: Frameworks like Django and Flask let you build fast, secure websites.
- Data Analysis: Python’s libraries, like Pandas and NumPy, help you crunch numbers and visualize data.
- Artificial Intelligence: Tools like TensorFlow and PyTorch make Python a favorite for AI and machine learning.
- Automation: Want to save time? Python can automate boring tasks like renaming files or sending emails.
- Games: Libraries like Pygame let you create fun games, from simple puzzles to 2D adventures.
The possibilities are endless! And the best part? You can start with small projects and grow your skills over time.
Interpreter in Python Programming Language
Names of some Python interpreters are:
- PyCharm
- Python IDLE
- The Python Bundle
- pyGUI
- Sublime Text etc.
Companies Using Python Programming Language in real time
- In operations of Google search engine, youtube, etc.
- Bit Torrent peer to peer file sharing is written using Python
- Intel, Cisco, HP, IBM, etc use Python for hardware testing.
- Maya provides a Python scripting API
- i–Robot uses Python to develop commercial Robot.
- NASA and others use Python for their scientific programming task.
EXECUTING A SIMPLE “Hello World” PROGRAM IN PYTHON
Ready to jump in? Starting with Python is super easy. Follow these steps, and you’ll be coding in no time:
Install Python: Visit the official Python website (python.org) and download the latest version. It works on Windows, Mac, and Linux.
Choose an Editor: Use a code editor like VS Code, PyCharm, or even a simple one like IDLE, which comes with Python.
Write Your First Code: Try this simple program to print “Hello, World!”:
print("Hello, World!")
Run it, and you’ll see the output instantly!
EXECUTION MODES IN PYTHON PROGRAMMING LANGUAGE
There are two modes to use the python interpreter:
- Interactive Mode
- Script Mode
Interactive Mode in python
Without passing python script file to the interpreter, directly execute code to Python (Command line).
Example:
>>>a=2
>>b=3
>>c=a+b
>>print(c)
Fig: Interactive Mode
Important –
The interactive mode is better when a programmer deals with small pieces of code. >>> is a command the python interpreter uses to indicate that it is ready.
To run a python file on command line:
exec(open(“C:\Python33\python programs\program1.py”).read( ))
Script Mode in python
In this mode source code is stored in a file with the extension (.py) and use the interpreter to execute the contents of the file. To execute the script by the interpreter, you have to tell the interpreter the name of the file.
if you have a file name (As qissba.py) , to run the script you have to follow the following steps:
- Open the text editor i.e. Notepad
- Write the python code and save the file with .py file extension. (Default
- directory is C:\Python33/qissba.py)
- Open IDLE ( Python GUI) python shell
- Click on file menu and select the open option
- Select the existing python file
- Now a window of python file will be opened
- Click on Run menu and the option Run Module.
Output will be displayed on python shell window.
Fig. : IDLE (Python GUI)
Before you begin your journey with python it is important to know what all it takes to develop ‘computational thinking’? this is because using any programming languages, your devices solution for problem and to reach at effective solution, computational thinking is required. so, let us first talk about ‘computational thinking’ before starting with python.
CHARACTER SET IN PYTHON PROGRAMMING LANGUAGE
Character set is an important concept in programming, especially when it comes to handle the text data task. In Python.
A character set, also known as a charset, is a set of characters that are used in a particular encoding system. In Python, character sets are used to represent text data. Each character in a character set is represented by a unique code point, which is a numerical value that corresponds to a specific character.
Python supports a wide range of character sets, including
- ASCII
- Unicode
- ISO-8859
Let’s take a closer look at each of these character sets.
Basic character set in Python
in Python, character set is a set of valid characters that python language can recognize and use for processing where a single character represents any letter digit or any other symbol. This means the python supports the following character set.
- The very basic elements that a python programming can have to make it possible to read write and understand by both the humans and the machine as well.
- The character set plays and important role to complete this IPO cycle, means the is no input and process nor any output without the concept of CHARACTER SET.
- character set refers to the set of characters that are available in a particular encoding system.
Every component of python programming is created using these character set. It may be a basic units like keyword, identifiers or may be an statement, expression or any other component.
List of basic Characters in Python
TOKEN IN PYTHON PROGRAMMING LANGUAGE
In simple terms, tokens are the basic building blocks of any programming language. They are the individual components that make up the syntax of a program. In Python, tokens can be anything from keywords and identifiers to operators and punctuation marks.
By mastering the various types of tokens and their usage, you will be able to write more efficient and error-free code. Whether you are a student preparing for your exams or a beginner programmer looking to enhance your skills, this guide will provide you with everything you need to know about tokens in Python. So let’s get started and explore the world of Python tokens!
While learning about python tokens and to understand it deeply, first we have the following diagrams about An English sentence and a python program.
Let’s see
As so-called definitions of different books says:
A token in python is the smallest individual unit in a program and sometimes it is also called as lexical unit in Python programming
OR
In a passage of text individual words and punctuation marks are called tokens lexical units or lexical elements in python
But how we, as a beginner can understand the tokens in python.
Let’s have an example to understand
Suppose as a beginner you want a Python program to write any sentence on the screen, let’s say your name then you can do it very easily by using a simple sentence on your Python IDLE.
print(“my name”)
Now, you can see
There are some English words like:-
print TOKEN 1 ( KEYWORD TOKEN)
my name TOKEN 2 ( STRING TOKEN)
Here, we can see that there are two English words and we are denoting them as TOKEN 1 and TOKEN 2 and token one is a Keyword type token and Token 2 is an string type token.
What does it means?
It means the tokens can be have more than one types YES!!!!!, So now you have a right question to learn about tokens and that is :-
How many types of tokens are there in Python?
Basically a Python program breaks a logical line into a sequence of elementary lexical components and these components are known as tokens and each token corresponds to a substring of the logical line, so to know the different types of tokens that can be used while writing a Python program, please have a look at the following diagram.
So we can say that there are the following types of tokens in Python programming
- 1. Keyword
- 2. Identifiers
- 3. Literals
- 4. Operators
- 5. Punctuators
- 6. Special literal
TRICK : You can remember these types easily by considering all tokens as kILOPS where
- K : stands for keywords
I : stands for identifiers
L : stands for literals
O: stands for operators
P: stands for punctuators
P: stands for special symbols
Now, you have understood that when we write any command or statement in a Python program that will do something for us, and we write the command or statement by combining some tokens and that command is also meaningful to a computer and Python software and Python interpreter can understand it easily.
Keywords
If you’re new to programming in Python, you may have heard the term “reserved keywords” but aren’t quite sure what they are. In this post, we’ll provide a comprehensive guide to Python reserved keywords, explaining what they are, why they’re important, and how to use them properly.
Keywords are predefined words in Python that have a specific meaning and cannot be used as identifiers. Python has 35 keywords, and they are reserved for specific uses within the language. These keywords include “if”, “else”, “while”, “for”, “class”, “def”, “return”, and more.
These keywords are an important part of the Python programming language, defining its structure and syntax. By following best practices for using reserved keywords, you can ensure that your code is easy to read, understand, and maintain. We hope this tutorial will help you gain a better understanding of Python reserved keywords and how to use them properly in your code.
Reserved keywords are words that have a special meaning in Python and cannot be used as variable names or other identifiers. These keywords are reserved for specific programming purposes and have predefined functionality in the Python language. Examples of Python reserved keywords include “if,” “else,” “while,” “for,” “break,” “class,” and “def.”
LIST OF Python KEYWORDS
- Value Keywords: True, False, None.
- Operator Keywords: and, or, not, in, is.
- Control Flow Keywords: if, elif, else.
- Iteration Keywords: for, while, break, continue, else.
- Structure Keywords: def, class, with, as, pass, lambda.
- Returning Keywords: return, yield.
- Import Keywords: import, from, as.
Why Are Reserved Keywords Important?
Reserved keywords are important in Python because they help define the language’s structure and syntax. By reserving certain keywords for specific programming purposes, Python ensures that developers can write code that is easy to read and understand, making it simpler to create and maintain complex software projects.
How to Use Reserved Keywords in Python?
To use keywords in Python, you simply need to include them in your code where appropriate. For example, if you want to use a conditional statement in your code, you would use the “if” reserved keyword followed by the condition you want to test. It’s important to remember that reserved keywords cannot be used as variable names or other identifiers in your code.
Example of Reserved Keywords
From the previous discussion we know that keywords in python are special types of tokens whose meanings and uses are already defined to the Python interpreter. it means if you use these words for any other purpose except for which it is defined then they will not work and give errors in your Python program.
This can be understood by the example of English dictionary. Because in In English dictionary meanings for each
Example:
word is already define that means
An apple is always an apple Apple is a keyword for a specific fruit
A table is always a table Table is a keyword for a specific furniture
and
you cannot use word apple for table
and cannot use word table for apple
Now, so called definitions for keywords in python are:-
Keywords in python are special identifiers with predefined meanings that cannot be changed.
A keyword in python is a special word that has a special meaning and purpose keywords are reserved and are few in quantity .
Example
If, elif, else
That’s enough for writing answers in examinations. Now let’s finish the topic by the following table which has all useful keywords in Python programming.
Identifiers
Identifiers are names given to variables, functions, classes, and other objects in a Python program. An identifier is a user-defined name that is used to identify a particular variable, function, or object in the program. Identifiers can be composed of letters, numbers, and underscores, but cannot begin with a number. It’s best practice to use descriptive names for your identifiers.
Similar to the keywords, identifiers are also names given to different parts of a Python program identifiers are used to provide new names for the following useful entities in Python like wise.
- Variables
- Objects
- Classes
- Functions
- Lists
- Dictionaries etc.
Definition of Python Identifiers:
A variable or identifier is the name given to the memory location so that there is no need to to remember the address of the location and these identifiers can hold different kind of data like integer, float, and string etc.
Example
You use the name of the person to remember the number of mobile contacts because it is easier to find the mobile number via the name saved by you .
one more example for your ease to understand is the website address if I tell you the web address of my left side is 17268 152 137 and you have to remember this address if you wish to visit again and if I tell you www.iasbaba.com then it will be easier to remember.
Similarly our system memory is divided into a number of small parts (sectors and blocks).
now you can see that IN A PYTHON PROGRAM, IF WE DECLARE AN STATEMENT LIKE THIS:-
age=32
Then the random location 11052 (LET’S SAY ) is occupied by variable / Identifier age and the value 52 is given.
Rules for creating Python Identifiers:
There are some rules for creating Python identifiers. Here are some of the key rules:
- Identifiers can be any length and can contain letters, numbers, and underscores. However, they cannot start with a number.
- Identifiers are case-sensitive. This means that
my_variable
,My_Variable
, andMY_VARIABLE
are all different identifiers. - Identifiers cannot be the same as a reserved keyword in Python. For example, you cannot use
if
,else
,while
,for
,return
, ordef
as an identifier. - Identifiers should be descriptive and indicate the purpose of the variable, function, class, or other object they are identifying.
- For variable and function names, use lowercase letters and separate words with underscores, such as
my_variable
ormy_function
. - For class names, use CamelCase where the first letter of each word is capitalized and there are no underscores, such as
MyClass
orMyOtherClass
. - Avoid using single-character variable names unless they have a specific purpose, such as
i
for a loop index.
Overall, the rules for creating Python identifiers are designed to ensure that identifiers are clear, easy to read, and unambiguous. By following these rules, you can create identifiers that are both effective and easy to work with in your Python code.
Now also, there are some rules for creating identifiers for variables in Python.
- We cannot use keywords as an identifier
- variable names must be made with only letters numbers and_
- variable names cannot start with numbers although they can contain numbers
Important Note :
we cannot use space between in Python programs BECAUSE Python is case sensitive as it treats lower and uppercase characters differently.
now you can more understand this concept with the help of the following table diagram
Literals
Literals are fixed values in a Python program that are used to represent specific data types. Examples of literals include strings, integers, floating-point numbers, and Boolean values. String literals are enclosed in single or double-quotes, and numeric literals are represented by a sequence of digits.
Basically, Literals are the values that may be given to identifiers.
Now the question arises that how many types of literals are there in Python? that can be used to assign values to the different identifiers
for example
name = “qissba”
age = 32
height = 5.75
status = true
grade = a
Let’s discuss these types of literal values one by one.
- STRING LITERALS IN PYTHON:
- NUMERIC LITERALS IN PYTHON:
- BOOLEAN LITERALS IN PYTHON:
- SPECIAL LITERALS IN PYTHON:
- LITERALS COLLECTION IN PYTHON:
STRING LITERALS IN PYTHON:
A string literal is a sequence of characters surrounded by quotes and quotes may be single or double and also a string literal can be of the following two types:
- single line string in python: A single line string must be terminated in one line, that is the closing quotes should be in the same line as the open quotes are given.
Example
name = “my name is Qissba.”
- multiline string in python: A multiline string main spread across multiple lines with only one opening and closing quote and each line is ended with an and character\
- Note: no backslash ( / ) is needed if you are using couple quotes for enclosing the springs.
Example
name = “my name /
is qissba”
but name =’’’ my name
is qissba’’’
- Note: In string literal you can use non graphical characters through escape sequences important escape sequences are given in the following table.
TABLE FIGURE
NUMERIC LITERALS IN PYTHON:
Numeric literals are the values which are used to represent the quantity of identifier or variable at the time of execution in a Python program
Example
Age= 32
height=8.5 and
sum = 2 + 3j.
So, the numeric value literals that are used in Python Programming are one of the following types
Integers:
Integer literals are the whole numbers as used in mathematics which are used to represent the value of complete entity like table or chair or person
Example: you cannot purchase that half chair or table
that means integer literals are positive or negative whole numbers with no decimal points these integers literals can be written in following forms in Python programming.
Decimal form:
when an integer is written with the help of digits from 0 to 9 it is called decimal form for example 1249 4002
Octal:
When an integer is written with digits 0 1 2 3 4 5 6 7 and followed by Oz 0 followed by letter O note remember that digit 89 are excluded in this form for example 4035 4074.
Hexadecimal:
When an integer is written with the help of digits from 0 to 9 and letters A to F and also followed by 0X (zero followed by letter X), where.
# Read more on of these NUMBER SYSTEMS in detail. Click Here
FLOATING POINT ITERALS
When we want to represent things with fractional part like 1.5 meter or 3.5 liter we use floating point values and Sporting point values literals represent real number and are written with the decimal point dividing the integer and fractional Parts
for example
age = 30.5
weight = 68.9
- Note that floating point values can also be written in exponent form, for example 17305 64 I will learn in detail.
COMPLEX LITERALS
If a python literal is written in the form like a+bj, then this type of literal is called Complex Literal. Where
a,b are integers or floating point values and
j represents , which is an imaginary value.
Example: We have an equation like
S=3+5j
And we want our python program to solve this by executing it ,then what will be the output of this equation?, obviously here j is a variable that requires an instant value at the time of execution of this equation and, the value you give at execution time (let’s say ) is 2, then the output will be
S=3+5×2 j=2
S=13
But another time, when you execute this program, you may check it for other values of j like 1, 2, 3,4,5,6 ……. and so on.
Then the output will come differ every time. It means the value of S is always depends on the value of j and the value of j may be different and rely on users imagination. Hence this concept makes this form of literal complex because the output always depends on user’s imagination and create a complexity about the final output of this python program.
Finally we can say that , a complex number is made up of two parts
- Real part a ( a is 3)
- Imaginary part bj (b is 5)
BOOLEAN LITERALS IN PYTHON:
Boolean literals in Python is to represent only two values. These are true and false and we can assign only one Boolean value true or false to an identifier for a variable in Python.
SPECIAL LITERALS IN PYTHON:
Similar to the Boolean literals special literals has only one value that is none and this null literal is used to include the absence of any value it mean that there is no value even not is zero for that identifier or variable but a compiled by the variable
for example
house_number = 57
owner = Mr Ashok
Number_of_persons = None
LITERALS COLLECTION IN PYTHON:
In Python, literals collection refers to the different types of literals that can be used to represent different types of data. Python supports several types of literals, including:
- Numeric literals: These are used to represent numeric data types such as integers, floating-point numbers, and complex numbers.
- String literals: These are used to represent textual data and can be enclosed in either single or double quotes.
- Boolean literals: These are used to represent the truth values True and False.
- None literal: This represents the absence of a value.
In addition to these basic literals, Python also supports other types of literals such as:
- List literals: These are used to represent a collection of values, and are enclosed in square brackets.
- Tuple literals: These are similar to list literals, but are enclosed in parentheses and cannot be modified once created.
- Dictionary literals: These are used to represent key-value pairs, and are enclosed in curly braces.
- Set literals: These are used to represent an unordered collection of unique values, and are enclosed in curly braces.
Operators
Operators are symbols that are used to perform operations on variables and literals. Python has several types of operators such as arithmetic operators, assignment operators, comparison operators, logical operators, and more. Some examples of operators include “+” for addition, “-” for subtraction, “*” for multiplication, “/” for division, and “%” for modulo.
Punctuators
Punctuations are symbols used to structure a Python program. Punctuations are used to indicate the beginning and end of blocks of code, define function arguments, and more. Examples of punctuations include parentheses, commas, colons, semicolons, and more.
Special literal
Python has a special literal called None that is used to represent the absence of a value. None is an object in Python that is commonly used to indicate that a variable has no value or that a function returns no value. In this blog post, we will explore the special literal – None in Python, its characteristics, and its usage in Python programs.
VARIABLES IN PYTHON PROGRAMMING LANGUAGE
Variables represent labelled storage locations, whose values can be manipulated during program run.
In python ,to create a variable, just assign to its name the value of appropriate type. For example, to create a variable namely Student to hold student’s name and variable age to hold student’s age, you just need to write somewhat similar is shown below:
Student=” Jacob”
Age=16
Python will internally create labels referring to these values as shown below.
Creating a variable
Let’s take statement we used just now to create the variable marks:
Marks = 70
As you can see, that we just assigned the value of numeric type to an identifier name and python created the variable of the type similar to the type of value assigned. In short, after the above statement, we can say that marks is a numeric variable.
So, creating variable, just assign to it name the value of appropriate type. For example, to create a variable namely student to hold student ‘s name and variable age to hold student’s age, you just need to write somewhat similar to what is shown below:
Student = ‘Jacob’
Age = 16
Python will internally create labels referring to these value as shown below:
Isn’t it simple?? 😊okay, let ‘s now create some more variable.
Train No = ‘T#1234’ #variable created of string type
Balance = 23456.75 #variable created of numeric (floating point) type
roll No = 105 #variable created of numeric (integer) type
some, way you can create as many variables as you need for your program.
Multiple assignments
Python Is a very versatile with assignment. let’s see in how many different ways, you can use assignment in python.
Assigning some value to multiple variables
You can assign same value to multiple variables in a single statement, e.g.,
a = b = c = 10
it will assign value 10 to all three-variable a, b, c. that is all three labels a, b, c will refer to same location with value 10.
Assigning multiple value to multiple variables
You can even assign multiple values to multiple variables in singles statement, e.g.,
x, y, z = 10,20,30
it will assign the value order wise, i.e., first variable is given first value, second variable the second value and so on. That means, above statement will assign value 10 to x,20 to y and 30 to z.
this style of assigning value is very useful is very useful and compact. for example, consider the code given below:
X, y, = 25,50
print (X, y)
it will print result as
25 50
Because x is having value 25 and y is having 50. Now, if you want to swap value of x and y you just need to write:
X, y = y, x
Print (x, y)
Now the result will be
50 25
Because this time the value has been swapped and x is having value 25 and y is having 50. while assigning value through multiple assignments, please remember that python first evaluates the RHS (right hand side) expression (s) and then to LHS (left hand side), e.g.,
A, b, c = 5,10,7 #stament1
B, c, a=a + 1, b + c, c-1 #statement2
Print (a, b, c)
- Statement 1assign 5,10 and 7 to a, band c respectively.
- Statement2 will first evaluate RHS i.e., a +1, b + 2, c – 1 which will yield
5 + 1, 10 +2, 7 – 1 = 6, 12, 6
Then it will make the statement (by replacing the evaluated result of RHS) as :
b, c, a = 6, 12, 6
Thus, b = 6, c=12 and a = 6
- The third statement print (a, b, c) will print
6 6 12
Isn’t this easy? now can you guess the output of following code fragment2
P, q = 3
q, r = p – 2, p+2
print (p, q, r)
please note the expression separated with commas are evaluated from left to right and assigned in same order e.g.,
x = 10
y, y = x + 2, x + 5
will evaluate to following (after evaluating expression on RHS = Operator)
y, y = 12,15
i.e., firstly, it will assign first RHS value to first LHS variable i.e.,
y = 12
then it will assign second RHS value to second LHS variable i.e.,
y = 5
so, if you print y after this statement y will contain 15.
Now, consider following code and guess the output:
x, x = 20, 30
y, y = x + 10, x + 20
Print (x, y)
Well, it will print the output as
30 50
Now you know why? 😊
CONCEPTS OF L-VALUE AND R-VALUE IN PYTHON PROGRAMMING LANGUAGE
In Python, l-value and r-value refer to the type of expression an operator can take. An l-value is an expression that can be assigned a value (usually a variable), while an r-value is an expression that yields a value (e.g., a literal or the result of a calculation).
L-value Definition in Python:
An l-value is an expression that can appear on the left-hand side (LHS) of an assignment operator (=). It represents a memory location that can be modified.
Examples:
x in x = 5
my_list[0] in my_list[0] = 10
a.b in a.b = 20 (where a is an object and b is an attribute)
R-value Definition in Python:
An r-value is an expression that yields a value. It can appear on the right-hand side (RHS) of an assignment operator.
Examples:
5 in x = 5
1 + 2 in x = 1 + 2
len(my_list) in y = len(my_list)
Key Differences between L-value and R-value:
Feature | L-value | R-value |
Assignment | Can appear on the LHS of an assignment. | Can appear on the RHS of an assignment. |
Modifiability | Can be assigned a value. | Cannot be assigned a value. |
Memory Location | Represents a memory location. | Represents a value. |
Examples | Variables, array elements, object attributes | Literals, calculations, function calls (returning a value) |
In Python Programming Language:
- L-values in Python are typically variables, array elements, or object attributes that can be modified.
- R-values are expressions that produce a value, such as literals, arithmetic calculations, or function calls that return a value.
Example :
x = 5 # x is an l-value, 5 is an r-value
my_list = [1, 2, 3]
my_list[0] = 10 # my_list[0] is an l-value, 10 is an r-value
y = len(my_list) # y is an l-value, len(my_list) is an r-value
USE OF COMMENTS IN PYTHON PROGRAMMING LANGUAGE
Comments are lines of text that are ignored by the Python interpreter when we execute a program. Comments are used to provide additional information about the code, explain complex logic, or describe the purpose of a specific block of code. Comments are preceded by the hash symbol (#) in Python and can be placed on a separate line or at the end of a line of code.
It means Comments in python are the additional readable information, which is read by the programmers but ignored by Python interpreter. In Python, comments begin with symbol # (Pound or hash character) and end with the end of physical line.
TYPES OF COMMENTS IN PYTHON
In the above code, you can see four types of comments:
Single Line Comment:
Single-line comments are the most common type of comment in Python. They are used to provide a short description of the code on a single line. Single-line comments start with the hash (#) symbol and are placed at the beginning of the line. Any text that follows the hash symbol on the same line is treated as a comment and is ignored by the Python interpreter.
The physical lines beginning with # are the full line comments. There are three types of full line comments in python:
- # This program shows a program” s components
- # Definition of function see you () follows
- # Main program code follows now
Inline Comment:
The fourth comment is an inline comment as it starts in the middle of a physical line, after Python code (see below)
if b > 5: # colon means it requires a block
Inline comments are used to provide comments within a single line of code. They are useful for explaining complex code or providing additional information about a specific operation. Inline comments start with the hash symbol (#) and are placed at the end of the line of code.
Multi Line Comment:
Multi-line comments are used to provide longer descriptions of the code or to add comments to multiple lines of code. In Python, multi-line comments are created using triple quotes (‘ ‘ ‘ or ” ” “). Anything that is enclosed within triple quotes is treated as a comment and is ignored by the interpreter.
What if you want to enter a multi- line comment or a block comment? You can enter a multi – line comment in Python code in two ways:
Add a # symbol in the beginning of every physical line part of the multi- line comments, e.g.,
# Multi-line comments are useful for detailed additional information.
# Related to the program in question.
# It helps clarify certain important things.
Type comment as a triple – quoted multi-line string e.g.,
” ” “ Multi-line comment are useful for detailed additional information related to the program in question. It helps clarify certain important things
” ” “
This type of multi-line comment is also known as docstring.
You can either use triple – apostrophe ( ” ” ” ) or triple quotes ( ‘ ‘ ‘ ) to write docstrings. The docstring are very useful in documentation -and you “II learn about their usage later.
Documentation comments
Documentation comments are used to provide detailed information about a module, class, or function. They are often used to generate documentation for Python code using tools like Sphinx. Documentation comments start with a triple quote ( ‘ ‘ ‘ or ” ” “ ) and are placed directly below the module, class, or function definition.
Why are comments important in Python?
Code documentation: Comments serve as a form of documentation for your code. By providing explanations and notes about your code, you make it easier for other developers to understand and modify your code in the future.
Improved readability:
Comments improve the readability of your code by breaking it down into smaller, more manageable chunks. By using comments to separate your code into logical sections, you can make it easier for others (and yourself) to read and understand the code.
Debugging:
Comments can be used to identify and troubleshoot issues in your code. By adding comments to specific lines or blocks of code, you can make it easier to identify the cause of errors and fix them quickly.
Collaboration:
Comments make it easier for multiple developers to work on the same codebase. By providing clear explanations and notes about your code, you can make it easier for others to contribute to the project and maintain the codebase over time.
How to write effective comments in Python?
Use clear and concise language:
Your comments should be easy to read and understand. Use simple language and avoid technical jargon or abbreviations that may be unfamiliar to other developers.
Comment frequently:
Commenting frequently can help ensure that your code is easy to read and understand. Try to add comments to each function, loop, or block of code that performs a specific task.
Use descriptive comments:
Your comments should describe the purpose of the code and provide context for other developers. Use descriptive comments that explain the what, why, and how of your code.
Avoid unnecessary comments:
While comments are important, too many comments can make your code harder to read. Avoid adding comments that simply repeat the code or state the obvious.
EXAM TIME
Here are some important questions and their answers on the topic of “Python Keywords”:
Q. What are Python Keywords?
Answer: Python Keywords are reserved words that have a special meaning in the Python programming language. These words cannot be used as identifiers, such as variable names or function names, and are used to define the syntax and structure of the Python language.
Q. How many keywords are there in Python?
Answer: As of Python 3.10, there are 35 keywords in Python. Some of the commonly used keywords include “if”, “else”, “while”, “for”, “in”, “def”, “return”, “import”, and “from”.
Q. What is the difference between a keyword and an identifier in Python?
Answer: Keywords are reserved words that have a special meaning in Python, and cannot be used as identifiers such as variable names or function names. Identifiers, on the other hand, are user-defined names that represent variables, functions, classes, or modules in Python.
Answer: No, Python Keywords cannot be used as variable names or function names, as they are reserved for a specific purpose in the Python programming language. If you try to use a keyword as an identifier, you will get a syntax error.
Q. How are Python Keywords useful in programming?
Answer: Python Keywords are useful in programming as they define the structure and syntax of the language, making it easier to write and read Python code. By using keywords, developers can write code that is concise, clear, and easy to understand, and avoid using ambiguous or misleading names for variables and functions.
Q. What are some of the new keywords added in Python 3.10?
Q. Can keywords be imported in Python?
Answer: No, keywords cannot be imported in Python as they are part of the language syntax and cannot be overridden or redefined. If you try to import a keyword, you will get a syntax error.
Q. Are Python Keywords case-sensitive?
Answer: No, Python Keywords are not case-sensitive. For example, you can use “if”, “If”, or “IF” interchangeably in your code.
Q. Can Python Keywords be deleted?
Answer: No, Python Keywords cannot be deleted as they are an integral part of the language syntax and cannot be modified or removed. If you try to delete a keyword, you will get a syntax error.
Q. What is the purpose of the “as” keyword in Python?
Q. What is the keyword for function in Python?
The keyword for defining a function in Python is “def”.
The “def” keyword is followed by the function name, a set of parentheses that may include arguments, and a colon. The body of the function is indented below the “def” statement and includes the code that defines what the function does.
Here’s an example of a simple function that takes two arguments and returns their sum:
def add_numbers(a, b):
sum = a + b
return sum
In this example, “def” is used to define the function named “add_numbers”, which takes two arguments “a” and “b”. The body of the function calculates the sum of the two numbers and returns the result using the “return” keyword.
Q1. What are tokens in Python?
Answer: Tokens are the basic building blocks of Python programs. These building blocks are the smallest individual elements that are combined to create a complete Python program. A Python program consists of several types of tokens such as keywords, literals, identifiers, operators, and punctuations.
Q2. What are the different types of tokens in Python?
Q3. What are keywords in Python?
Answer: Keywords are predefined words in Python that have a specific meaning and cannot be used as identifiers. Python has 35 keywords, and they are reserved for specific uses within the language.
Q4. What are identifiers in Python?
Answer: Identifiers are names given to variables, functions, classes, and other objects in a Python program. An identifier is a user-defined name that is used to identify a particular variable, function, or object in the program.
Q5. What are literals in Python?
Answer: Literals are fixed values in a Python program that are used to represent specific data types. Examples of literals include strings, integers, floating-point numbers, and Boolean values.
Q6. What are operators in Python?
Answer: Operators are symbols that are used to perform operations on variables and literals. Python has several types of operators such as arithmetic operators, assignment operators, comparison operators, logical operators, and more.
Q7. What are punctuations in Python?
Answer: Punctuations are symbols used to structure a Python program. Punctuations are used to indicate the beginning and end of blocks of code, define function arguments, and more.
Q8. How are tokens used in Python code?
Answer: Tokens are used to define the structure and behavior of a Python program. The keywords, identifiers, literals, operators, and punctuations are combined to form a program that performs a specific task.
Q9. What is the importance of understanding tokens in Python?
Q10. What are some best practices for using tokens in Python code?
Answer: Some best practices for using tokens in Python code include using descriptive names for identifiers, following Python naming conventions, using whitespace and indentation to improve readability, and commenting your code to make it easier to understand.
Q11. What is the special literal – None in Python?
Answer: None is a built-in constant in Python that represents the absence of a value. It is used to indicate that a variable has no value or that a function returns no value. None is an object in Python, which means that it has its own data type. The data type of None is NoneType.
Q12. What are the Characteristics of the special literal – None?:
Answer
- None is a built-in constant in Python.
- None is an object in Python.
- None represents the absence of a value.
- The data type of None is NoneType.
- None is falsy, which means that it evaluates to False in Boolean context.
Q13. Explain the Usage of the special literal – None in Python ?:
Answer
- Initializing variables: None is often used to initialize variables that do not have a value at the time of declaration. For example, if we want to declare a variable but do not have a value for it yet, we can initialize it to None.
- Default return value: None is often used as the default return value for functions that do not return a value. For example, if we have a function that performs some operation but does not return a value, we can use None as the default return value.
- Placeholder value: None is often used as a placeholder value in data structures such as lists, dictionaries, and tuples. For example, if we want to create a list with 10 elements but do not have a value for some of the elements yet, we can initialize those elements to None.
- Comparison: None is often used in comparison operations to check if a variable has no value. For example, if we want to check if a variable is None, we can use the comparison operator ‘is’ or ‘is not’.
Q: What is a Python identifier?
Answer : A Python identifier is a name used to identify a variable, function, class, module, or other object in a Python program. Identifiers can be any length and can contain letters, numbers, and underscores, but cannot start with a number.
Q: What are some best practices for naming Python identifiers?
Answer : Some best practices for naming Python identifiers include: using descriptive names that clearly indicate the purpose of the identifier, avoiding reserved words or built-in functions as identifiers, using lowercase letters for variable and function names, and using CamelCase for class names.
Q: How can you check if a given string is a valid Python identifier?
Answer : You can use the built-in isidentifier() method to check if a string is a valid Python identifier. For example: my_string.isidentifier() will return True if my_string is a valid identifier.
Q: Can Python identifiers include spaces?
Answer : No, Python identifiers cannot include spaces. If you need to represent a multi-word name, you can use either underscores between the words, or CamelCase where the first letter of each word is capitalized.
Q: What is the scope of a Python identifier?
Answer : The scope of a Python identifier refers to the region of the program where the identifier can be accessed. Variables defined within a function have local scope, meaning they can only be accessed within that function. Variables defined outside of any function or class have global scope, meaning they can be accessed throughout the entire program.
Q: What are some common mistakes to avoid when naming Python identifiers?
Answer : Some common mistakes to avoid when naming Python identifiers include: using unclear or overly generic names, using variable names that are too similar to each other, using reserved words or built-in functions as identifiers, and using uppercase letters in variable or function names (which should be reserved for class names).
Q: How long can a Python identifier name be?
Answer : In Python, the length of an identifier name can be as long as you want it to be, theoretically. However, it’s generally recommended to keep identifier names reasonably short and descriptive for readability and ease of use.
According to the official Python documentation, an identifier can be any length and can include uppercase and lowercase letters, digits, and the underscore character. However, the identifier cannot start with a digit. Additionally, Python has no limit on the total number of identifiers you can define in a program, although having too many can make your code harder to understand and maintain.
It’s important to note that although Python allows long identifier names, many style guides and best practices recommend keeping identifier names under 79 characters to make code more readable, especially when working with long function or class names. Overall, it’s best to strike a balance between descriptive and concise identifier names to make your code both easy to understand and easy to use.
- Use CamelCase: CamelCase is a naming convention where the first letter of each word is capitalized, and there are no underscores between the words. For example, “myVariable” instead of “my_variable”. This is a common convention used in many programming languages, and can make your code easier to read and understand.
- Use Abbreviations: You can use abbreviations to shorten the length of a multi-word identifier without using underscores. For example, “numEmployees” instead of “num_employees”. Be careful not to use too many abbreviations, as this can make your code less readable.
- Use Descriptive Names: In some cases, you may be able to use a single-word identifier that is descriptive enough to convey the meaning of the variable or function. For example, instead of “my_list_of_numbers”, you could use “numbers”.
Overall, the most important thing is to use descriptive and meaningful names for your identifiers, whether you use underscores or not. This will make your code easier to read and understand for yourself and others who may be working with your code in the future.