340 likes | 509 Views
Learning to Program with Python. Advanced Class 1. Hello World. Figured we may as well….it’s just one line. print(“hello world”) p rint() is one of python’s 68 built-in functions. Basic Types. The four basic types of python are int , float, bool , and string ( str for short).
E N D
Learning to Programwith Python Advanced Class 1
Hello World • Figured we may as well….it’s just one line. • print(“hello world”) • print() is one of python’s 68 built-in functions.
Basic Types • The four basic types of python are int, float, bool, and string (strfor short). • There is no char. In python, ‘c’ is a string of length 1. • ‘hello’ is a sequence of 5 shorter strings, not 5 characters.
Variables • Variables in python are not statically typed. They can assume a new type at any time. • myVar = 2 • myVar = “now it’s a string” • myVar = 3.0 • You can assign any valid value to any variable at any time.
Math • Nothing new here. • 5 + 5 – 10 * 18 + (1 + 7) • The division operator will always return a float, even with ints. • 1 / 1 1.0
Math • There is an integer division operator, too. • 4 / 3 1.333333 • 4 // 3 1
Incrementing and such • Python does not have n++ and n--. But it does have: • n = n + 1 • n += 1 • There’s also: • -= • *= • /= • //= (and several others.)
The input() function • user_input = input(“Tell me your name!”) • Prompts the user in the shell, then returns what they type in as a string. • Here, we assign the return value to the newly declared variable user_input.
String concatenation • resultString = “one fish ” + “two fish” • The variable resultString now holds the string “one fish two fish”
Type conversion • “stringy stuff” + 50 • That’s an ERROR! Python can’t convert implicitly. • “stringy stuff” + str(50) “stringy stuff50” • str() is another built-in function, for type conversion. • int(“40”) 40
That’s enough info to get started. • Time to write our first python script.
A simple ATM transaction. • Using: • strings, ints • variables • type conversion • string concatenation • print() and input() • comparisons • if/elif/else statements.
Booleans • True and False are reserved words in python. They are capitalized. • 4 > 5, “hi” == “dog”, 1 != 2 • These are all boolean expressions that evaluate to True or False. • my_example_var = True
Looping in Python • The while loop works like in every language. • Python uses indentation to determine scope. while condition: indented code to be executed as long as it’s indented, it’s part of the loop this code is now back outside the loop
Lists • Python’s word for a dynamic array. • Elements can be of different types. • Declared with square brackets • myList = [] #this variable now holds an empty list
Comments #by the way • Single-line comments are done with the hash tag. • Multi-line comments are done with triple quotes. ’’’This is a multi- -line comment’’’ • More on triple-quoted comments later– there’s more to them than meets the eye.
Back to Lists • Internally implemented as an array of pointers in C, to put it in straightforward terms. • Has many handy methods: append, extend, pop, count, membership testing, etc. • Subscriptable! print(myList[7])
For loops in Python • Works a bit different than lower-level languages. • Designed to be intuitive and human readable. myList = [“hello”, “how”, “are”, “you?”] for item in myList: print(item)
For loops in Python • Besides iterating over a list with a for…in… loop, you can also loop over a set of numerical values like you may be used to, using the built-in range() function. for x in range(10): print(x) • Prints 0,1,2,3,4,5,6,7,8,9
More built-in functions • Here are some more built-ins that happen to work very well with lists: • max(list) returns the highest value in the list. • min(list) returns the lowest value in the list.
More built-in functions • sorted(list) returns a sorted version of the list. • sum(list) returns the sum of all the elements. • len(list) returns the length of the list.
Functions in Python defname_of_function(arg1, arg2…): indented code is part of function scope • The keyword is “def”, short for “define”. • Function names, just like variable names, can have letters, numbers, and underscores, but cannot start with a number. Almost as if….functions were variables….hmm…. • Functions must be declared before they can be used.
Let’s write another program. • We’re going to create a function that takes a base 10 number and returns a Roman Numeral string.
Scope in Python • I hate interview scope puzzles. • Code should be clear enough that the reader isn’t wondering “which MyVagueVariable is he referring to now???” • But it’s important to understand anyway, and in Python it’s fairly straightforward.
Scope in Python withSimple Functions • Functions can see outside their own scope so long as you don’t redeclare the variable. But they cannot change an external variable. • From the main scope, you cannot see into a function’s scope.
Scope in simple functions x = 4 def test(): x = 2 print(x) test() • test() looks inside its own scope, finds x, and prints it.
Scope in simple functions x = 4 def test(): print(x) test() • test() looks in its own scope, finds nothing, so it checks the outer scope, and finds x there.
Scope in simple functions x = 4 def test(): print(x) x = 2 test() • ERROR! The function knows you have redeclared x. It knows that a variable `x` exists in its local scope, so it refuses to look at the external scope at all. • So it just errors because you’re trying to reference a variable without declaring it.
Global Variables in Python • There is a global keyword, if you’re into that sort of thing. • It’s usually prudent to avoid global variables, as you’ve no doubt heard before. • If you really must use it….Google it or ask after class.
So much more • I would like to tell you about mutability. • I would like to tell you about list comprehensions. • I would like to tell you about functional programming with Python. • I would like to tell you about iterables, iterators, and generators. • I would like to tell you about magic methods. • I would like to tell you about function decorators.
So much more • Those are all somewhat in-depth topics which will give you a very, very strong grasp on how Python works. • Until we can establish a firm, basic understanding of the language, it’s best to avoid most of that. • So let’s write more code.
A word about the Standard Library • Python has an extremely comprehensive standard library, including but not limited to: • Math, data structures, database access, XML, HTML, threading, randomness, regular expressions, JSON, email, cryptography, csv, os access, ZIP, tarfile, gzip, time, date, HTTP cookies, sockets, codecs, and much more
Helpful Links • I’m going to put helpful links in a new topic under “Discussions” on the Meetup site, including: • Documentation for built-in functions • Python execution/memory visualization tool. • Module of the Week, the best introductory guide to the standard library.
Future Classes • Dictionaries, object-oriented programming with classes, recursion, the os module, the sys module, regular expressions, tuples, file access, sockets, in-depth understanding with magic methods, function decorators