📱

Get Our Mobile App

Take your business learning on the go!

Download on the App StoreGet it on Google Play

All Python Syntax in 25 Minutes – Tutorial

Beau Carnes24:59

Transcription

I'm about to teach you almost all of Python syntax. You'll learn about the things that Python can do. We'll be going quick, so it may be helpful if you have at least some programming experience.

In this tutorial, if I show code that starts with three angle brackets, that means it is the Python shell. The lines of code are run individually, and the result of running the code is displayed right below. If there are no angle brackets, that means it's a section of code that's meant to run all at once in a program.

Okay, let's get started. Basic math works just like you would expect in Python. You can just do addition, multiplication, division, basic order of operations. You can use parentheses.

You can concatenate strings just by putting two strings right next to each other. You can use a plus sign to concatenate them, to put them together, but you don't have to. You can just use a space. And you can also multiply strings. "L" times five equals "LLLLL".

This is how you create a variable. `spam` is the variable name, and it's set to equal the string "hello". And this is a comment. And then a multi-line comment. And this is how you initialize a variable. We're initializing `a` to one.

You can print a message to the console just like this: `print("hello world")`. And in the print statement, you can put a comma, and we have a string and then the variable, and it just puts a space in between.

Now, here, this is how you get input from the user. Just this `input()` here. We can set it to this variable, and we can print what was typed in. And this is a special way, this `.format()`. It's a special way to put a variable in a string. There's a few other ways that we'll talk about later.

The `len()` function. We can get the length of a string. "hello" is five characters. And `str()` will convert an integer into a string. And then `int()` we can convert a float into an integer.

These are the different equality operators. It's pretty much the same in every programming language. Just keep in mind that equal to is two equal signs. A single equal sign is the assignment operator. So we can check to see if "hello" equals "hello". Well, no, because there's a capital letter and one in a lowercase 'h' on the other. An `int` and a `float` do equal each other. An `int` is a number without a decimal, and then a `float` is a number with a decimal point.

And we can also see if something is not equal. "dog" does not equal "cat". That's true. But you should never use the `==` or `!=` operator to evaluate Boolean operations. Use the `is` or `is not` operators, or use implicit Boolean evaluation.

We can use `and` to evaluate two things. So the first one and the second one has to be true for this to evaluate as true. And we can use `or`. So either this part or this part can evaluate as true for it to be true. And you can combine multiple `and`s and `or`s together.

And this is how you do an `if` statement. So `if name == "Alice":` then we'll print "Hi Alice". And in Python, spacing or tab is very important. After the colon, the next line has to be indented or tabbed over. And each line that's indented the same amount will be inside the `if` statement.

So here's how you do `if else`. So `if name == "Alice":` "Hi Alice". `else:` if any other condition, `if name == "anything else":` print "hello stranger".

We can also do an `elif` or an `else if`. So `if this is true` then we do this. But `else if` we're going to now check if this is true. `if age < 12:` then we're going to print this. And if neither is true, we're not going to do anything.

Now we have the `if`, the `elif`, and the `else`. We've combined everything. So if the first two are not true, we'll do this last line here.

And this is a loop. This is a `while` loop. So `while spam < 5:` it's going to keep running these lines of code over and over until `spam` is not less than five. And then the code will stop running.

Now, if you do `while True:`, that means it's going to continue doing this forever. But if it hits a `break` statement, then it's going to break out of the loop and go to the line underneath the loop. The indentation shows which lines of code are within the loop. So these three lines are all indented, so they're all in the `while` loop. And then this line is indented even more, so it's in the `if` statement.

Here's another `while` loop. If we get to `continue`, that means we'll just go to the next iteration of the loop, and it's not going to run any of the code after the `continue` statement. So `if name != "Joe":` it's just going to now get another input from the user. And then when it gets to `break`, that's when it will break out of the loop and go to this next line of "Access granted".

Here's another type of loop, a `for` loop. `for i in range(5):`. So `range(5)` is going to go through the loop five times, and `i` is going to be each number in the range from 0, 1, 2, 3, 4. So you can see it prints 0, 1, 2, 3, 4. It gets used `.format()` to add this variable right into here, into the string.

Another way you can create a loop is with this: `range(0, 10, 2)`. So 0 is the first number in the range, 10 is the last number in the range, and 2 is the increment. So it's not just going to count 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. It's going to do 0, 2, 4, 6, 8, which you can see down in the print statement. And you can also count backwards. So now we're going, we're incrementing by negative one each time.

Here is a `for...else` statement. The `else` statement will only run if a `break` has been reached in the loop.

And here's how to import a module. We're importing the `random` module, and then we're using the `random` module to get a random integer between 1 and 10. And this is how you would import everything from the `random` module.

If you want to end a program early, you can use `sys.exit()`.

This is how you create a function. `def hello(name):` and then you can pass in a `name` to the function. And then this is what is the body of the function. So we can call this function many times. So here we're calling the function `hello` and passing in "Alice". And you can see it prints "hello Alice". That's right here, "hello Alice". It's getting the "Alice" from this `name` variable here. And we can also call the function again: `hello("Bob")`. So you can call the function multiple times with different things that we're passing into it.

And here's a function with return values. So when this function is run, this `get_answer()` function is run, it's going to return something different. See `return "It is decidedly so."`. So depending on what `answer_number` it is, it's going to return a different text. So we're going to get a random integer here, and then we're going to get the answer of the random integer, and it's going to print the fortune, which is going to be one of these strings.

Normally, a `print` statement will have a new line at the end. But if you specify `end=""` to be just an empty string here, there will not be a new line at the end. So then both print statements will happen on the same line, like that.

And this is just an example of printing a bunch of strings. And if there's a comma in between them, it's just going to put a space in between them when it prints out. And you can also specify what the separator is. Normally, it's a space, but you can specify it to be a comma or anything else.

Usually, if you define a variable within a function, you cannot use that variable outside of the function. But if you put the `global` keyword here, `global x`, and we're setting this variable `x` to be a global variable. So now, when the function runs here, it's actually going to change the value of the `x` variable. People, when it prints `print(x)`, it's "spam".

This is basic exception handling. You use the `try...except` keywords. We're going to `try` something that could cause an error. Now, if you don't have this `try` block here, an error will make the program end. But if you have this `try...except`, instead of making the program, instead of an error making the program end, it will do whatever happens here. Except if there's a `ZeroDivisionError`, then it's going to print "Error: invalid argument". And you can see in this example, when we print `spam / 0`, it's not going to make the program stop. It's going to print this error.

Here's another example with a `finally` statement. A `finally` section, code inside the `finally` section is always executed, no matter if an exception has been raised or not, and even if an exception is not caught.

Here is how you create a list. A list in Python is similar to an array in some other programming languages. And a list is just a series of values. They could be strings, ints, or some other variable type.

And here's how you access an element in a list. You count from the beginning, and you always count starting at zero. So when we do `spam[0]`, that's going to be "cat". If we said `spam[1]`, that would be "bat". `spam[2]` would be "rat". And we can do a negative number to start counting from the end of the list. So `spam[-1]` is going to be "elephant".

Here's how we get a sub-list with slices. So we define the list here. And then `spam[0:4]` is going to be a section of the list starting at the zero index and ending at the fourth index. In this case, it's actually the whole list again. But here, `spam[1:3]`, we're going to start at "bat" and then "rat". Or `spam[0:-1]`, we start at "cat" and we're going to end at "rat" because `-1` would be "elephant" here. So you're going to go up until, but not including, the final number after the colon sign.

If you slice the complete list like this, it's going to create a copy. So now we have the original list `spam` and `spam2`. If we use `.append("dog")` to add an element to the original list, the original list now has "dog", but the copy does not have "dog" at the end. And we can use the `len()` function to get the length of the list. There's three items in that list.

You can change values in a list with indexes. So `spam[1] = "aardvark"`. And if we look at the list again, now "aardvark" instead of "bat" is in index one. And we can also set `spam[2]` to be whatever's in `spam[1]`. And we can see it's "cat", "aardvark", "aardvark", "elephant".

You can just use the plus operator to add two lists together to become one list. You can also multiply a list to multiply the list three times. And here's another example of using the plus operator to combine the list.

And you can delete an element of the list with `del` or `d e l`. And then we're deleting the element at the index two, which is "rat".

You can use `for` loops with lists. `for i, supply in enumerate(supplies):`. Using `enumerate` is going to make `i` the index and `supply` is going to be each item in the list. So we print "Index {} is {}".format(i, supply). This is going to go into the first curly braces, and the `supply` is going to go in the second curly braces. You can see how that works.

And you can loop through multiple lists with `zip`. So we have `zip` here. So now we're going through the `name` and the `age` list into `n` and `a`. And you can see what that prints out.

You can use the `in` and `not in` operators to see if something is in a list. So `"howdy" in this list`? Well, `True`. `"cat" in spam`? `False`. `"howdy" not in spam`? `False`.

This is the multiple assignment trick where you have this list `cat`. Now `a, b, c, d = cat`. It's going to assign each element of the list to each of these variables. The multiple assignment trick can also be used to swap the values in two variables.

You can use the `+=` operator to add something to a variable. `spam = "hello"`. This line right here, `spam += "world"`, is the same as `spam = spam + "world"`. And you can see what it equals here. You can also use it with the `*=` operator.

And we can use `.index()` to find out the index of a certain item in a list. And we already talked about this, but `.append()` can add an item to the end of the list. And `.insert()` can add an item at a specific index in a list. And `.remove()` will remove the first item in the list that has that value.

And you can use `.sort()` to sort a list. You can sort number lists. You can sort string lists, which will sort in alphabetical order. And you can also reverse the sort with `reverse=True`. You can also use the built-in function `sorted()` to return a new sorted list. `sorted(spam)`.

Now we'll talk about the `tuple` data type. The main way that tuples are different from lists is that tuples, like strings, are immutable. So you cannot change them. So here is a tuple, which is kind of just like a list. And you can still access the items in the tuple similar to the list. So at index 0 is "hello". And we can get the items from index 1 to 3. We can get the length.

And this is showing that we can convert the types with the `list()` and `tuple()` functions. So we have this `tuple()` function, and we pass in a list, and it returns a tuple. We have this `list()` function, we pass in a tuple, and it returns a list.

This is an example of a dictionary. A dictionary is similar to what is called an object in some other programming languages. And a dictionary is made up of key-value pairs. So the key is `size`, the value is `fat`. The key is `color`, the value is `gray`. The key is `disposition`, the value is `loud`.

You can use `.values()` to get each value. So in this `for` loop, we're looping through all the values and we're printing the values. "red", 42. You can do the same thing with the keys, so `.keys()`. And now we're printing the keys. And then with `.items()`, we can print each item in the list that has the key and the value. And here we're storing the key and the value into these variables as we iterate over the dictionary.

You can check whether a key or value exists in the dictionary with `in`. So `if "name" in spam.keys():` `True`. `"zapi" in spam.values():` `True`. And you don't even have to do `spam.keys()`. You can just do `"color" in spam`. `False`.

This `get()` method has two parameters: the key and the default value. If the key does not exist. So here it's trying to get the value of `cups`, which does happen to be 2. But if there is no `cups`, then it's going to return 0. Here, in the second one, there is no `egg`, so it does return 0.

If we look up at this top section, first we're checking if `color` is not already in the dictionary, and if so, we'll set it to "black". Well, there's an easier way to do it, which is with `setdefault()`. So if you do `spam.setdefault("color", "black")`, it will only add the `color` as "black" if `color` is not already in the dictionary.

This is a way to merge two dictionaries. So we have the two dictionaries `x` and `y`. And if we see what `z` is with `**x, **y`, and now we've merged those two dictionaries into one.

Here are two ways to create sets. A set is an unordered collection with no duplicate elements. You can use sets to test for membership and to eliminate duplicate entries, and they support mathematical operations like union, intersection, difference, and symmetric difference. So you see we're creating this set that does have two 2s and two 3s, but then when we check to see what `s` equals, there's only one 2 and one 3 because sets cannot have duplicate entries. And since they're unordered, you cannot access an index number because they're not stored in any particular order.

You can add an element to a set with `.add()`. And `.update()` will add multiple elements to a set at once. And you can use `.remove()` to remove an element. If you do `.remove()` and remove an element that's not already in the set, you will get an error. `.discard()` is just like `remove()`, except when you try to discard something that's not in the set, there will not be an error.

The `.union()` method will create a new set that contains all the elements from the sets provided. The `.intersection()` method will return a set containing only the elements that are common to all of them. The `.difference()` method will return only the elements that are unique to the first set. And the `.symmetric_difference()` method will return all the elements that are not common between them.

This is an example of a list comprehension. So we have this list, and then we're going to create a new list, but it's going to do something to each element in the original list. `i - 1 for i in a`. So each element in the list, we're going to subtract 1 from.

And here's an example of set comprehension. So we have the set, and we're doing `s.upper() for s in b`. So we're actually changing each of these elements in the set to uppercase. And then this is a dict or dictionary comprehension, where we're going to do something for each element in the dictionary to create a new dictionary.

These are examples of some common escape characters. If you want a string to contain a single quote, a tab, new lines, or a backslash, you're going to instead have to put this in there with these escape characters. So here's an example. If you put `\n` in a string, when that prints out, it's going to put a new line. `print("Sirius says I'm doing fine.")`. You can do `\'` to make it appear as a single quote.

If you put the letter `r` at the beginning of a string, it becomes a raw string. A raw string completely ignores all escape characters and prints any backslash that appears in the string.

You can use triple quotes to do multi-line strings. So the string starts with these three quotes, and it ends with these three quotes down here. But with triple quotes, you can see everything starting at the very beginning of the line, so you can't indent it at all. But you can indent if you import the `dedent` function from the `textwrap` standard package. And then you can use the triple quotes, and you can indent everything. And this code is going to generate the same string as as before. This is the "Dear Alice" letter here.

Let's talk about indexing and slicing strings. Just like getting an element of a list, you can get a letter in a string. So you just count from zero, and you can get the letter `string[0]`. The letter at index 0 of the string is 'H'. You can also get sections of a string. You can slice a string `string[0:5]`. Or if you just put `string[:5]`, it's going to assume zero. Or if you put a blank at the end, it's going to assume the last character in the string. And here's another example.

You can use the `in` and `not in` operators with strings. `"hello" in "hello world"`? `True`. `"Hello" in "hello world"`? `False`. `"cats" not in "cats and dogs"`? Well, that's `False` because it actually is.

You can also use the `in` and `not in` operators with lists. `5 in a`? `False`. And we already touched on this a bit, but you can use `.upper()` to change the string to uppercase, or `.lower()` to change the string to lowercase. And you can use `.islower()` to find out if a string is all lowercase. In this case, it's `False` because it has this uppercase letter. We can use `.isupper()` to find out if it's all uppercase. `False`. But here, `"HELLO".isupper()`? `True`. That is all uppercase.

And you can do `.startswith()` to see if a string starts with certain letters, or `.endswith()` to see if the string ends with certain letters.

You can use `.join()`. You take a string and do `.join()`, and then you pass in a list. And now it'll change that list to a string, joining the elements with whatever string it starts with here. So here we use the comma. You can also use a space here.

And you can split a string with `.split()`. `split()` splits into a list. And normally, it's just going to split at the spaces. But you can split at anything, like you could split at "abc".

`.rjust()` will right-adjust. And the full string is now going to be 10 characters, and "hello" is going to be right-adjusted to the end of the 10 characters. Or it can do with 20 characters. So this `.rjust()` right justifies.

You can use `.ljust()` to left-justify in the same way. And you don't even have to have it spaces. You can have asterisks or dashes or anything you like. And `.center()` will center a string within a certain number of characters.

You can remove white spaces with `.strip()`. And it's going to strip off all the spaces at the beginning and the end. `.rstrip()` will just remove the space at the beginning. `.lstrip()` will remove the spaces at the end.

We've already talked about `.format()`. It's just a way to get variables into a string at where the curly braces are. F-strings are in some ways an even better way of putting variables into a string. You start the string with the letter `f`, and then you use curly braces, and you can put the variable right in here. So we're using the variable inside the string in an F-string.

You can also do arithmetic or put any code you like within the curly braces. So you can see `a + b` or `2 * a + b`, and it's right within those curly braces.

You can raise your own exceptions or errors within code. So `raise Exception("This is the error message.")`. And then this is going to be the message that's going to print out. So you can see an example of what happens when the exception is raised. You'll commonly see a `raise` statement inside a function, and then the `try...except` statements in the code calling the function. So this `box_print()` function is going to raise these exceptions. And when we call the `box_print()` function, it's in a `try...except` block. So it's going to try `box_print()`, and it may raise any of these exceptions. And if it does, it's going to print "An exception happened" and then put the string of the error.

Assertions are sanity checks to make sure your code isn't doing something obviously wrong. These sanity checks are performed by `assert` statements. If the sanity check fails, then an `AssertionError` exception is raised. So here are some examples. We have `pod_bay_door_status = "open"`. And we're going to `assert pod_bay_door_status == "open"`. If this was false, this error would be displayed. So we're going to set `pod_bay_door_status` to not be "open", to something different. And we're going to assert that it's equal to "open", but it's not equal to "open". So you can see down here, the exception will happen.

So this goes a little smaller, but it's an example of logging. To enable the logging module to display log messages on your screen as your program runs, we'll import `logging` and then configure `logging`. And then you can add this code within this function that's going to log certain things to the console.

Now let's talk about Lambda functions. If we look at this top part of code, this is a normal function. This function is called `add`. It takes two arguments, and it's going to return adding those things together. So `add(5, 3)` is going to return 8. Well, this function down here is a Lambda function, and it's equivalent to the function above it. It's creating this function on a single line. So the `add` is now at the beginning: `add = lambda x, y: x + y`. And you can see the colon is going to add `x` and `y` together. You can even create a Lambda function without a name. So before it was called `add`, but this isn't even called `add`. We just create the function and then we pass in the numbers right at the end.

Like regular nested functions, Lambdas also work as lexical closures. So basically, you can use a function to create another function. So now we're making a `plus_3` function that's going to add 3 to numbers, and a `plus_5` function that's going to add 5 to numbers. So `plus_3(4)` is going to add 3 + 4. `plus_5(4)` is going to add 5 + 4.

This is how you do ternary operations within Python. So this is basically a one-line code. So this is basically an `if else` statement in a single line. So we're going to print `"kid" if age < 18 else "adult"`.

Now let's talk about `*args` and `**kwargs`. You can see `*args` here. The actual word `args` is arbitrary. The important thing is the asterisk, or if there's two asterisks. So the asterisk basically means pack all the remaining positional arguments into a tuple. While two asterisks is the same for keyword arguments. So basically, what that means is that we can pass in as many arguments as we like. So `fruits("apple", "banana", "cherry")`. This can be one argument, two arguments, three arguments. In this example, we're passing in three arguments, and then it's just going to print each one. But you could have had four, five, six. So that's what the asterisk does. The `**kwargs` it means keyword arguments, and you can have an indefinite number of them, which is just key-value pairs. So we can pass in an unlimited number of key-value pairs. And here's just going to print them.

This here is a special way to only run code if it's run as a script. So this `if __name__ == "__main__":` is the name of the scope in which top-level code executes. A module's name is set equal to `__main__` when read from the standard input, a script, or from an interactive prompt. So we're checking if `name == "__main__"`, and if so, it will run that code, which is just if it's run as a script.

So let me show you how that would be used. So we have this program here that defines the `add()` function here. And then now we're testing the `add()` function. But now, if we want to use this module, this code here, we would have to comment out this test here. So instead, in the program, we'll say `if __name__ == "__main__":`. So now, if we import this file, it's not going to add this. But if we run this file just as a program, it will run `add(3, 5)`.

We've reached the end. You can learn about Python classes and objects in this other video. Leave a comment explaining how to use the parts of Python I missed, and they'll pin the most helpful comment.