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

Python Variables

This document provides an introduction to Python variables and data types. It discusses variables, comments, and basic data types including strings, integers, floats, booleans, lists, dictionaries. For each data type, it demonstrates how to create, read, update and delete values, and provides examples of common operations and methods. The overall purpose is to introduce fundamental Python concepts like variables and basic data types to new Python learners.

Uploaded by

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

Python Variables

This document provides an introduction to Python variables and data types. It discusses variables, comments, and basic data types including strings, integers, floats, booleans, lists, dictionaries. For each data type, it demonstrates how to create, read, update and delete values, and provides examples of common operations and methods. The overall purpose is to introduce fundamental Python concepts like variables and basic data types to new Python learners.

Uploaded by

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

Introduction to Python (Part I)

Variables and data types

Week1

Middlesex University Dubai. Winter ‘23, CST4050


Instructor: Dr. Ivan Reznikov
Plan
Python Basics:
– Variables
– Comments
– Basic Data Types:

String

Integer

Float

Boolean

List

Dictionary
2
Variables
some_answer = 42 42

print(some_answer)
>>>42
some_
answe
print(type(some_answer)) r
>>>int

3
Naming variables
Can you guess what is in each box?

cat c var_
1
Variables: Naming convention

Bad examples Good examples


'l' (lowercase letter “el”), temp_celsius
'O' (uppercase letter “oh”) station_id
'I' (uppercase letter “eye”) current_timestamp

'some_variable'
'NOT_GLOBAL_VAR' ----
'Averagecamelsizeindesert' tempCelsius
'number-of-cans-in-a-sixpack' stationID
'xxrstaqwe' currentTimestamp

5
Basic operations with variables

Create Read Update Delete

6
Comments
# This is a comment before some code '''
print("Hello Python!") multi-row
comment
'''

print("Winter is coming!") # this is an in-line comment

Comments are left to increase the understandability of ones code.


Very often to later version of yourself.

7
Data Type: String my_string = "Burj Khalifa"

my_string[xstart:xend:step] Speed Task:

my_string[0:4] >>>"Burj" my_string[5:] >>>


my_string[2] >>>"r" my_string[4] >>>
my_string[-1] >>>"a" my_string[-0] >>>
my_string[2:-5] >>>"rj Kh" my_string[3:9:2] >>>
my_string[::3] >>>"Bjhi" my_string[::-1] >>>
8
Data Type: String my_string = "Burj Khalifa"

my_string[xstart:xend:step] Speed Task:

my_string[0:4] >>>"Burj" my_string[5:] >>>"Khalifa"


my_string[2] >>>"r" my_string[4] >>>" "
my_string[-1] >>>"a" my_string[-0] >>>"B"
my_string[2:-5] >>>"rj Kh" my_string[3:9:2] >>>"jKa"
my_string[::3] >>>"Bjhi" my_string[::-1]
>>>"afilahK jruB" 9
Data Type: Updating Strings
String concatenation:
string_one = "Expo2020 took"
string_two = "place in 2021"
string_three = string_one + string_two
>>>Expo2020 tookplace in 2021

string_three = string_three + " " + "in Dubai"


>>>Expo2020 tookplace in 2021 in Dubai

string_three += "!"
>>>Expo2020 tookplace in 2021 in Dubai!
10
String methods
dir(my_string)
>>>[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__doc__’, ‘__eq__’, ‘__format__’,
‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__getslice__’, ‘__gt__’,
‘__hash__’, ‘__init__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’,
‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’,
‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘_formatter_field_name_split’,
‘_formatter_parser’, ‘capitalize’, ‘center’, ‘count’, ‘decode’, ‘encode’, ‘endswith’,
‘expandtabs’, ‘find’, ‘format’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isdigit’, ‘islower’, ‘isspace’,
‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’,
‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’,
‘title’, ‘translate’, ‘upper’, ‘zfill’]

11
Data Type: Integers and Floats

Integer: Whole numbers Float: Fraction numbers

my_number = 5 my_number = 5.0


type(my_number) type(my_number)
>>><class 'int'> >>><class 'float'>
int(5.0) float(5)
>>><class 'int'> >>><class 'float'>
my_number += 1 del my_number
>>>6 >>>

13
Data Type: Boolean
Boolean values represent True/False statements.
Often used to check for None, empty strings, list, objects, etc.

my_bool = 2 + 2 == 5
my_bool, type(my_bool)
>>>False, <class 'bool'>

bool(False), bool(None), bool(0), bool(""), bool(()), bool([]), bool({})


>>>False, False, False, False, False, False, False

bool(True), bool(1), bool("a"), bool((b)), bool([c]), bool({"d":"e"})


>>>True, True, True, True, True, True

14
Data Type: List
my_string = [4,8,15,16,23,42]

my_list[xstart:xend:step] my_list[0] = 1
my_list[0] >>>4 >>>[1, 8, 15, 16, 23, 42]
my_list[-1] >>>42
my_list[1:4] >>>[8, 15, 16] my_list = my_list + [100]
my_list[3:] >>>[16, 23, 42] >>>[1, 8, 15, 16, 23, 42, 100]
my_list[::-1] >>>[42, 23, 16, 15, 8, 4]
my_list[:] >>>[4, 8, 15, 16, 23, 42] del my_list[-2]
>>>[1, 8, 15, 16, 23, 100]
15
List methods
dir(my_list)
>>>['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__',
'__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__',
'__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__',
'__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

16
Data Type: Tuple
my_tuple = (16,2,4,8)

my_tuple[0] = 0 Tuples are immutable.


>>>TypeError: 'tuple' object Neither they, nor their elements
does not support item assignment can be changed.

my_tuple.append(0) Tuples are ordered. Their order


>>> AttributeError: 'tuple' won’t change. They maintain
object has no attribute 'append' the order of data insertion.

my_tuple[-1] >>>8
my_tuple[1:3] >>>(2, 4)

17
Data Type: Set
my_set = {1, 2, 4, 8, 16, 32}

my_set = {16,1,2,32,2,2,4,8,16,1,1} Sets contain unique values.


>>>{1, 2, 4, 8, 16, 32} Duplicate values are not
allowed.
my_set.add(5.0)
my_set.add(False) Sets are immutable.
>>>{False, 1, 2, 4, 5.0, 8, 16} Their elements cannot be
changed.
my_list = [8, 2, 2, 3, 1, 1, 4, 5, 5, 7, 8]
my_set = set(my_list) Sets are unordered. They don’t
>>> {1, 2, 3, 4, 5, 7, 8} maintain the order of data
insertion.
18
Data Type: Dictionary my_dictionary = {
"name" : "Burj Khalifa",
"height_m" : 830,
my_dictionary["name"]
"completed" : True
>>>”Burj Khalifa”
}
my_dictionary.keys()
{
>>>dict_keys(['name', 'height_m',
"key": "value"
'completed'])
}
Keys are unique within a
my_dictionary.values()
dictionary
>>>dict_values(['Burj Khalifa', 830, True])
Dictionaries are ordered
by key, not maintaining
initial order
19
Data Type: Dictionary
my_dictionary = {
my_dictionary['height_m'] = 829.8 "name" : "Burj Khalifa",
"height_m" : 830,
my_dictionary['hashtags'] = ["#burjkhalifa", "completed" : True
"#dubai", "#uae", "#dubaimall"] }

del my_dictionary['completed']

>>>{
"name" : "Burj Khalifa",
"height_m" : 829.8,
"hashtags" : ["#burjkhalifa",
"#dubai", "#uae", "#dubaimall"]
}
20
Dictionary methods
dir(my_dictionary)
>>>['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__',
'__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear',
'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update',
'values']

21
Data Type comparison

You might also like