Python
Data
- All data in a Python program is stored in objects.
- These objects have three components: id, type, and value.
- Each object has a unique identifier.
- Object’s type determines what functions can operate on that particular data type
print(id(50))
print(type(50))
Variables
- A Python variable is not an object and does not actually store data; it stores an id that refers to an object that stores data.
- Python standard for naming varibale is to use underscore.
Determining types of data values
print(type('hello'))
print(type(1))
print(type(1.64))
print(type(True))
Printing
- Syntax:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
print('My name is Ambreen.')
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output Formatting
x = 5; y = 10
print('The value of x is {} and y is {}'.format(x,y))
# Output: The value of x is 5 and y is 10
print('I like {0} and {1}'.format('mango','orange'))
# Output: I like mango and orange
print('Hello {name}, {greeting}'.format(greeting = 'Good Morning', name = 'John'))
# Output: Hello John, Good Morning
x = 12.3456789
print('The value of x is %3.2f' %x)
# Output: The value of x is 12.35
print('The value of x is %3.4f' %x)
# Output: The value of x is 12.3457
Type Casting
a = int(1) # a will be 1
b = int(2.5) # b will be 2
c = int("3") # c will be 3
#c1 = int("3.4") # c1 will be... This will result in an error; replace it with below statement to work:
c1 = int(float("3.4"))
d = float(1) # d will be 1.0
e = float(2.5) # e will be 2.5
f = float("3") # f will be 3.0
g = float("4.23") # g will be 4.23
h = str("80s") # h will be '80s'
i = str(22) # i will be '22'
j = str(3.01) # j will be '3.01'
print([a,b,c,c1,d,e,f,g,h,i,j])
Eval
# int('2+3') - This will result in an error
eval('2+3')
# Output: 5
Arithmatic Operators
a=10
b=3
print('Addition : ', a + b)
print('Subtraction : ', a - b)
print('Multiplication : ', a * b)
print('Division (float) : ', a / b)
print('Division (floor) : ', a // b)
print('Modulus : ', a % b)
print('Exponent : ', a ** b)
Getting user input values
num1=input('Enter a digit: ')
num2=input('Enter a second number:')
answer=float(num1)+float(num2)
print(answer)
Example
# - Create a distance converter converting Km to miles
# - Take two inputs from user: Their first name and the distance in km
# - Print: Greet user by name and show km, and mile values
# - 1 mile is 1.609 kilometers
name= input('What is your name?: ')
distance = input('Enter the distance you can run?')
print(f'{name.capitalize()} you can run {distance} kms and that is equivalent to {round(float(distance)*1/1.609)} miles')
Working with Strings
msg='welcome to Python 101: Strings'
print(msg)
print(msg.upper())
print(msg.lower())
print(msg.capitalize()) #capitalize first letter on the sentence
print(msg.title()) #capitalize first letter of each word
print(len(msg))
print(msg.count('Python'))
print(msg.count('o'))
# Slicing
print(msg[4])
print(msg[-7])
# To grab everthing after 2
print(msg[2:])
# from position -> to upto (character at last position is not included)
print(msg[2:15])
# Starting everything from 0 to indicated number-1
print(msg[:7])
# Challenge: Write text '1 Welcome Ring To Tyler' using given variable 'msg'
msg1=msg[18]+' '+msg[:8]+msg[25:29]+msg[7:11]+msg[13]+msg[12]+msg[2]+msg[1]+msg[-5]
print(msg1.title())
# Print the same string backward
print(msg1[::-1])
#Other way to flip the list
my_list = [1,5,3,7,2]
print(list(reversed(my_list))) #output: [2, 7, 3, 5, 1]
# multi-line strings
msg2="""Dear Terry,,
You must cut down the mightiest
tree in the forest with…
a herring! <3"""
print(msg2.find("mightiest"))
# Find/Replace in Python
msg3='welcome to Python 101: Strings'
print(msg3.find('Python'))
print(msg3.replace('Python', 'Java'))
# Check if text exists in given string
msg4='welcome to Python 101: Strings'
print('Python' in msg)
print('Java' not in msg)
# String Formatting using variables
name1='terry'
color1 = 'RED'
msg6 = '[' + name1 + '] loves the color ' + color1.lower() + '!'
msg7 = f'[{name1.capitalize()}] loves the color {color1.lower()}!'
print(msg6)
print(msg7)
Working with Lists
friends = ['John','Michael','Terry','Eric','Graham']
# 2nd element and 5th element
print(friends[1],friends[4])
# last element
print(friends[-1])
# 3rd to 5th element
print(friends[2:4])
# first element to fourth element
print(friends[:4])
# reverse the list
print(friends[::-1])
# whole list
print(friends[:])
# number of elements in list
print(len(friends))
# Determine index of element in list
print(friends.index('Eric'))
# Count # of certain elements
print(friends.count('Eric'))
# Generate certain number of values
alot_of_zeros = [0] * 20
print(alot_of_zeros)
# Sorting a list
friends.sort()
print(friends)
# Sort in descending order
friends.sort(reverse=True)
print(friends)
# reverse the list
friends.reverse()
print(friends)
# Sort numeric array
cars = [911,130,328,535,740,308]
cars.sort()
print(cars)
# Find minimum/maximum value in an array
print(min(cars))
print(max(cars))
# Sum of the elements in an array
print(sum(cars))
# Add new elements in the list
friends.append('TerryG')
print(friends)
# Specify the position where to insert the element
friends.insert(1,'TerryV')
print(friends)
# Replacing the value in the list
friends[2]='TerryG'
print(friends)
# Extend the lists (combines 2 lists)
friends.extend(cars)
print(friends)
# Remove an elements
friends.remove('Terry')
# Pop the last element from the list. This element can be assigned to any variable
friends.pop()
# Pop last element - alternate way
friends.pop(-1)
# pop specific element
second_element = friends.pop(2)
print(second_element)
# Remove all elements from the list and returns an empty list
friends.clear()
# Delete a list
del friends
# removes specific index value
del friends[2]
# Copy List - Method 1
new_friends = friends.copy()
# Copy List - Method 2
new_friends = list(friends)
# Copy List - Method 3
new_friends = friends[:]
# Un-packing the list
items = ['laptop', 'mouse', 'keyboard']
laptops, mouse, keyboard = items #generates variables using items from the list
print(laptops)
mobile = ['Pixel3', 'Android 12', 'Android 13', 'Android 14']
mobile_type, *ios_version = items #generates variables using items from the list
print(mobile_type) # prints Pixel3
print(ios_version) #prints other items from the list
# Creating a list from a string
name = list('Ambreen')
print(name)
# Output
['A', 'm', 'b', 'r', 'e', 'e', 'n']
# Creating a list by giving a range
my_list = list(range(0, 10))
# Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# Generating a list by giving range and increment value
my_list = list(range(2, 22, 2))
print(my_list)
#Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Example List
# Lemonade sales for week 1 & week 2
sales_w1 = [7,3,42,19,15,35,9]
sales_w2 = [12,4,26,10,7,28]
# Get the number of lemonades sold on 7th day in second week
new_day = input('Enter number of lemonades sold on 7th day in second week')
sales_w2.append(int(new_day))
# Combine the sales for week 1 & week 2
#sales.extend(sales_w1)
#sales.extend(sales_w2)
sales = sales_w1 + sales_w2
print(sales)
# How much you earned on Best & Worst Days
worst_day_prof = min(sales) * 1.5
best_day_prof = max(sales) * 1.5
print(f'Worst day profit:$ {worst_day_prof}')
print(f'Best day profit:$ {best_day_prof}')
print(f'Combined profit:$ {worst_day_prof + best_day_prof}')
Split and Join
Split
- Split turn data into a list
msg ='Welcome to Python 101: Split and Join'
names = 'Edward,Gor,Eileen,Andy,Abdul'
print(msg.split()) #Splits by spaces
print(names.split(',')) #Splits by Commas
Join
- Join turns data into a string
name_list = ['Edward','Gor','Eileen','Andy','Abdul']
print('-'.join(name_list))
# Output:
# Edward-Gor-Eileen-Andy-Abdul
- To remove the spaces from a string and join it back
print(''.join(msg.split()))
# Alternate approach
print(msg.replace(' ', ''))
Example
- Make a list from the names given in csv variable
csv = 'Eric,John,Michael,Terry,Graham:TerryG;Brian'
friends_list = (','.join((','.join(csv.split(';'))).split(':'))).split(',')
print(friends_list)
# Alternate way using replace method
print(csv.replace(';',',').replace(':',',').split(','))
Tuples
- Tuple is read only list that can't be changed
- Tuples are faster in performace than lists
- Tuple can have duplicate items
i_am_tuple = ('1', '2', '2','3')
# To get an element from tuple, use same method as list
print(i_am_tuple[0])
print(i_am_tuple[1:3])
Sets
- Sets are unordered list and remove duplicate date
- Sets are faster in finding the element than the list
i_am_set = {'1','2','3'}
- Applying intersection, difference and union on two Sets
friends_set = {'John','Michael','Terry','Eric','Graham','Eric'}
my_friends_set = {'Reg','Loretta','Colin','Eric','Graham'}
print(friends_set.intersection(my_friends_set)) # What's common in two sets
print(friends_set & my_friends_set) #Alternate way of writing intersection statement
print(friends_set.difference(my_friends_set)) # What's different in two sets
print(friends_set - my_friends_set) #Alternate way of writing difference statement
print(friends_set.union(my_friends_set)) #Union of two sets removing dupliactes
print(friends_set | my_friends_set) #Alternate way of writing union statement
- Symmetric Difference - data that exists only in one of the set
print(friends_set.symmetric_difference(my_friends_set))
print(friends_set ^ my_friends_set) #Alternate way of writing smmetric difference statement
Creating empty list, tuple and set
#empty Lists
empty_list = []
empyt_list = list()
#empty Tuple
empty_tuple = ()
empty_tuple = tuple()
#empty Set
empty_set = {} # this is wrong, this is a dictionary
empty_set = set()