Introduction to Python
The course is part of this learning path
In this first course, we introduce the Python Language, the declaration model, and how variables and functions are used in python.
Our learning objectives for this course are to introduce the python language and to be able to recognize and explain the core concepts of the Python language.
- [Instructor] Hi and welcome back. So let's start with a high level overview of Python features. First off, everything in Python is declared by assignment. In Python, if you reference a variable inside a function, that variable is implicitly global. If a variable is assigned a value anywhere within the function's body, it's assumed to be a local, unless explicitly declared as global. Second, Python supports dynamic typing. Now, this is a massive timesaver when you need to write repetitive functions quickly. Third, variables in Python are declared by assigning to them. So Python does not require explicit type specifiers, but sets the type implicitly by examining the value that was assigned. That means assigning a literal integer to a variable creates a variable of type int, while assigning quoted text to a variable creates a variable of type string. Once a variable is assigned to, it'll cause an error if the variable is used with an operator or function that is inappropriate for that type. Fourth, a variable cannot be used before it is assigned to. Now, variables must be assigned some value. A value of None may be assigned if no particular value is needed. Let's look at naming in Python. Names in Python are quite constrained, so the sooner you get into the habit of following the conventions, the less time you will waste dealing with errors. In Python, names may contain only letters, digits, and underscores, and may not start with a digit. Python convention for variable name is all underscore, lower underscore case, underscore words, underscore with underscore underscores. Python has many datatypes. A few high-level points to keep in mind. Python has built-in functions to convert from one type to another. This is useful as Python defines variable types for you based on what you declare. So once a variable is assigned to, it could cause an error if the variable is used with an operator or function that is inappropriate for that type. So we can't convert from one datatype to another. If the source type cannot be converted to the target type, then a TypeError is thrown. In Python, number are created by numeric literals, or by using built-in functions and operators. Python supports three numeric types, integers, floating point numbers, and complex numbers. While Booleans are a subtype of integers, it's worth calling these out early, as you'll find yourself using Booleans frequently. In Python, integers have unlimited precision. In Python, integers have unlimited precision. You can check the precision and internal representation of floating point numbers on the host your code is running on by querying sys.float_info. Complex numbers have a real and imaginary part, which are each are floating point number.
To extract these parts from a complex number in, use in.real and in.imag. The standard floating library also includes additional numeric types. Decimals that can hold floating point numbers, where you set the precision, and fractions that hold rationals. While the constructors in float and complex can be used to produce numbers of a specific type, Python also provides full support for mixed arthritic. Comparisons between specific and mixed number types use the same evaluation criteria. When a binary arithmetic operator has operands of different numeric types, the operand with the narrower type is widened to that of the other. Python supports four types of sequences, strings, bytes, lists, and tuples. All sequences share a common set of operations, methods, and built-in functions. Each type also has operations specific to their type. Strings are text, or essentially an array of Unicode characters. Bytes are arrays of bytes, and lists are sequences of values. Tuples are read-only sequences of values, which can be used as records. You can also use slicing syntax. Slicing can be used with indexes. Sliced indices have useful defaults, like a method first index defaults to zero, and a method second index defaults to the size of the string being sliced, for example. When indexing is used to obtain individual characters, slicing allows you to obtain a substring. With slices, the starting value of a slice is inclusive, while the ending value is exclusive. So the best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered zero. Python also supports mapping types, i.e dictionaries and sets. Now, dictionaries are mapped sets of values. A dictionary is a set of values indexed by an immutable keyword. Dictionaries are used for many tasks, including mapping one set of values to another, and counting occurrences of values. Prior to version 3.6 of Python, dictionaries were unordered, but beginning with version 3.6, dictionaries preserve the order in which items are added. Now, dictionary keys must be hashable, which means, in general, that they must be immutable. This means that most dictionary keys are strings, but they can be numbers or tuples of immutable types. Sets are similar to the dictionaries but contain only keys. A set is a unique collection of values, and there are two types. The normal set is dynamic or mutable, and the frozen set is fixed, i.e. immutable, like a tuple.
Let's review the programming structure for Python. The shorthand view on how to structure your code goes like this. All imports at the top. Variables, functions, and classes must be declared before use. The main function goes at the top, the main function is then called at the bottom, so in Python, modules must be imported before their contents may be accessed. Variables, functions and classes must be declared before they can be used. So most scripts are ordered in this way. Import statements, define your global variables, main function, functions, call to main function.
Let's look into how we read data in and out in Python. There are three main I/O methods in Python, print, open, and input. To output to the screen, we use the print function. Print normally outputs a newline after its arguments. This can be controlled with the end parameter. Print put spaces between its arguments by default. To use a different separator, set the sep parameter to the desired separator, which might be an empty string. To read a file, open it with the open function as part of a with statement. To read it in line by line, iterate through the file with a for loop. To read the entire file, use file.read. To read all the lines into a list, use file.readlines. To read a specified number of bytes, use file.read. To navigate within a file, use file.seek, where we have offset or whence. To get the current location, use file.tell. To get input from the user, use input. It provides a prompt to the user and returns a string, with the newline already trimmed.
The conditional statement in Python, like most languages, is if. There are several variations of how if is used. All depend on testing a value to see whether it is true or false. The following values are false. False, empty collections, e.g. empty string, empty list, empty dictionary, empty set, et cetera, or numeric zero, just about everything else in Python is true. User-defined objects and many built-in objects are true. If you create a class, you can control when it is true and when it is false. Python has a shortcut if-else that's a lot like the other shortcuts you'll see in Perl and curly brace languages.
Loops. There are two types of loops in Python. The while loop is used for reading data, typically from a database or other data source, or when waiting for user input to end a loop. The for loop is used to iterate through a sequence of data. Because Python uses iterators to simplify x's to many kinds of data, the for loop is used in places that would use while in most other languages. The most frequent example of this is in when say reading lines from a file. While and for loops can also have an else block, which is always executed unless a break statement is executed. Python has mini built-in functions. These provide generic functionality that is not tied to a particular type or package. Built-in functions can be applied to many different data types, but not all functions can be applied to all data types. There are 72 builtin functions in Python, which cover a wide range of common functions and expressions. Built-in functions can be called from anywhere. They do not need to be called from an object or package. Okay, that brings us to the conclusion of Course One.
Head of Content
Andrew is an AWS certified professional who is passionate about helping others learn how to use and gain benefit from AWS technologies. Andrew has worked for AWS and for AWS technology partners Ooyala and Adobe. His favorite Amazon leadership principle is "Customer Obsession" as everything AWS starts with the customer. Passions around work are cycling and surfing, and having a laugh about the lessons learnt trying to launch two daughters and a few start ups.