Lesson 2: Variables, assignments, & Simple input
Variables are nothing but reserved memory locations to store values. It means
that when you create a variable, you reserve some space in the 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 the variables, you can store integers, decimals or
characters in these variables.
Data Types
Python has five standard data types-
a) Numbers (integers, float, and complex numbers)
b) String
c) List
d) Tuple
e) Dictionary
Numbers
Number data types store numeric values. They are immutable data types. This
means, changing the value of a number data type results in a newly allocated
object. Number objects are created when you assign a value to them.
Homework:
Practice using mathematical functions on numbers
Strings
A string as a contiguous set of characters represented in the quotation marks.
Python allows either pair 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 to the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator. For example-
name = 'Meru # Assign a string literal to a variable
University'
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 + " # Prints concatenated string
A. Irungu
Library")
Homework:
Practice using string functions & operations
Lists
A list contains items separated by commas and enclosed within square
brackets ([]). To some extent, lists are similar to arrays in C. One of the
differences between them is that all the items belonging to a list can be of
different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes starting at 0 in the beginning of the list and working their way to
end -1. The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator. For example-
List = ['peter', 22, 7.5, # Create a list
'cow']
fruits = ['lemon', 'bananas'] # Create a second list
print (list) # Prints the first list
print (list[0]) # Prints the first element of first
list
print (list[1:3]) # Prints elements of the first list,
starting from 2nd till 3rd
print (list[2:]) # Prints elements of the first list
starting from 3rd element
print (list * 2) # Prints the first list twice
print (list + fruits) # Prints concatenation of the two lists
Homework:
Practice on list functions & operations
Tuples
A tuple is sequence data type consisting of a number of values separated by
commas.
The main difference between lists and tuples is while elements in a lists are
enclosed in brackets ( [ ] ) and their elements and size can be changed, while
elements in a tuple are enclosed in parentheses ( ( ) ) and cannot be updated.
Tuples can be considered as read-only lists. For example-
tuple = ('peter', 22, 7.5, # Create a first tuple
'cow')
A. Irungu
fruits = ('lemon', 'bananas') # Create a second tuple
print (tuple) # Prints the first tuple
print (tuple[0]) # Prints 1st element of the first
tuple
print (tuple[1:3]) # Prints elements of the first tuple
starting from 2nd till 3rd
print (tuple[2:] # Prints elements of the first tuple
starting from 3rd element
print (fruits * 2) # Prints of the first tuple twice
print (tuple + fruits) # Prints concatenation of the two
tuples
Homework:
Practice on tuple functions & operations
Dictionary
A dictionary work like associative arrays or hashes, and consist of key-value
pairs. A dictionary key can be almost any data type, but are usually numbers
or strings. Values, on the other hand, can be any arbitrary object in Python.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and
accessed using square braces ([]). For example-
mydict = {'name': 'peter','staffno':1261, 'dept': 'HR'}
print (mydict['staffno']) # Prints value for 'staffno' key
print (mydict) # Prints complete dictionary
print (mydict.keys()) # Prints all the keys
print (mydict.values()) # Prints all the values
Elements in a dictionary are not ordered, or simply put, order is of no
importance!
Homework:
Practice on dictionary functions & operations
Data Type Conversion
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.
Function Description
int(x [,base]) Converts x to an integer. The base specifies the base
A. Irungu
if x is a string.
float(x) Converts x to a floating-point number.
str(x) Converts object x to a string representation.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,
value) tuples.
chr(x) Converts an integer to a character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
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.
e.g.
name="peter" # A string
num2=100 # An integer
weight=67.50 # A float
isMale=True # A bolean
Python allows assigning of a single value to several variables simultaneously.
e.g. num1=num2=num3=100
or multiple objects to different variables.
e.g. name, num2, weight ="peter", 100, 67.50
Assigning Values from User Input
Python allows assigning a value to a variable from an input entered by a user.
Example
name=input ("Enter your name: ")
The input is always treated as a string. Thus, the input must be converted
before assigning to a different variable type.
Homework:
Practice on date & time functions and operations
Try out the following
import calendar as cal
print (cal.calendar(2022))
A. Irungu