Python Introduction PDF
Document Details
Uploaded by CleanestHeliodor5720
The World Islamic Sciences & Education University
Dr. Adel Hamdan
Tags
Summary
This document is an introduction to Python programming. It covers installation, basic data types, variable assignments, and string manipulation. The presentation also provides examples and explains different Python concepts, including order of precedence, floating-point arithmetic, and more.
Full Transcript
Python Dr. Adel Hamdan Installation www.anaconda.com/downloads Free “No Install” Options jupyter.org/try Google Collab Online Notebooks Free “No Install” Options Hard to upload your own code, data, or notebooks! May not save your code in the free version! Jupyter Notebook Help –...
Python Dr. Adel Hamdan Installation www.anaconda.com/downloads Free “No Install” Options jupyter.org/try Google Collab Online Notebooks Free “No Install” Options Hard to upload your own code, data, or notebooks! May not save your code in the free version! Jupyter Notebook Help – Keyboard shortcuts View – Toggle Header View – Toggle Toolabar Add Number to cells Use Menu View Then Toggle Line Number Use keyboard Or Press ESC Then L Basic Data Types Example Order of precedence in python Parentheses, Exponential ( ( 13 + 5 ) * 2) (exp), Multiplication, Division, Addition, Subtraction Multiple variables assignments in one line a, b, c =10,20, 30 Basic Data Types Difference between Tuples and List Tuples : They look a lot like lists, except they have parentheses and they're immutable, meaning you cannot change an object that's already in that sequence. Difference between Tuples and List List is mutable Tuple is Immutable Numbers There are two main number types we will work with: Integers which are whole numbers. Floating Point numbers which are numbers with a decimal. Let’s explore basic math with Python! We will also discuss how to create variables and assign them values. 14. Floating Point Arithmetic: Issues and Limitations Why doesn't 0.1+0.2-0.3 equal 0.0 ? This has to do with floating point accuracy and computer's abilities to represent numbers in memory. For a full breakdown, check out: https://docs.python.org/2/tutorial/floatingpoint.html >>> 0.1 + 0.2 0.30000000000000004 meaning that the exact number stored in the computer is approximately equal to the decimal value 0.100000000000000005551115123125. In versions prior to Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits, giving ‘0.10000000000000001’. In current versions, Python displays a value based on the shortest decimal fraction that rounds correctly back to the true binary value, resulting simply in ‘0.1’. Variable Assignments my_dogs = 2 Rules for variable names Names can not start with a number. There can be no spaces in the name, use _ instead. Can't use any of these symbols :'",/?|\()!@#$%^&*~-+ Rules for variable names It's considered best practice (PEP8) that names are lowercase. https://www.python.org/dev/peps/pep-0008/ Avoid using words that have special meaning in Python like "list" and "str" Variable Assignments Python uses Dynamic Typing This means you can reassign variables to different data types. This makes Python very flexible in assigning data types, this is different than other languages that are “Statically-Typed” my_dogs = 2 my_dogs = [ “Sammy” , “Frankie” ] This is okay in Python! Variable Assignments Pros of Dynamic Typing: Very easy to work with Faster development time Cons of Dynamic Typing: May result in bugs for unexpected data types! You need to be aware of type() Variable Assignments myincome =1000 tax= 0.2 mytax= myincome*tax print multiple variables band = 8 name = "Sarah Fier" print("The band for", name, "is", band, "out of 10") Strings Strings are sequences of characters, using the syntax of either single quotes or double quotes: 'hello' "Hello" " I don't do that " Strings Because strings are ordered sequences it means we can using indexing and slicing to grab sub-sections of the string. Indexing notation uses [ ] notation after the string (or variable assigned the string). Indexing allows you to grab a single character from the string... Strings These actions use [ ] square brackets and a number index to indicate positions of what you wish to grab. Character : h e l l o Index : 0 1 2 3 4 Reverse Index: -5 -4 -3 -2 -1 Strings Slicing allows you to grab a subsection of multiple characters, a “slice” of the string. This has the following syntax: [start:stop:step] start is a numerical index for the slice start stop is the index you will go up to (but not include) step is the size of the “jump” you take. Strings mix single quotes and double quotes. This is going to confuse Python because it thinks that you're trying to end the string here when really I'm trying to end the string there. Strings Print statement Escape sequence \n \t Strings Len String Format Often you will want to “inject” a variable into your string for printing. For example: my_name = “Jose” print(“Hello ” + my_name) There are multiple ways to format strings for printing variables in them. This is known as string interpolation. String Indexing and Slicing indexing or grab a single character slicing or grab a subsection of that string. String Indexing and Slicing Slicing String Indexing and Slicing Slicing Python Trick to reverse a String mystring[::-1] # Reverse a String Reverse a String Reverse a String a[-1:-5:-1] -1: The start -5: The end (excluded) -1: The step String Indexing and Slicing Do not assign a variable name to the string String Indexing and Slicing immutability The first thing we're going to discuss is the immutability of strings, and immutability. It stems from the word mutate basically means immutates or cannot mutate or cannot change. TypeError: 'str' object does not support item assignment String Indexing and Slicing Concatenation String Indexing and Slicing you're going to get errors if you try to concatenate a number with a string. String Indexing and Slicing String Function x.split('i’) # You can split based on a character instead of space String Indexing and Slicing 1. Are strings mutable? Strings are not mutable! (meaning you can't use indexing to change individual elements of a string) String Formatting for Printing Often you will want to “inject” a variable into your string for printing. For example: my_name = “Jose” print(“Hello ” + my_name) There are multiple ways to format strings for printing variables in them. This is known as string interpolation String Formatting for Printing txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36) txt2 = "My name is {0}, I'm {1}".format("John",36) txt3 = "My name is {}, I'm {}".format("John",36) print(txt1) print(txt2) print(txt3) String Formatting for Printing Let’s explore two methods for this:.format() method f-strings (formatted string literals) print (' The {} {} {}'.format ('Fox','Brown','Quick')) String Formatting for Printing print ( " the result is {:0.4f}".format(result)) # note that 0 here is not important since it will see the results # we are focus on decimal values print ( " the result is {:10.4f}".format(result)) # if you use large value such as 10 # it will fill 2 blanks to the left 128.7001 9s 8 digit plus 2 digit String Formatting for Printing print ( f' University name is {name}') Methods Fortunately, with iPython and the Jupyter Notebook we can quickly see all the possible methods using the tab key. The methods for a list are: append count extend insert pop remove reverse sort Let's try out a few of them: Methods append() allows us to add elements to the end of a list: # Create a simple list lst = [1,2,3,4,5] lst.append(6) # Check how many times 2 shows up in the list lst.count(2) You can always use Shift+Tab in the Jupyter Notebook to get more help about the method. In general Python you can use the help() function: Lists Lists are ordered sequences that can hold a variety of object types. They use [] brackets and commas to separate objects in the list. [1,2,3,4,5] Lists support indexing and slicing. Lists can be nested and also have a variety of useful methods that can be called off of them. Lists Methods List method is: Append Clear Copy Count Extend Index Insert Pop Remove Reverse sort Lists Length Lists Concatenation Change a value So that's a way you can mutate or change the elements that are already in a list. Lists List Methods Add Just press tab Lists List Methods Remove( pop) Just press tab Save popped item using a varaiable Lists Remove at specific index Lists Sort # note since newlist.sort() does not return any thing # you cannot say sorted_list=newlist.sort() Lists reverse Lists You would just add another set of brackets for How do I index a nested indexing the nested list, list? For example, if I want for example: my_list to grab 2 from [1,1,[1,2]]?. We'll discover later mylist=[1,2,[3,4]] on more nested objects mylist and you will be quizzed on them later! mylist Dictionaries Dictionaries are unordered mappings for storing objects. Previously we saw how lists store objects in an ordered sequence, dictionaries use a key-value pairing instead. This key-value pair allows users to quickly grab objects without needing to know an index location. Dictionaries use curly braces and colons to signify the keys and their associated values. {'key1':'value1','key2':'value2'} So when to choose a list and when to choose a dictionary? Dictionaries Dictionaries: Objects Dictionary Method retrieved by key name. Clear Unordered and can not be Copy sorted. Fromkeys Get Lists: Objects retrieved by Items location. Keys Ordered Sequence can be Pop indexed or sliced. Popitem Setdefault Update values Dictionaries my_dict={'Key1':'Value1','Key2':'Val ue2’} my_dict my_dict['Key1’] prices={'Apple':100, 'Banan':200,'Milk':250} Prices prices['Apple'] Dictionaries Flexibility of Dictionary dic= {'Key1': ['a','b','c','d’]} dic['Key1'].upper() Add element to Dictionary d={'K1':100, 'K2':200,'K3':300} d d['K4']=400 Overwrite an existing Key d['K3']=5000 Keys and values Keys and values d.keys() d.values() d.items() Tuples Tuples are very similar to lists. However, they have one key difference - immutability. Once an element is inside a tuple, it can not be reassigned. Tuples use parenthesis: (1,2,3) Tuples : There are only two methods for tuples! Count index Multiple assignments in one line (tuple) Multiple assignments in one line Tuples Tuple vs List Tuples method is ( use tab) Count Index List method is: Append Clear Copy Count Extend Index Insert Pop Remove Reverse sort Tuples Indexing Index: first appearance Tuples Tuples are very similar to lists. However, they have one key difference - immutability. Once an element is inside a tuple, it can not be reassigned (immutability) The fact that we can't do reassignments like this by accident, we'll get an error instead is going to be useful when you want to make sure that elements don't get flipped or reassigned later on in larger pieces of code. Sets Sets are unordered collections of unique elements. Meaning there can only be one representative of the same object. Sets are used to store multiple items in a single variable. Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage. A set is a collection that is unordered, unchangeable*, and unindexed. * Note: Set items are unchangeable, but you can remove items and add new items. Set Methods Add Issubset Clear Issuperset Copy Pop Difference Remove Difference_update Symmetric_difference Discard Symmetric_difference_upd Intersection ate Intersection_update Union Isdisjoint update Sets #A set can contain different data types: set1 = {"apple", "banana", "cherry"} set2 = {1, 5, 7, 9, 3} set3 = {True, False, False} Sets Now let's try adding 2 a second time and see what happens. If I call my set, it still just shows one and two, it doesn't show (1 2 2), and this is basically what it is. It has to be unique values in there. You can't add item twice Sets Cast a list to a set. You will have a set of the unique values Again, to remember just that sets are unordered collections of unique elements. Note that set use { } {1,2,3,4} is an example of Set Sets set('Mississippi') Add and remove from set Add remove Booleans Booleans are operators that allow you to convey True or False statements. These are very important later on when we deal with control flow and logic! Pow import math print(math.pow(10,2)) Files Before we finish this section, let’s quickly go over how to perform simple I/O with basic.txt files. We’ll also discuss file paths on your computer. Let’s get started! Files %%writefile testoutput.txt hello this is a test this is line one this is line two myfile=open ('testoutput.txt') Files Display Content of File myfile= open('test.txt’) myfile.read() OR print(myfile.read()) Files Read Line print(myfile.readline()) Files Readlines myfile.readlines() Files If file not Found No such file or directory: 'ifnotfounf.txt' Files Read File myfile.read() Files Read the same file again You get ‘ ‘ The reason this is happening is because you can imagine that there's a cursor at the beginning of the file and when you read it, the cursor goes all the way to the end of the file and you need to reset the cursor or seek it back to zero in order to read it again. Reset the cursor myfile.seek(0)# reset the cursor Files Readlines Readline myfile.seek(0) myfile.readlines() myfile.seek(0) myfile.readline() Note: the output is a list Files Different between read and readlines The output of readlines is a list Files Open from any location Provide the full path myfile= open("C:\\Users\\MYDELL\\Documents\\test.txt") Files Close file Highly recommended after end myfile.close() Files We have to close the file in order to not get any errors, because let's say you open this file somewhere else on your computer and you were trying to delete it, you'd get an error saying, hey, Python is still using this file and you'd have to manually close it once you were done working with it to avoid any such errors, we have to use with statement Open file using with statement, so you don’t get error Files Mode r: read only w:write only (will overwrite or create new) a:append (only will add to a file) r+:reading and writing w+:writing and reading (overwrites existing file or creates a new file) Files with open ('testoutput.txt',mode='r’ ) as my_new_file: print(my_new_file.read()) with open ('testoutput.txt',mode='a’ ) as my_new_file: my_new_file.write('\n ADD STATEMENT’) with open ('thisfilenotexist.txt',mode='w’ ) as my_new_file: # even this file not exist python will create it my_new_file.write('\n i will create it') Files Note that using mode=‘w’ # even this file not exist python will create it Assessment Test / String # Square root: s ='hello' 100** 0.5 # Print out the 'o' # Square: # Method 1: 10 **2 s = 'hello' s=[-1] # Print out 'e' using indexing s ='hello' s # Print out the 'o' s ='hello' # Method 2 # Reverse the string using slicin s s[::-1] Assessment Test / List Build this list [0,0,0] two Sort the list below: separate ways. list4 = [5,3,4,6,1] *3 list4.sort() list =[0,0,0] List4 Reassign 'hello' in this OR nested list to say sorted(list4) 'goodbye' instead: list3 = [1,2,[3,4,'hello']] # sorted display the result immdediately list3='Good Bye' Assessment Test / Dictionary d = {'simple_key':'hello'} # Grab 'hello' d['simple_key’] d = {'k1':{'k2':'hello'}} # Grab 'hello' d['k1']['k2'] Assessment Test / Dictionary # This will be hard and annoying! d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]} Assessment Test / Dictionary Can you sort a dictionary? Why or why not? Answer: No! Because normal dictionaries are mappings not a sequence. Assessment Test / Tuple What is the major difference between tuples and lists? Tuples are immutable! Assessment Test / Sets What is unique about a set? Answer: They don't allow for duplicate items! Use a set to find the unique values of the list below: list5 = [1,2,2,33,4,4,11,22,3,3,2] set(list5) Assessment Test / Booleans