Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
36 views

Python Variables and Collections Declaration and Operations: 1 Lab Overview

This document provides instructions for a lab on declaring variables and using collections in Python. It discusses how to create variables, assign values, perform operations, and cast variable types. It also covers different collection types like lists, tuples, sets, and how to access and manipulate items within collections. Built-in methods for lists are also summarized in a table. Students are instructed to write code examples in a Python file to create variables, use operators, and work with collections to learn fundamental Python concepts.

Uploaded by

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

Python Variables and Collections Declaration and Operations: 1 Lab Overview

This document provides instructions for a lab on declaring variables and using collections in Python. It discusses how to create variables, assign values, perform operations, and cast variable types. It also covers different collection types like lists, tuples, sets, and how to access and manipulate items within collections. Built-in methods for lists are also summarized in a table. Students are instructed to write code examples in a Python file to create variables, use operators, and work with collections to learn fundamental Python concepts.

Uploaded by

Renas Dareesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Variables and Collections Declaration and

Operations
Department of Computer Science
University of Zakho
Third Year Students
Compiler Design (Practical Part)

October 2, 2020

1 Lab Overview
In this lab, students will learn how to declare variables and collections in
python. Then different operations on variables and collections will be given.
Please follow the instructions given below.

2 Creating Variables in Python


Variables are containers for storing data values. Unlike other programming
languages, Python has no command for declaring a variable. A variable is
created the moment you first assign a value to it. In this lab, students will
be learn how to declare variables and use them in different operation using
python. Start this lab by writing a program Lab2_variables.py with the
following code:
1 x = 5
2 y = " John "
3 print ( x +4)
4 print ( y )

print is used to display result in python. Run the code and see result.
Variables do not need to be declared with any particular type and can even
change type after they have been set. Example: change above code to the
following:
1 x = 6
2 x = " Hello "
3 print ( x )

Which value of x is printed (Hello or 6) why ?

1
2.1 Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total volume). Rules for Python variables, are the following:

• A variable name must start with a letter or the underscore character

• A variable name cannot start with a number

• A variable name can only contain alpha numeric characters and un-
derscores (A − z, 0 − 9, and underscores )

• Variable names are case-sensitive (age, Age and AGE are three differ-
ent variables)

2.2 Assign Value to Multiple Variables


Python allows you to assign values to multiple variables in one line. Add
the following code into to the Lab2_variables.py .
1 x ,y , z = " Orange " , " Banana " , " Cherry "
2 print ( x )
3 print y )
4 print ( z )

In this case: x = "Orange", y = "Banana", z = "Cherry". You can assign


the same value to multiple variables in one line. Add the following code into
the Lab2v ariables.py and see results.
1 x = y = z = " Orange "
2 print x )
3 print ( y )
4 print ( z )

2.3 Casting Variables


Casting variable is used when you want to assign variables with different
types. For examples:
1 x = float (1) # x will be 1.0
2 y = float (2.8) # y will be 2.8
3 z = float ( " 3 " ) # z will be 3.0
4 w = float ( " 4.2 " ) # w will be 4.2
5 s = str ( " 545 " ) # w will be " 545 "
6 n = int ( s ) # convert s into int
7 print ( x +6)
8 print ( y +7.8)
9 print ( z +6.0)
10 print ( w +5)
11 print ( s + str (2) )
12 print ( n )

Add this code into the Lab2.py and see results.

2
2.4 Expressions Using Different Variables
Variables are used to create expressions using different operations. Change
given code to include the following:
1 x = 5
2 y = 4
3 z = 2
4 x = x + y *(3+ z )
5 print ( x )
6 x = y = ((3+ x ) +( z -2) *5)
7
8 print ( x )
9 print ( y )
10 m = x // 5 # // is div in python
11 print ( m )
12 n = x % 5 # % is mod
13 print ( n )
14 k = x ** 2
15 print ( k )

Try to write more complex expressions and print results.

2.5 Python Comparison Operators


Python has the following comparison operators. Add the following code and
see results. Then change comparisons operators and see results.
1 x = 6
2 y = 5
3 print (x > y ) # if x > y then true , otherwise false
4 print (x < y ) # if x < y then true , otherwise false
5 print ( x == y ) # if x == y then true , otherwise false
6 print ( x >= y ) # if x >= y then true , otherwise false
7 print ( x != y ) # if x != y then true , otherwise false

2.6 Python Logical Operators


Python has the following Logical operators. Add the following code:
1 print (x > y and x >2) # and
2 print (x < y or x <4 ) # or
3 print ( not x == y ) # not

2.7 Python Membership Operators


Membership operators are used to test if a sequence is presented in an object.
At the end of the program, add the following code.
1 x = [ " apple " , " banana " ]
2 print ( " banana " in x ) # in
3 print ( " pineapple " not in x ) # not in

3
3 Collections in Python
When choosing a collection type, it is useful to understand the properties
of that type. Choosing the right type for a particular data set could mean
retention of meaning, and, it could mean an increase in efficiency or security.
In this lab, it will be shown how Lists, tuple and sets can be implemented
in Python, based on different operations.
Start this by writing a new python file with name Lab2_collections.py.
Add code given in each section into this file and see corresponding results.
You can change the code as you wish and ask lab assistants, if you get any
problems.
In programming, data type is an important concept. Variables can store
data of different types, and different types can do different things. Python
has the following data types built-in by default:

• string: is any thing between”and”orbetween0 and0 .


1 x = " Hello "
2 print ( x )

• Integer: is a number which consists of combination of ([0 − 9])


1 x = 66
2 print ( x )

• Float: is number.number
1 x = 6.8
2 print ( x )

• Bool: is True or False


1 x = True
2 print ( x )

• List: is a list of objects. These object can be from the same or different
types.
1 x = [ 4 ,5 , " 6 " ,[4 ,6]]
2 print ( x )
3

• Tuple: is (object1, object2, ....)


1 x = (6.8 ,5)
2 print ( x )

• Set: is { object1, object2, .... }


1 x = {6 ,2}
2 print ( x )

4
• Range(n): is 0, 1, 2, ..., n
1 x = range (5)
2 print ( x )

3.1 Type of Objects in Python


To verify the type of any object in Python, use the type(object). Add the
following code into Lab2_collections.py and see results.
1 x = range (5)
2 y = 5
3 z = [4 ,3 ,2]
4 print ( type ( x ) )
5 print ( type ( y ) )
6 print ( type ( z ) )

You must see this result:


1 < class ’ range ’ >
2 < class ’ int ’ >
3 < class ’ list ’ >

3.2 Creating Collection


Lists, tuples and sets can be created based on given set of numbers. For
example, the following code generates list l, tuple t and set s based on x.
Add this code into the given code and see result.
1 x = range (20) # creating a 0 ,1 ,2 ,3 ,... ,19
2 l = list ( x ) # a list of 20 numbers [0 ,1 ,2 ,... 19]
3 t = tuple ( x ) # a tuple of 20 numbers (0 ,1 ,2 ,... 19)
4 s = set ( x ) # a set of 20 numbers {0 ,1 ,2 ,... 19}
5 print ( x )
6 print ( l )
7 print ( t )
8 print ( s )

3.3 Access Items


Square brackets can be used to access items of the string,lists, tuple. How-
ever, set needs some operations to access times. Dictionaries need keys to
access their items.
Square brackets [index] can be used to print any characters from the
string,lists,tuples. Positive indexes starting from the first of the given col-
lection, while negative indexes from the last item in the given collection.
The last item is indexed by -1. The first item is indexed by 0. Add this
code into Lab2_collections.py and see what results will you get, ask if
anything is not clear.

5
1 s = " Hello5161 "
2 l = [1 ,2 ,3 ,4 ,5]
3 t = ( " Ali " ," Ahmed " , " Rame " )
4 set = {2.3 ,4.4 ,5.6}
5
6 # Printing first items ([0]) ( str is used to convert integers
to string )
7 print ( " First item in s is : " + s [0])
8 print ( " First item in l is : " + str ( l [0]) )
9 print ( " First item in T is : " + t [0])
10
11 # Printing last items [ -1]
12 print ( " Last item in s is : " + s [ -1])
13 print ( " Last item in l is : " + str ( l [ -1]) )
14 print ( " Last item in t is : " + t [ -1])
15
16 # Printing item indexed at i
17 i = 4
18 print ( str ( i ) + " item is : " + s [ i ])

Table 1: Built-in methods for lists in Python.


Built in Function Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified p
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

3.4 How to Join Two Tuples


t3 = t1 + t2 This will add t2 to to end of the t1. Add this code into
Lab2_collections.py and see how tupes are merged.
1 t1 = ( " Ali " ," Ahmed " , " Rame " )
2 t2 = (1 ,2 ,3)
3 t3 = t1 + t2
4 print ( t3 )

6
3.5 Printing a range of items in Collections (Lists and Tu-
ples)
[first:last] is used to print a range of items starting from the index first (first
is included) to the index last (index last not included). Positives indexes
starting from the first item in the tuple. Negative indexes meaning starting
from the end.
Add this code and see results. Then, you can use different indexes and
see corresponding results. Ask if you need help.
1 # Printing a range of items in Lists and tuples
2 t = (1 ,2 ,3 ,4 ,5 ,6)
3 l = [5 ,7 ,8 ,8 ,9]
4 print ( t [2:4])
5 print ( t [ -4: -2])

3.6 Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are unchange-
able.In order to change tuple, you can convert the tuple into a list, change
the list, and convert the list back into a tuple.
Add this code and see what will you get.
1 # Changing tuples
2 t = (1 ,2 ,3 ,4 ,5 ,6)
3 t [1] = 4
4 print ( t )

You will see an error. Look at the error and see what it is. Then delete
above code and add the following:
1 # Changing tuples using lists
2 t = (1 ,2 ,3 ,4 ,5 ,6)
3 l = list ( t )
4 l [2] = 9
5 t = tuple ( l )
6 print ( t )

You can see that t has been changed without errors.

Table 2: Built-in methods for Tuple in Python.


Built in Function Description
index() Returns the index of the first element with the specified value
count() Returns the number of times a specified value occurs in a tuple

7
3.7 Sets Collections

Table 3: Built-in methods for Sets in Python.


Built in Function Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between sets
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
union() Return a set containing the union of sets
update() Update the set with the union of this set and others

Add the following code into Lab2_collections.py to see how data can
be added into sets and how sets are merged.
1 # sets and their methods
2 s1 = {1 ,2 ,4 ,5 ,6}
3 s2 ={ " a " ," b " ," c " }
4 print ( s1 )
5 s3 = s1 . union ( s2 )
6 s4 = {4 ,5 ,6 ,7 ,8}
7 s5 = s1 . union ( s4 ) # all items in both sets with no repeating (
duplicating )
8 s6 = s1 . intersection ( s4 ) # Items sharing both sets
9 print ( s3 )
10 print ( s5 )
11 print ( s6 )

You can see that when merging two sets having similar items, only one
of such items are in the result. See result of print(s5).

4 More work to do in the lab


If time permits,do the following:
1. Write an expression to find ab . For example, a = 3, b=2 then result
= 32 = 9.

2. Write a code to print True if a > b and a > c , otherwise print False.
Use logical operators.

8
3. If you get time, apply methods given in the table 3 on sets, by changing
given code.

You might also like