Programming Webinar: Get Started with Python Programming

Page 1

Get Started with Python Programming

Karl Larson NetCom Learning www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Agenda

• • • • •

Getting Started with Python Functions and Variables Understanding Error Detection Working with Files and Classes Q&A session with the speaker

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Python Introduction • Python is • An open-source widely-used general purpose, high-level computer programming language optimized for • programmer productivity • code readability • software quality

• Used for both standalone programs and scripting applications • Dynamic typed • Source can be compiled or run just-in-time

• Its free, portable, powerful and is easy to use • Download from python.org

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Two Major Versions of Python • There are two major versions of Python: • Python 2.x is legacy, Python 3.x is the present and future of the language

• The last Python 2.x version was Python 2.7 in 2016 • The first Python 3.x version was released in 2008 and is under active development • • • •

Python 3.5 in 2015 Python 3.6 in 2016 Python 3.7 in 2018 All recent standard library improvements are available by default in Python 3.x

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Two Major Versions of Python 1994

1.0

2000

2.0

2006

2.5

Most recent versions: 2.7.13 and 3.6.2 2008

2.6

2016

2.7

2017

3.0

3.6

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


What can Python do? • Web applications and services • Data mining and data munging (copy, convert, filter) between anything • End-user GUI applications

• System Administration • Scientific analysis • Cloud-based applications

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Python Interfaces • IDLE – a cross-platform Python development environment • PythonWin – a Windows only interface to Python • Python Shell – running 'python' from the Command Line opens this interactive shell

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Indentation and Blocks • Python uses whitespace and indents to denote blocks of code • Lines of code that begin a block end in a colon: • Lines within the code block are indented at the same level • To end a code block, remove the indentation • You'll want blocks of code that run only when certain conditions are met

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Conceptual Hierarchy • Programs are composed of modules • Modules contain statements • Statements contain expressions • Expressions create and process objects

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Dynamic Types – Data Dictates Datatype • A variable's data type is not declared • It is determined based on the value assigned to the variable • which can change x=5 s = 'Hello World' s = 23.2

# x is an int data type # s is a str data type # s is now a float data type

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Dynamic Types – Conversions • Once a variable is assigned a value, the type is enforced x1 = 5 s1 = '3' s2 = s1 + x1

# TypeError: Can't convert 'int' object to str implicitly

• Most conversions must be explicitly performed s2 = s1 + str( x1 ) x2 = int( s1 ) + x

# s2 is set to '35' # x2 is set to 8

• … unless the intent was obvious x = 120.5 y = 10 z=x+y

# x is a float data type # y is an int data type # y is promoted to a float, z is a float data type

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Python Collections • Python provides several collections, including: • List: an ordered mutable collection of arbitrary objects L = [ 'a', 'b', 'c' ]

• Tuple: an ordered immutable collection of arbitrary objects T = ( 'a', 'b', 'c' )

• Set: an unordered mutable collection of arbitrary objects with no duplicates S = { 'a', 'b', 'c' }

• Dictionary: an unordered mutable collection of key, value pairs D = { 'TX' : 'Texas', 'CA' : 'California', 'PA' : 'Pennsylvania' }

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


if statements • If statements evaluate expressions • indented statement(s) following if statement are executed if the expression is true theAnswer = 42; if theAnswer == 40: print("The answer 40 is correct!") elif theAnswer == 41: print("The answer 41 is correct!") else: print("The answer is not 40 or 41")

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


while loop • The while loop executes statements while a condition is true i=0 while i < 10: print( i, end=' ' ) i += 1

# outputs 0 1 2 3 4 5 6 7 8 9

while True: # this is an example of an infinite loop print( 'Type Ctrl-C to stop me!')

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


for loop • For loops may be used to iterate through any iterable object for food in [ "spam", "eggs", "ham" ]: print( food) # outputs "spam\neggs\nham" for i in range(0, 10): print( i, end=' ' )

# outputs "0 1 2 3 4 5 6 7 8 9"

for i in range(10, 0, -2): print( i, end=' ' )

# outputs "10 8 6 4 2"

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Functions • Functions • • • •

contain indented blocks of code (statements) can be called at any time can have parameters which are passed into the function can perform tasks, returns results or both

• Functions are defined using the syntax: def funcName( parameters ): statements

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Function Return Values • Functions can return results (or not) def sayHello(): print('Hello Python') def giveFeedback(): return 'You are awesome!'

# does not return a result

# returns a string result

• The return data type depends on the value returned def square(x): return x * x x = 10 x2 = square( x ) # An int is returned from square() y = 2.5 y2 = square( y ) # A float is returned from square()

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Function Parameters • Functions can take parameters (or not) def sum( x, y ): return x + y

# two parameters

def greet(name): # one parameter print('Hello, {0}!'.format(name) ) def sayHello(): print('Hello Python')

# no parameters

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Syntax Errors • Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning Python >>> while True print File "<stdin>", line 1 while True print ^ SyntaxError: invalid syntax >>>

• The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected • The error is detected at the token preceding the arrow • File name and line number may also be output so you know where to look in case the input came from a script

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Exceptions • Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it • occur during the execution of a program • Exceptions are not unconditionally fatal

• Exceptions may result in error messages like “cannot divide by zero” or “cannot concatenate ‘str’ and ‘int’ objects” 10 * (1/0) 4 + spam*3 '2' + 2

# ZeroDivisionError: integer division or modulo by zero # NameError: name 'spam' is not defined # TypeError: cannot concatenate 'str' and 'int' objects

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Standard Python Exceptions • A list of some of the more common Python Exceptions and Errors

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Exception Handling • Exceptions may be caught using a try-except block • The rest of 'try' block is skipped after an execution occurs • the 'except' block is executed, and • execution continues try:

10 * (1/0) except( ZeroDivisionError ): print ( 'caught divide by zero attempt')

• If an exception does not match any exception • it is passed on to outer try blocks, if any • execution stops for unhandled exceptions

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Object-Oriented Programming • Python is an object-oriented language • In fact, everything is an object in Python

• Object-oriented programming terminology: • A class is a user-defined template for an object that defines a set of attributes that characterize any object of the class • Classes contain variables and methods (functions)

• Object-oriented design focuses on: • Encapsulation • Polymorphism • Inheritance

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Methods in Classes • Define a method in a class by including function definitions within the scope of the class block • All methods include a special first argument self which gets bound to the calling instance • Methods common to a class include: Method

Description

__init__()

Class constructor

__del__()

Class destructor

__str__() and __repr__

Class string representation

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Classes • Classes contain variable and methods (functions) accessed through references: class Animal: def __init__( self, name, height, weight ): # constructor self.__name = name self.__height = height self.__weight = weight def __str__(self): # called when the object is stringified return "{0}, height={1}, weight={2}".format(self.___name, self.__height, self.__weight) def speak( self ): # constructor print( "woof woof")

dog = Animal("Wolfee", 12, 23) # creates an Animal object print( dog ) # outputs "Wolfee, height=12, weight=23" dog.bark()

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Opening Files • The built-in open() function • opens the a file, and • returns a file object: f = open( file_name [, access_mode ][, buffering] )

• file_name: the name of the file to be accessed

• access_mode: optional access_mode determines the mode in which the file is opened (see next slide) • buffering: optional buffering specifies whether buffering is performed (non-zero) or not (0)

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


File Read Functions • The read(), readline() or readlines() functions read a file's content Function

Description

f.read()

read a file's contents as a string

f.readline()

next a line from file as a string

f.readlines()

read a file's contents as a list of lines

f = open('test.txt', 'r') while True: line = f.readline() if not line: break print( line)

# open read

f = open('test.txt', 'r' ) data = testFile.read()

# open read # read entire contents of file as a string

# read one line at a time

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


File Write Functions • The write() and writelines() functions write to a file Function

Description

f.write( str )

write a string to a file

f.writelines( sequence)

read a sequence of strings to a file

f = open('test.txt', 'w+') f.write( 'first line\n')

# writes one line of data to file

l=[] for i in range(10): l.append( 'number is ' + str(i) + '\n' ) f.writelines( l ) # writes sequence of strings to file f.close()

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Recorded Webinar Video

To watch the recorded webinar video for live demos, please access the link: https://goo.gl/8TfG6Z

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


About NetCom Learning

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Recommended Courses & Marketing Assets Courses: » Python Programming - Class scheduled on March 18 » Introduction to Python

» Advanced Python Programming » Python 3 Fundamentals eLearning

Marketing Assets: • •

Blog - 7 Top Programming Languages to Kick-off Your Career in Software Development Free On-Demand Training - Numerical Programming: Understanding Python, Numpy & Matplotlib

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Going Head-to-Head: CompTIA PenTest+ vs. CEH How to Successfully Migrate Office 365 Exploring the New Office 365 Cloud Computing Migration Plan: What You Must Know SQL Server 2017: Indexing for Higher Performance Cybersecurity Analyst (CySA+): Threat Management Illustrator for Web Design: Wireframing AWS: What's New in Amazon EC2 IT Pros: What's New in Windows Server 2019 Angular Architecture: Planning, Organizing and Structuring www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


Promotions

It’s time for a SALEbration! NetCom Learning is headed for its next milestone – 21 years of nonstop training and learning. To commemorate, we will kick off the best SALEbration of the year -- Courses, Bundles and Learning Passes at 21% OFF! Learn More www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Follow Us On:

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

Š1998-2019 NetCom Learning


THANK YOU !!!

www.netcomlearning.com | info@netcomlearning.com | (888) 563 8266

©1998-2019 NetCom Learning


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.