Lab Session 2
Lab Session 2
Programming Fundamentals
BS 2021
Department of CS andSE
Learning Outcomes
After this lab, students will be able to:
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.
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!
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.
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
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'
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
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:
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
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
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
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.