0% found this document useful (0 votes)
3 views

AI Lab 01

This document provides a practical guide for students to familiarize themselves with basic Python constructs, including setting up the development environment, understanding Python syntax, keywords, identifiers, and data types. It outlines steps for creating a first program in Visual Studio Code and explains Python statements, indentation, comments, variables, and operators. Additionally, it includes exercises for students to practice their skills in Python programming.

Uploaded by

Taha Aamir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

AI Lab 01

This document provides a practical guide for students to familiarize themselves with basic Python constructs, including setting up the development environment, understanding Python syntax, keywords, identifiers, and data types. It outlines steps for creating a first program in Visual Studio Code and explains Python statements, indentation, comments, variables, and operators. Additionally, it includes exercises for students to practice their skills in Python programming.

Uploaded by

Taha Aamir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Practical # 01

Getting Familiar with Basic Constructs of Python


Tools: Python, Visual Studio Code.
Objective: In this practical lab, the students will be able to learn the:
i. To setting up the developer environment for python
ii. The basic syntax of python language
iii. The basic constructs

1. Introduction to Python:
Python has become one of the most popular programming languages in the world in recent
years. It was created by Guido van Rossum, and released in 1991. It's used in everything from
machine learning to building websites and software testing. It can be used by developers and
non-developers alike. Python, one of the most popular programming languages in the world,
has created everything from Netflix’s recommendation algorithm to the software that controls
self-driving cars. Python is a general-purpose language, which means it’s designed to be used in
a range of application including:
data science, software and web development, automation, and generally getting stuff
done. Python is designed to be highly readable. It uses English keywords frequently. The
alternative are low- level languages, whose instructions are tied to a specific computer architecture
and consist of either numbers or special, non-intuitive four or five letter instructions. Obviously,
we prefer to program in high-level languages. Such languages not only make the programming
process faster, they also make programs easier to debug, and easier to extend and maintain. It
has fewer syntactical constructions than other languages. Python also allows very powerful
programs to be created with much less effort than some other programming languages. So even
though it is a good beginning language, it is also a powerful tool for application development.

2. Setting Up the Environment for Python:


To setup the developer environment for python we must follow the steps given below:

1
Step 01: Open your browser, in the address bar, type www.pyhton.org/downloads/

Step # 02: Download the latest available version of python interpreter and then install it.

Step # 03: Now, after successfully installing python interpreter into your computer, you have to
assure it by using the following command:

Step # 04: Open your browser, in the address bar, type https://code.visualstudio.com/download

2
Step # 05: Download the latest available version of Microsoft Visual Studio Code IDE and then
install it.

3
Step # 06: Install the Python Extension from Microsoft Visual Studio Code, to create, save and
execute the python files. Choose the first option from the suggested list, as shown in the figure given
below:

3. Creating First Program in Microsoft Visual Studio Code:


Step # 01: First, go into file menu, and create a new file.
Step # 02: Save that file with the file name and extension E.g. firstProgram.py
Step # 03: After saving that file, write a python code into it, then execute it.
Step # 04: To execute the python code, there is play button given on the top right corner of the
window.
Step # 05: After executing the program, the output is display in the terminal window.
The sample program and its output is shown in the figure given below:

4
4. Python Keywords and Identifiers:

4.1 Python Keywords:


Keywords are the reserved words in Python. We cannot use a keyword as a variable name,
function name or any other identifier. They are used to define the syntax and structure of the
Python language.
In Python, keywords are case sensitive. There are 33 or 35 keywords in Python depending on
version. This number can vary slightly over the course of time.
All the keywords except True, False and None are in lowercase and they must be written as they
are. Write help (“keywords”).
The list of all the keywords is given below:

S. No. Keyword Description 2 as To create an alias

1 and A logical operator 3 assert For debugging

5
To import specific parts
S. No. Keyword Description 15 from
of a module

To declare a global
4 break To break out of a loop 16 global
variable

To make a conditional
5 class To define a class 17 if
statement

To continue to the next


6 continue 18 import To import a module
iteration of a loop

To check if a value is
7 def To define a function 19 in present in a list, tuple,
etc.

8 del To delete an object To test if two variables


20 is
are equal
Used in conditional
9 elif To create an anonymous
statements, same as else if 21 lambda
function
Used in conditional
10 else
statements 22 None Represents a null value

Used with exceptions,


11 except what to do when an To declare a non-local
23 nonlocal
exception occurs variable

Boolean value, result of


12 False 24 not A logical operator
comparison operations

Used with exceptions, a


block of code that will be 25 or A logical operator

13 finally executed no matter if


A null statement, a
there is an exception or
26 pass statement that will do
Not
nothing

14 for To create a for loop

6
27 raise To raise an exception 31 while To create a while loop

To exit a function and Used to simplify


28 return 32 with
return a value exception handling

Boolean value, result of To end a function,


29 True 33 yield
comparison operations returns a generator

To make a try...except
30 try
statement

4.2 Python Identifiers:


An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
Rules for Writing Identifiers:
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or
digits (0 to 9) or an underscore_.
2. An identifier cannot start with a digit. Ex: 1variable is invalid, but variable1 is a valid name.
3. Keywords cannot be used as identifiers.
4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.
5. An identifier can be of any length.
Things to Remember:
Python is a case-sensitive language. This means, Variable and variable are not the same. Always
give the identifiers a name that makes sense. While c = 10 is a valid name, writing count =
10 would make more sense, and it would be easier to figure out what it represents when you look
at your code after a long gap. Multiple words can be separated using an underscore,
like this_is_a_long_variable.

5. Python Statement, Indentation and Comments:

7
5.1 Python Statement:
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is an
assignment statement. if statement, for statement, while statement, etc. are other kinds of
statements.
Multi-Line Statement:
In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\). For example:

In Python, line continuation is implied inside parentheses (), brackets [ ], and braces { }. For
instance, we can implement the above multi-line statement as:

Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [
] and { }. For example:

We can also put multiple statements in a single line using semicolons, as follows:

5.2 Python Indentation:


Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.
A code block (body of a function, loop, etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout
that block. Generally, four whitespaces are used for indentation and are preferred over tabs
8
.

5.3 Python Comments:


Comments are very important while writing a program. They describe what is going on inside a
program, so that a person looking at the source code does not have a hard time figuring it out.
You might forget the key details of the program you just wrote in a month's time. So taking the
time to explain these concepts in the form of comments is always fruitful.
In Python, we use the hash (#) symbol to start writing a comment.
It extends up to the newline character. Comments are for programmers to better understand a
program. Python Interpreter ignores comments.

Another way of doing this is to use triple quotes, either ' ' ' or " " ".

6. Python Variables:
A variable is a named location used to store data in the memory. It is helpful to think of variables as
a container that holds data that can be changed later in the program. For example:

9
Here, we have created a variable named number. We have assigned the value 34 to the variable. You
can think of variables as a bag to store books in it and that book can be replaced at any time.

Initially, the value of number was 34. Later, it was changed to 35.9.

1
0
6.1 Assigning values to Variables in Python:
As you can see from the above example, you can use the assignment operator = to assign a value
to a variable.

Example 1: Declaring and assigning value to a variable.

Output:

In the above program, we assigned a value python.com to the variable website. Then, we printed
out the value assigned to website i.e. python.com.

Example 2: Assigning multiple values to multiple variables.

Output:

If we want to assign the same value to multiple variables at once, we can do this as:

6.2 Constants:
A constant is a type of variable whose value cannot be changed. It is helpful to think of constants
as containers that hold information which cannot be changed later. You can think of constants as
a bag to store some books which cannot be replaced once placed inside the bag.

11
Assigning value to constant in Python:
In Python, constants are usually declared and assigned in a module. Here, the module is a new
file containing variables, functions, etc. which is imported to the main file. Inside the module,
constants are written in all capital letters and underscores separating the words.

Example 1: Declaring and assigning value to a constant.


Create a constant.py:

Create a firstProgram.py:

Output:

In the above program, we create a constant.py module file. Then, we assign the constant value to
PI, GRAVITY and RADIUS. After that, we create a firstProgram.py file and import the
constant module. Finally, we print the constant value.

7. Python Data Types:


Every value in Python has a datatype. There are various data types inPython. Some of the
important types are listed below:
Text Type Str
Numeric Types int, float, complex
Sequence Types list, tuple
Mapping Type Dict
Boolean Types True , False
Binary Types bytes, bytearray, memoryview

7.1 Getting the Data Type:


You can get the data type of any object by using the type() function:
Example 1: Print the data type of the variable x:

Output:

7.2 Setting the Data Type:


In Python, the data type is set when you assign a value to a variable:

8. Python Operators:
Operators are special symbols in Python that carry out arithmetic or logical computation. The value
that the operator operates on is called the operand.
Example: 2 + 3 = 5.
Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the output of the
operation.
Python divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators

13
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

8.1 Python Arithmetic Operators:


Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
8.2 Python Assignment Operators:
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3

14
8.3 Python Comparison Operators:
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y

8.4 Python Logical Operators:


Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is true x < 5 or x < 4
not Reverse the result, returns False if the result is not(x < 5 and x < 10)
True

8.5 Python Identity Operators:


Identity operators are used to compare the objects, not if they are equal, but if they are the same
object, with the same memory location:
Operator Description Example
Returns True if both variables are the same
is x is y
Object
Returns True if both variables are not the same
is not x is not y
Object

8.6 Python Membership Operators:


Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
Returns True if a sequence with the specified
in x in y
value is present in the object
Returns True if a sequence with the specified
not in x not in y
value is not present in the object

15
8.7 Python Bitwise Operators:
Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shift left by pushing zeros in from the right and let
the leftmost bits fall off
>> Signed right shift Shift right by pushing copies of the leftmost bit in
from the left, and let the rightmost bits fall off

16
Exercise

Write Python Programs for the following problems:

1. Print “your name and your roll number”.


2. Take any two numbers from the user and perform addition, subtraction,
multiplication,division on those numbers then finally display the result.

3. Write a program using multi line statement.


4. Find the square root of a number.
5. Take the radius of the circle from the user and display the diameter, area and
circumferenceof the circle.
6. Take input values from the user for ‘a’, ‘b’ and ‘c’ and apply the quadratic formula, then
display the real and/or complex solutions.
7. Design any program using all comparison operators.

17
18

You might also like