0% found this document useful (0 votes)
20 views9 pages

Lab Session 2

Uploaded by

zoyashad3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views9 pages

Lab Session 2

Uploaded by

zoyashad3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

CSS 1021

Programming Fundamentals
BS 2021
Department of CS andSE

Lab Session 2: Variables and Standard Data Types

Learning Outcomes
After this lab, students will be able to:

• Perform variable declarations in Python


• Use variables appropriately to refer data
• Understand different data types available in python
• Learn how to read data from user

Variables
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in
the reserved memory. Therefore, by assigning different data types to variables, you can store integers,
decimals or characters in these variables.

Creating Variables with Assignment Statements


You use an assignment statement to create a variable in Python. Here is an example of an assignment
statement:
age = 25
After this statement executes, a variable named age will be created and it will reference the value 25. The
arrow that points from age to the value 25 indicates that the name age references the value.

An assignment statement is written in the following general format:


Variable = expression

The equal sign (=) is known as the assignment operator. In the general format, variable is the name of a
variable and expression is a value, or any piece of code that results in a value. After an assignment
statement executes, the variable listed on the left side of the = operator will reference the value given on
the right side of the = operator.
In an assignment statement, the variable that is receiving the assignment must appear on the left side of
the = operator. For example, the following statement will cause an error: 25 = age # this is an error!

Assigning Values to Variables


Python variables do not need explicit declaration to reserve memory space. The declaration happens
automatically when you assign a value to a variable. The equal sign (=) is used to assign values to
variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of the =
operator is the value stored in the variable. For example
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

Example
counter = 100 # An integer assignment
miles = 1000.0 # A floating point name
= "John" # A string print counter print
miles print name
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables, respectively.
Program Output
100
1000.0
John

Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables. For example
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.

Python Data Types


The data stored in memory can be of many types. For example, a person's age is stored as a numeric
value and his or her address is stored as alphanumeric characters. Data types are the classification or
categorization of data items. Python supports the following built-in data types.

Scalar Types

• int: Positive or negative whole numbers (without a fractional part) e.g. -10, 10, 456, 4654654.
• float: Any real number with a floating-point representation in which a fractional component is
denoted by a decimal symbol or scientific notation e.g. 1.23, 3.4556789e2.
• complex: A number with a real and imaginary component represented as x + 2y.
• bool: Data with one of two built-in values True or False. Notice that 'T' and 'F' are capital. true
and false are not valid Booleans and Python will throw an error for them.
• None: The None represents the null object in Python. A None is returned by functions that don't
explicitly return a value.

Sequence Type

A sequence is an ordered collection of similar or different data types. Python has the following builtin
sequence data types:
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

• String: A string value is a collection of one or more characters put in single, double or triple
quotes.
• List: A list object is an ordered collection of one or more data items, not necessarily of the same
type, put in square brackets.
• Tuple: A Tuple object is an ordered collection of one or more data items, not necessarily of the
same type, put in parentheses.

Mapping Type

Dictionary: A dictionary Dict() object is an unordered collection of data in a key:value pair form. A
collection of such pairs is enclosed in curly brackets. For example: {1:"Steve", 2:"Bill", 3:"Ram", 4:
"Farha"}

Set Types

• set: Set is mutable, unordered collection of distinct hashable objects. The set is a Python
implementation of the set in Mathematics. A set object has suitable methods to perform
mathematical set operations like union, intersection, difference, etc.
• frozenset: Frozenset is immutable version of set whose elements are added from other iterables

Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.
For example var1 = 1 var2 = 10
Python supports four different numerical types
• int (signed integers)
• long (long integers, they can also be represented in octal and hexadecimal)
• float (floating point real values)
• complex (complex numbers)

Example
x = 1 # int y =
2.8 # float z = 1j
# complex

To verify the type of any object in Python, use the type() function:
print(type(x)) print(type(y))
print(type(z))

Program Output
<class 'int'>
<class 'float'>
<class 'complex'>
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice
operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and working their way from
-1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator.
Example
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string print
str[2:5] # Prints characters starting from 3rd to 5th print
str[2:] # Prints string starting from 3rd character print
str * 2 # Prints string two times print str + "TEST" #
Prints concatenated string

Program Output
Hello World! H
llo llo
World!
Hello World!Hello World!
Hello World!TEST

Data Type Conversion


Sometimes, you may need to perform conversions between the built-in types. To convert between types,
you simply use the type name as a function.
There are several built-in functions to perform conversion from one data type to another. These functions
return a new object representing the converted value.

Python has two types of type conversion.

• Implicit Type Conversion


• Explicit Type Conversion

Implicit Type Conversion


In Implicit type conversion, Python automatically converts one data type to another data type. This
process doesn't need any user involvement.
Let's see an example where Python promotes conversion of lower datatype (integer) to higher data type
(float) to avoid data loss.
Example 1
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("answer of num_new:",num_new)
print("datatype of num_new:",type(num_new))

Program Output
datatype of num_int: <class 'int'>
datatype of num_flo: <class 'float'>
answer of num_new: 124.23
datatype of num_new: <class
'float'>

Example 2

num_int = 123
num_str = "456"

print("Data type of
num_int:",type(num_int)) print("Data type
of num_str:",type(num_str))
print(num_int+num_str)

Program Output
Data type of num_int: <class 'int'>
Data type of num_str: <class 'str'>
Traceback (most recent call last):
File "python", line 7, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object to required data type. We use the
predefined functions like int(), float(), str(), etc to perform explicit type conversion.
This type conversion is also called typecasting because the user casts (change) the data type of the
objects.
Syntax
(required_datatype)(expression)

Typecasting can be done by assigning the required data type function to the expression.
Example
num_int = 123
num_str = “456”
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str

print("Sum of num_int and


num_str:",num_sum) print("Data type of the
sum:",type(num_sum))

Program Output
Data type of num_int: <class 'int'>
Data type of num_str before Type Casting: <class 'str'>
Data type of num_str after Type Casting: <class 'int'>
Sum of num_int and num_str: 579
Data type of the sum: <class 'int'>

User Input
Python allows for user input. That means we are able to ask the user for input. The method is a bit
different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the
raw_input() method.
Example
The following example asks for the username, and when you entered the username, it gets printed on the
screen:
Python 3.6 username = input("Enter
username:") print("Username is: " +
username) Python 2.7
username = raw_input("Enter username:")
print("Username is: " + username)

Program Output
Enter username:

After typing name


Username is: Anisa
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

Exercises
1. Create a variable named carname and assign the value Volvo to it.
2. Create a variable named x and assign the value 50 to it.
3. Input variables x, y and z. Assign values to the variable and display it in the following format. Use
inline comments in the program.
x y z
3 6 8
4. Which of the following are illegal variable names in Python, and why?
• x
• 99bottles
• july2009
• theSalesFigureForFiscalYear
• r&d
• grade_report

5. What will the following code display? val = 99


print('The value is', 'val')

6. What will be displayed by the following program? my_value = 99 my_value = 0


print(my_value)

7. Write a program in which you have to input your information and make variables to store the
following information:
• Your name
• Your address, with city, state, and ZIP
• Your telephone number  Your department

Print the following information in the following format:


Name: yourName City:yourCity
Contact: yourNumber State:yourState
Department:yourDepartment Zip:AreaCode

8. Input two variable first name and last name. Assign values to it and print the full name.

9. Write a Python program which accepts the user's first and last name and print them in reverse order
with a space between them.
10. Make any two variables and assign integer and float value to it and print the values. Output should be
in the following form:
CSS 1021
Programming Fundamentals
BS 2021
Department of CS andSE

The “int” value is 9


The “float” value in 5.78
CSS 102
Programming Fundamentals
BS 2021
Department of CS andSE

11. What type of value is 3.4? How can you find out?

12. Insert the correct syntax to convert x into a floating point number. x = 5

13. What type of value (integer, floating point number, or character string) would you use to represent each
of the following?
• Number of days since the start of the year.
• Time elapsed from the start of the year until now in days.
• Serial number of a piece of lab equipment.
• Average population of a city over time.

You might also like