340 likes | 352 Views
Join this session for a beginner-friendly introduction to Python programming. From basic concepts to practical applications, learn about variables, expressions, and more. Get started on your Python journey today!
E N D
Introduction to Python WCF TECHCON Feb. 22, 2019 Dave Birnbaum, K2LYV WCF Technical Specialist
Goals/expectations • What I hope to be able to do in the next few hours is to give you just enough to encourage you to be able to start developing your own Python programs. • Since there were no “prerequisites” I’ll try and match my presentation to your experiences • I assumed that you would have had some sort of programming experience. • Arduino, MicroPic, even BASIC
CD/Flash drive files • I have included a CD with the install files for Python 3 with IDLE, a more complex system with a graphical UI, a PDF version of an excellent book for learning Python and a 3 page summary of key Python ideas • These are all free and open source
What is a computer program? • Set of instructions to enable a computer to perform some task • History: • Machine code – e.g. switches, raw numbers • Assembly – symbols machine code • High Level languages Human readable • Let the computer do the translation • FORTRAN, COBOL, then too many to count
Why Python? • Modern language – benefit of 50+ years of development of HLL • Widely used and supported • HUGE number of “packages” to perform almost any computer task (numical, Web, data analysis, Artificial Intelligence …) • Free • Language, packages, development environments • OS – independent • Linux, Windows, MacOSj
Start • Development Environment • Way to write, edit, run, debug program(s) • Simple – IDLE • Complex – Spyder, Eclipse, many others • DVD has Windows installers for IDLE and WinPython which includes Spyder and many other packages with “bias” towards science and engineering • We’ll start with IDLE
Python Versions • Python introduced in late 90s • Python 2.x 2010 • Major change to Python 3 2018 • Most differences between 2.0 and 3.0 are under the hood, but a few are not – I will try and point out where • This talk will use Python 3
Python as calculator • Python is interpreted • Each statement is analyzed and executed as it is entered • Can use Python as “desk calculator” • 2+2, sin(45) • Can “try out” statements to check understanding
Variables • Python, like all HLL has variables to store things that you’ll want to use later • Name must begin with a letter and are case sensitive • Basic types: integer, float, string, complex • We will also look at data structures which are collections of variables • Variables NOT typed at definitionbut at assignment • “Strong typing” but type will change with new assignment • a=1.576 a is now floating point • a = “Hello” a is now a string
Variables cont’d • Test to see what a type a variable is: • type(abc) • “Coercion” of variables • Force one type to another • i = int(4.75) results in I having value of 4 • X = float(4) • Y = float(“3.75”) string to float • Z = str(5.8) Z is now “5.8” • These are important – especially in converting input, usually a string, to numeric values
Expressions • Combining variables to get new value: • a = sqrt(b*17-5*c) • C= “Hello” + “world” • Note + for strings means concatenate (put together) the variables • “Usual” combination of arithmetic operations: • +,-,*,/,** • But / does “truncation” for integerse.g. 5/4 = 1 not 1.25 • For strings “*” means copy multiple times • “Hello”*3 = “HelloHelloHello”
Expressions cont’d. • Relational expressions • a>b, g<=17 … • Operators: >, <. >=,<=, == (note double ==) • Result is True or False • Logical expressions • Bitwise logical: a AND b, NOT a, a OR b • These are used in testing to see if computation has reached some desired (or undesired) state
Digression - flowcharts • Good idea to make graphic depiction of your program (first!) • Common symbols: • “Standard” combinations – “if”, “if then else”, “while”
Ready to write a simple program • We’ll need a way to get input: • Variable = input(“Optional”) • Variable gets assigned a string version of user’s typing • Need to convert to form you want to use e.g. int name = input(“What’s your name?”) phrase = “Okay “+name +” give me a number” number = input(phrase) number = number*number print(“your number squared is “,number) Anybody spot the error?
Error name = input(“What’s your name?”) phrase = “Okay “+name +” give me a number” number = input(phrase) number = number*number print(“your number squared is “,number) Anybody spot the error? Number is a string – have to convert it before multiplying Just add a statement number = int(number) before the multiplication
Variables are really objects • Objects are a concept from modern programming practice. The object has it’s own “methods” for working on the object’s data. • For python each variable has several object methods associated with it. • Most common use is with strings • Syntax – variable.method() • Example “ABC”.lower() makes it “abc” • Many of these are useful and you will “accumulate” some as you go
String objects • Strings seem to be the most common place that I use object functions • Example: • Read a line of input containing several pieces of data • e.g. line in Cabrillo file • Would like to split the single string into individual pieces. • Surprise! There’s a function string.split() to do this
Data structures • It is often useful to deal with collections of data as a single item e.g. arrays in C or Fortran • Python has four basic structures: • List – ordered list of objects, can be changed • Tuple – like list but can’t be changed • Dictionary – Like a list but instead of addressing individual elements by their order it uses a “key” which has an associated value • Value can be any other object e.g. list • Set – unordered collection of objects. • Okay, let’s dig a little deeper
List • Create list by enclosing comma separated list of values inside [] • Members = [“jack”, “jill”, “pail”, “cow’] • Can address individual members by number But starts at 0 • Print(member[2]) gives “pail” • Length of list function len(list) • Note list items go from 0 to len(list)-1 • Can add to list: member.append(“bob”)
Lists continued • List items are addressed using [] • List[3] 4th item in List • List items can be other lists! • Array =[[1,2,3],[4,5,6],[7,8,9]] • Array[2] =[7,8,9] • How about Array[2][2]? • Lists have methods: • append(), extend(), insert(), remove() and 20 more
Logical tests and looping • Almost readyto design a simple program but we need to look at how to do logical tests and how to create a loop • If statement: if “logical expression” : • some stuff else:
Logical stmt cont’d • Note that if statement ends with a : • What about the “some stuff”? • One or more statements • Separated by indentation unlike other languages which use some form of parentheses or brackets • All lines in the block of code have the same indentation • Python will flag an error if unexpected indentation • “logical expression” can be any expression whose value is True or False
Looping • Used when one needs to either repeat some process until some condition exists • “while” and “for” statements are the tools • I’ll save “for” until later • While statement • while ‘logical expression” : • Note termination with a “:” • Again followed by block of statements • Block is repeated until “logical expression” is False • Note that something in the loop must change to logical expression or the loop goes on forever
Problem 1 • Let’s design a (piece of a) program to process a contest log • Given contest log we’d like to make a plot of some sort of contact rate over the course of the contest • To make life simple and avoid details of how to read files etc assume that there is a function that either returns a list or 0. • The list elements in order are: the date, time, frequency, your call, your section, his call, his section. • All are strings
For loop • “for” statement used when you want to repeat some block of statements some fixed number of times. • Typical: for i in range(100) • range is a function returning list of numbers from 1 to n-1 • Note the use of the ‘in” parameter. Other uses • for b in string – covers all characters in the string • for key in dict – runs through all the keys in the dict
Functions • Functions are NOT only things provided by Python but things you can write yourself • Way to process some piece(s) of data where the specific piece may vary over the course of the program • Functions have input via “arguments • FunctionName(arg1, arg2,…) • Function returns a value (may be null) • Scope issues • All variables inside the function are defined only while the function is active and disappear when the function returns
Function Creation • def function(arg,arg,arg …): • Note concluding “:” • Statements following are block of indented code • When the Python interpreter encounters the function definition it does NOT execute the statements • Execution occurs only when function is called • Function ends with “return” statement • return value • Value may be any Python type e.g. list, string …
Python functions • Python includes many functions but not all are immediately available when you start Python. • To save space and limit confusion packages of commonly used and similar functions are bundled and can be loaded if needed. • Possibly the most common are math beyond arithmetic e.g. trig, log, sqrt … • The way to get access to these packages functions is to import them into the current environment
Packages • To import a package you include a statement • import packagename • you can also import just one or two functions in a package e.g. from math import sin • Importing a package makes its functions available but must identify the package • import math • math.sin(45) – prefix package name to function • This has to do with concept of “namespaces” • Bad practice – from package import * dumps all package’s functions into the same namespace as the core program. Can lead to confusion and conflict
Packages • There are a bunch of standard packages that are part of a base Python installation: • math • os – access to os functions e.g. change directory • string – more advanced string functions • random – a variety of random number generators • for science work big three • numpy • scipy • matplotlib • Online there are a semi-infinite number of specialized packages that can work with almost anything you can imagine (and a lot you can’t) • These can be downloaded and installed with the rest of your installation
File I/O • To read/write a file we need to connect to the file. • open(filename,”mode”) retruns a “file object” • mode is one of r,w,a read, write, append • opening a file for write creates it if it doesn’t exist, but wipes out existing content • Need to be sure that you are in the directory where the file is or else filename must contain path to the file e.g. C:/users/drdave/Desktop/FDLog.dat • there is a package “os” that contains cd (change directory) and similar commands • the “file object” can be used by file-specific read/write commands to transfer data
Fancier IDE • Example that I use: Spyder • I use it because it’s focused on science and engineering users but is not specific to them. • There are several others. Look them over and pick the one that fits your preferences and tastes
Optional time • We could use the remaining time to work on some program where you pick a problem and work to develop a program with my help or I can walk you through a program that I wrote several years ago, and have upgraded over the years, to analyze the FD logs from N4TP