Python for Beginners – Full Course [Programming Tutorial]

Brief Summary

Alright ji, so this full course is all about learning Python programming from scratch. You'll start with the basics, use an online IDE called Replit, and code a rock paper scissors game. Then, you'll dive deeper into Python's core features and finish by building a Blackjack game. The course focuses on hands-on learning with repetition of key concepts for a solid understanding.

  • Learn Python basics with no prior experience needed.
  • Code along using Replit and build two games.
  • Understand core Python features and object-oriented programming.

Introduction to the Course

The course is designed for beginners with no prior programming experience. It aims to teach the core aspects of Python, simplifying complex topics. Python is versatile, used in shell scripting, task automation, web development, data analysis, and machine learning. The course uses Replit, an online IDE, for easy coding and execution in a web browser. It includes a comprehensive section on Python features and culminates in coding a Blackjack game.

Setting Up Replit

To start coding quickly, the course uses Replit, an online IDE. Users can sign up or log in to Replit and create a new Python replit. Replit allows coding and running programs in various languages within a web browser. The interface includes a code editor, output console, and file management. It also offers features like version control and a debugger, though these won't be covered in the course.

Creating Variables

The course starts with creating variables for a rock paper scissors game. A variable named player_choice is assigned the string "rock". Variable names can include underscores for spaces, following Python convention. The = sign is the assignment operator. Strings are words or characters enclosed in quotation marks (single or double). The code will automatically replace the variable with it's value.

Functions in Python

A function is a block of code that runs only when called. Indentation is crucial in Python; code indented the same amount is considered part of the function. A function named get_choices is defined using def, and the player and computer choice variables are indented within it. The return statement specifies what the function outputs when called.

Calling Functions and Printing

To call a function, type its name followed by parentheses. An example function greeting is created to return the string "hi". To print the returned string to the console, the print function is used. The returned value from greeting is assigned to a variable called response, which is then printed.

Dictionaries in Python

Dictionaries store data in key-value pairs, enclosed in curly braces. Keys and values are separated by commas. Keys can be strings or variables. A dictionary named choices is created with keys "player" and "computer", and their values are assigned to player_choice and computer_choice variables.

Getting Input from the User

The input function gets input from the user. The input function is used to get the player's choice, prompting them to enter "rock", "paper", or "scissors". The entered value is stored in the player_choice variable.

Importing Libraries and Using Lists

Python libraries are sets of useful functions. The import statement is used to import libraries, usually at the top of the program. A list in Python stores multiple items in a single variable, surrounded by brackets and separated by commas. The random library is imported to randomly choose an item from a list.

Creating the Check Winner Function

A function named check_win is created to determine the winner. Functions can receive data through arguments specified inside the parentheses. The check_win function takes two arguments: player and computer.

If Statements

An if statement checks a condition, and if true, executes the indented code block. Double equal signs == are used to check if two values are equal. The check_win function is updated to return "it's a tie" if player equals computer.

Concatenating Strings

Strings can be combined using the + operator. An f-string is a simpler way to combine strings and variables by putting f at the beginning of the string and enclosing variables in curly braces {}.

Else and Elif Statements

elif stands for "else if" and combines else and if. It checks a condition if the previous if condition is false. The program executes only one of the if, elif, or else blocks.

Refactoring with Nested If Statements

Refactoring is restructuring code while maintaining its functionality to make it simpler or more understandable. Nested if statements are used to simplify the check_win function.

Calling the Functions to Play the Game

The get_choices and check_win functions are called to play the game. The choices variable stores the result of calling get_choices, which returns a dictionary. The values of the "player" and "computer" keys are passed to the check_win function.

Setting Up Python Locally

Python can be installed locally by downloading it from python.org. The download page provides instructions for different operating systems. Python programs can be run using an interactive prompt (Python REPL) or through a code editor like Visual Studio Code.

Using Visual Studio Code

Visual Studio Code can be used to run Python programs by installing the Python extension. A new file is created, code is written, and the file is saved with a .py extension. The program can be run by clicking the play button, which opens a terminal window and executes the code.

Variables in Detail

A Python variable is created by assigning a value to a label using the = sign. Variable names can include characters, numbers, and underscores but cannot start with a number. Certain keywords like if, for, and import cannot be used as variable names.

Expressions, Statements, and Comments

An expression returns a value, while a statement performs an operation on a value. A program consists of a series of statements, each on its own line. Comments, indicated by a # symbol, are ignored by the Python interpreter.

Indentation and Data Types

Indentation is meaningful in Python and must be consistent within a block of code. Python has built-in data types like strings (str), integers (int), and floating-point numbers (float). The type() function checks the data type of a variable.

Checking and Converting Data Types

The isinstance() function checks if a variable is an instance of a specific class. Data types can be converted using class constructors like str(), int(), and float(). This conversion is called casting.

Operators in Python

Python has various operators, including assignment, arithmetic, comparison, logical, and bitwise operators. Arithmetic operators perform mathematical operations. Comparison operators compare values and return boolean results (True or False).

Boolean Operators

Boolean operators (not, and, or) are used with boolean values. not negates a boolean value. and returns true if both operands are true. or returns true if either operand is true.

Ternary Operator

The ternary operator provides a concise way to write conditional expressions. It has the form result_if_true if condition else result_if_false.

Strings in Detail

A string is a series of characters enclosed in quotes (single or double). Strings can be concatenated using the + operator or appended using the += operator. Multi-line strings are defined using triple quotes.

String Methods

Strings have built-in methods like upper(), lower(), title(), isalpha(), isdigit(), startswith(), endswith(), replace(), split(), and strip(). These methods return a new modified string without altering the original.

String Functions and Escape Characters

Global functions like len() can be used with strings to get their length. The in operator checks if a string contains a substring. Escape characters, denoted by a backslash \, are used to include special characters in a string.

Accessing String Characters

Individual characters in a string can be accessed using square brackets and their index, starting from 0. Negative indices count from the end of the string. Slicing extracts a portion of the string using a range of indices.

Booleans in Detail

Booleans (bool) have two values: True or False. They are useful in conditional statements. Numbers are generally true except for 0. Strings, lists, tuples, sets, and dictionaries are false only when empty.

Boolean Functions

The any() function returns true if any value in an iterable is true. The all() function returns true only if all values in an iterable are true.

Number Data Types

Python has number data types: integers (int), floating-point numbers (float), and complex numbers (complex). Complex numbers are written with a j suffix for the imaginary part.

Number Functions and Enums

The abs() function returns the absolute value of a number. The round() function rounds a number to the nearest integer or a specified decimal point. Enums (enumerations) are readable names bound to constant values.

User Input in Detail

The input() function gets input from the user. It pauses program execution until the user enters a value. The prompt can be included directly in the input() function.

Control Statements in Detail

Control statements like if, elif, and else allow programs to execute different code blocks based on conditions. Indentation defines the code blocks associated with each statement.

Lists in Detail

Lists store multiple items in a single variable, enclosed in square brackets. Items can be of different data types. The in operator checks if an item is in a list. Items are accessed by their index, starting from 0.

List Methods

List methods include append(), extend(), remove(), pop(), and insert(). These methods modify the list. The len() function returns the number of items in a list.

Sorting Lists

The sort() method sorts the list in place. To avoid modifying the original list, a copy can be made using slicing. The sorted() function returns a new sorted list without modifying the original.

Tuples in Detail

Tuples are immutable groups of objects, created using parentheses. They are ordered like lists, and items can be accessed by index. Tuples cannot be modified after creation.

Dictionaries in Detail

Dictionaries store data in key-value pairs, enclosed in curly braces. Keys must be immutable values. Individual values are accessed using bracket notation or the get() method.

Dictionary Methods

Dictionary methods include pop(), popitem(), keys(), values(), and items(). The in operator checks if a key is in a dictionary. New key-value pairs can be added using bracket notation.

Sets in Detail

Sets are unordered collections of unique items, created using curly braces. Sets support mathematical set operations like intersection, union, and difference.

Functions in Detail

Functions are blocks of code that can be called when needed. They promote readability and code reuse. Functions can accept parameters, which are variables used inside the function.

Parameters and Arguments

Parameters are the values accepted by a function, while arguments are the values passed to the function when it's called. Arguments can have default values.

Variable Scope

Variable scope determines where a variable is accessible. Global variables are declared outside functions and are visible throughout the program. Local variables are declared inside functions and are only visible within those functions.

Nested Functions and Closures

Functions can be nested inside other functions. Inner functions can access variables from the outer function if declared as nonlocal. Closures occur when a nested function retains access to variables from its enclosing function even after the outer function has finished executing.

Objects in Python

Everything in Python is an object, including basic types like integers and strings. Objects have attributes and methods accessed using dot notation. Mutable objects can be changed, while immutable objects cannot.

Loops in Python

Python has while loops and for loops. while loops repeat a block of code as long as a condition is true. for loops iterate over a sequence of items.

Break and Continue Statements

The continue statement skips the current iteration and proceeds to the next. The break statement exits the loop entirely.

Classes in Detail

Classes are used to create objects, which are instances of the class. Classes have methods (functions) and attributes (data). The __init__ method is a constructor that initializes the object's attributes.

Inheritance

Inheritance allows a class to inherit properties and methods from another class. This promotes code reuse and organization.

Modules in Python

Every Python file is a module. Modules can be imported from other files to reuse code. The import statement is used to import modules.

Importing Modules

Modules can be imported using import module_name or from module_name import function_name. Modules can be organized into subfolders, requiring an __init__.py file in the folder.

Python Standard Library

The Python standard library provides a wide range of pre-built modules for various tasks. Common modules include math, re, json, datetime, os, and random.

Command Line Arguments

Python programs can accept arguments from the command line. The sys module provides access to these arguments. The argparse module simplifies parsing and validating command-line arguments.

Lambda Functions

Lambda functions are anonymous, one-line functions defined using the lambda keyword. They are often used with map(), filter(), and reduce().

Map, Filter, and Reduce

map() applies a function to each item in an iterable and returns a new iterable. filter() returns a new iterable with items that satisfy a condition. reduce() calculates a single value from a sequence.

Recursion in Python

Recursion is when a function calls itself. Recursive functions must have a base case to stop the recursion.

Decorators in Python

Decorators modify or enhance functions. They are defined using the @ symbol followed by the decorator name.

Docstrings in Python

Docstrings are used to document code. They are enclosed in triple quotes and can span multiple lines. The help() function displays docstrings.

Annotations in Python

Annotations specify the expected data types for variables, function parameters, and return values. They are ignored by Python but can be used by external tools for type checking.

Exceptions in Python

Exception handling uses try, except, else, and finally blocks to manage errors. The try block contains code that might raise an exception. The except block handles specific exceptions. The else block runs if no exceptions occur. The finally block always runs.

Raising Exceptions

Exceptions can be raised using the raise statement. Custom exception classes can be defined by extending the Exception class.

The "With" Statement

The with statement simplifies exception handling, especially when working with files. It ensures that resources are properly managed, such as automatically closing files.

Third-Party Packages and Pip

Third-party packages are installed using pip, the Python package installer. Packages are hosted on the Python Package Index (PyPI).

List Comprehension

List comprehensions provide a concise way to create lists. They are often preferred over loops for simple operations.

Polymorphism

Polymorphism allows functions to work with different types of objects. It's a key concept in object-oriented programming.

Operator Overloading

Operator overloading allows classes to define how they interact with Python operators like >, <, +, and -.

Coding the Blackjack Game

The course culminates in coding a Blackjack game. This involves creating classes for the deck, card, and hand, and implementing game logic.

Setting Up Variables for the Game

The initial steps involve setting up variables for suit, rank, and value. The goal is to print the card's rank and suit.

Using Lists for Suits and Ranks

Lists are created for suits and ranks. A nested for loop is used to combine each rank with each suit, creating a deck of cards.

Shuffling the Deck

The random.shuffle() function is used to shuffle the deck. A function called shuffle is created to encapsulate the shuffling logic.

Dealing Cards

A function called deal is created to remove a card from the deck. The function is updated to deal a specified number of cards.

Determining Card Values

Conditional statements are used to determine the value of each card based on its rank. A dictionary is used to store the rank and value of each card.

Creating the Deck Class

A class called Deck is created to represent the deck of cards. The __init__ method is used to initialize the deck with cards.

Creating the Card Class

A class called Card is created to represent a single card. The __init__ method takes suit and rank as parameters. The __str__ method is used to define how a card object is printed.

Creating the Hand Class

A class called Hand is created to represent a player's hand. The __init__ method initializes the hand with an empty list of cards and a value of 0.

Adding Cards to the Hand

The add_card method is created to add cards to the hand. The calculate_value method is created to calculate the value of the hand, accounting for aces.

Displaying the Hand

The display method is created to print the hand's cards. The method handles hiding the dealer's first card.

Creating the Game Class

A class called Game is created to manage the game logic. The play method is created to run the game.

Getting User Input for Number of Games

The program prompts the user for the number of games they want to play. A try-except block is used to handle invalid input.

Implementing the Game Loop

A while loop is used to play multiple games. Inside the loop, the deck is created, shuffled, and hands are dealt to the player and dealer.

Checking for a Winner

The check_winner method is created to determine the winner based on various conditions, such as blackjack or busting.

Implementing Hit or Stand

The player is prompted to choose "hit" or "stand". A while loop is used to keep asking for input until a valid choice is entered.

Dealer's Turn

The dealer draws cards until their hand value is 17 or more. The dealer's hand is then displayed.

Determining the Final Winner

The check_winner function is called one final time to determine the winner. The final results are printed, and a "Thanks for playing" message is displayed.

Summarize any YouTube video in seconds

Get summaries like this one for any video, in your language, with the free Summ app.

Download on the Apple Store
Get it on Google Play

Transcript

Full transcript of “Python for Beginners – Full Course [Programming Tutorial]”. Click a timestamp to open the video at that moment. Need another video? Use the YouTube transcript generator.

0:00 in this full course you will learn the basics of python programming i'm beau carnes with freecodecamp.org i've previously created one of the most popular javascript courses on youtube and i've created many python tutorials now i've created this complete python course for beginners you don't need any previous programming experience to follow along and all you need to code in python is a web browser in this course i will teach you all the core aspects of the python programming language and i will simplify the more complex topics python is considered one of the most popular programming languages in the world and it's only growing in popularity python excels in a wide variety of scenarios such as shell scripting task automation and web development and it's also the language of choice for data analysis and machine

0:46 learning but it can also adapt to create games and work with embedded devices we're going to jump right into it so you can start coding your first python program as soon as possible to get started quickly we'll use a replit which is an online ide that allows users to code and run programs in a variety of different languages all in a web browser and later i'll show you how to get python set up on your local operating system after the first project i'll go into more detail about each of the main features of python the section is comprehensive and detailed and in the final section you will use what you've been learning to code a blackjack game with me guiding you every step of the way throughout the course there will be a little repetition of some of the key python programming concepts to make sure

1:32 you have a deep understanding of the language so let's get started we're going to start by creating a simple rock paper scissors game and we'll start by going to replit.com replied provided a grant that made this course possible and replie is going to make it super easy to get up and running really quickly so you can either sign up or log in and create an account i'm just going to use my google account okay now that you're logged into replit you can either just click the create button or this plus button over here to create a new replit and i'll make sure to create a python replit but you can see you can also select all sorts of different programming languages oh these are just the ones that start with the word python but so there's there's tons

2:18 of different programming languages you can select but in this case we are just going to use python and then i'll click create reple okay so let me just kind of show off replica a little bit this is where we're going to create our python code i'm going to zoom in just a little bit so we're going to write the code right here and then we can see some output over on the right side and then you can create different files over on the left side here and then there's some other things like you can connect to version control and if you have environment variables we're not even going to be discussing those in this course there's a debugger you can connect to a database and just some other things but we're mainly going to just be using this main.pi program to write our program and we're going to see

3:04 the results in the console so i'm just going to close this files window so it's a little bigger here i'm going to start off by showing you how to create a variable with python so this is a rock paper scissors game and there's going to be a players a player is going to have a choice and a computer is going to have a choice so i'm going to create a variable called player choice and i'm going to set that equal to rock so let's look at a few components about this this is the variable name player choice and you can see if you we use an underscore that's just kind of the convention for python to use an underscore if you're going to have a space in the variable name and we're

3:51 going to assign it that's what this equal sign this is the assign operator and we're going to assign it to a string a string is just a word or a collection of characters like rock and we're going to put quotation marks around it now we could have also used a single quotes instead of double quotes as long as you use the same quote on each side that's what's important so we've now created a variable called playerchoice and assigned it to rock and now we can reference this variable later and whenever we reference the variable called playerchoice it's going to the code is going to automatically replace that player choice with rock so this is going to be a very interactive project i hope you're following along i hope you have already

4:38 got replit loaded up like this now throughout this project i'm going to tell you what the next thing to do is and i want you to try doing it yourself before you watch what i'm going to do so periodically you'll want to pause the video based on and what i say you and try to implement what i say before you come back to the video and watch me implement it and see if you've implemented the the same way so i'm just going to zoom in one more time and this is the first thing i want you to do see if you can make another variable on the next line so you're going to press return or enter to go to the next line and this variable should be called computer choice and you should set it to equal paper

5:24 okay so you can pause the video and see if you can make a variable called computer choice and set it to equal paper so here it's pretty simple here it's going to start simple but it's going to get harder as we go so computer choice equals paper okay so like i said it's starting simple but it's going to get more complex as we go along if you've done that you've now written your first line of python code in this course okay now i'm going to talk about functions a function is a set of code which only runs when it is called so i'm going to show you how to put this code into a function now one thing about python is that indentation is very important so after we create a we define the name

6:11 of a function any line of code that's indented the same amount is considered within that function so i'm going to create a new line of code at the top and i'm going to call it get choices okay so we define the function with def and get choices and i'm going to select all these these two lines of code at the same time and just press the tab key and that's going to indent all these the same amount and you can see sometimes they'll be squiggly lines and if you hover over some of the squiggly lines it will tell you something in this case it just says the local variable called player choice is assigned to but never used that's not

6:59 necessarily bad it's just it's just telling us that usually if you create a variable you're going to want to use it later well we are going to use it later we just haven't gotten to it yet so sometimes the squiggly lines will indicate there's some sort of error in the code usually i think it's the color red will indicate an error but if it's a different color it just may mean that there's something maybe not quite right but it's not really that big of a deal so if you have a variable that's assigned to but never used that's not going to stop your program but it's just saying that it's not this variable isn't really being used for anything yet but we will change that this function i'm going to show you how to call a function later but we're creating a function called getchoices that assigns these two variables and

7:45 it's also i'm going to put another line at the very end here and it's a return statement and i'm going to return player choice this will indicate what's returned when this function is called so later we'll call this function get choices and it will return something it will return the player choice which is right here we'll turn in this case rock that we can use somewhere else in our code and i did just happen to put an extra line here that's just that's optional i put a blank line here just to kind of make things easy to kind of organize the code a little bit so different sometimes i'll just put an extra line between different sections of code and it just makes it easier to

8:30 identify the different sections when you're looking at the code for the computer those extra lines don't mean anything the indentation though definitely does mean something so as long as every line of code is indented the same amount as the previous line of code then it's all within the same function okay so this is what i want you to do see if you can change the return statement so instead of returning player choice it's returning the computer choice so that's pretty simple it's now returning the computer choice here now i'm going to create another function down here this is just going to be an example function just so i can demonstrate something to you and then we'll delete it it's not going to be

9:15 part of our rock paper scissors game but i'm going to create a new function called greeting and then i am going to add what it's going to do oh yeah put the semicolon you also know a colon so a function always has to have a colon at the end of how we define it so i'm going to return a string and it's just going to say hi and one thing you'll notice is that there's no you don't have to put any anything at the end of each line some programming languages such as javascript you're going to put a semicolon at the line at the end of the line but in python it doesn't matter you don't put anything at the end of each line so now i'm going to call the function to call the function i just type the name and i put the parentheses at the end so it's going to say so greeting is now going to call it's going

10:03 to call this function and that's going to return the string hi now it's not going to do anything with the string because our program doesn't do anything with the string that's been returned it's not going to go into the console or anything but let's add additional code so we will make this string hi go on to the console first let me create a variable that takes what this greeting function returns so i'm going to type in response equals greeting so now we set the the what greeting is being returned to this variable called response and now i can use the print function and i can print the response and this will print it to the console so now i

10:48 can we have this green button here this runs the program i'll click this green button here and now we can see it's high so this response is getting this high from here and then we're printing it right there okay i'm actually going to delete all of this and what i want you to try to do now is to call the get choices function and store the response in a variable called choices and then print the value of choices to the console so you can pause and try that really quick and then i'm going to show you how okay so remember the variable is called choices and we're going to set that equal to the get choices variable now ins or the get choices function now instead of typing out get choices you can see that

11:34 this code editor is actually giving us suggestions on what we want to put in here so i just typed in get and you can see it's now saying get choices right here so i can instead of typing out the whole thing i can either click there or i can just press the tab key and it's going to fill in the rest of that function name so that's just something little that makes it easier to write a program and you don't have to type out every single thing so if you've already created a function or a variable then the the code editor then reply will will suggest what you may want to fill in when you're typing and most other code editors do something similar it's called code completion so i'm going to but i still have to add parentheses at the end and now i'm going to print

12:20 the choices [Music] okay so i'm gonna just click this play button to make sure it does what we're trying to do yep it clicked paper great now let's talk about dictionaries dictionaries in python are used to store data values in key value pairs so let me just show you an example okay so a dictionary is going to have these curly braces at the beginning and end and then here's a key value pair there's one it's separated by a comma and then here's another key value pair so we're setting name we're setting that to equal bow and we're saying the color to equal blue so here's the key here's

13:05 the value here's the key here's the value and the key or the value in a dictionary can be a variable like the color we could set that we already created this variable here i'm just going to copy the word choices and we can put choices and you can see now it's not surrounded by the quotation marks so if you surrounded by quotation marks it's a string but if we don't surround it by quotation marks it's getting the the variable here choices so this would be set to paper because that's what choice is going to is going to equal so we're about to delete this line because that was just an example but now before the return statement in this function we're going to add a new line we're going to create a variable named choices and make it equal to a

13:50 dictionary the first key should be player with a value of the player choice actually this variable here the second key should be computer with a value of computer choice and then we're going to update the return statement to return the the choices dictionary now i'm not going to keep telling you to pause and try it yourself so just the rest of this time whenever i say what we're going to do you'll know that after i get done explaining it you can pause it and try it yourself but that's what we're going to do now so i'm going to create choices and it's going to be a dictionary and then it's going to have a player that's the key and the value is going to

14:37 be player choice and i was just able to press tab to fill that in and then we're going to have computer and it's going to be computer choice and you can see sometimes if it goes to the next line there just won't be a line number right here but i can move this over for now and then i am going to oh i forgot to put the equal sign that's what that red squiggly line means so because the red means there is a problem in the program so it's not going to run correctly now the orange just means that we haven't used choices yet which we will right now because we're going to return choices okay so now we don't have any squiggly

15:23 lines because we're using every variable that we created and we're returning choices here so you may have noticed that player choice it does not actually get set to the player's actual choice so let's fix that the input function gets input from a user and will use it to get the player's choice so instead of having players choice equal rock we're going to make players choice input enter a choice rock paper scissors okay so this is how you get input from a user we use the input function and this

16:09 is going to be something that's going to be printed we'll print to the console here and whatever the result of this input will be that the the player that the user entered will get stored to this variable which we then can use later in our program so let's just try that out i'll click run and enter let me just stop and run it again okay enter a choice rock paper scissors i'll just put rock and now you can see the player's choice we're still printing that and it's going to print as rock great now let's just clean up this code a little bit we still have this here we don't need that dictionary that's not going to be part of our final code and now we'll make it so the computer can actually make a choice

16:55 so we're going to learn about importing libraries creating lists and calling methods python libraries are a set of useful functions so you don't have to write code from scratch when you import a library to your program you get access to more features without writing additional code with basic python it's challenging to get your program to do something randomly but it's easy to choose something randomly using the random library so let me show you how we can import the random library import statements are used to import libraries and they're usually put at the top of a program so i'm going to press enter a few times here to add some lines at the top and i'm going to do import random so now we are going we we've imported the random library

17:43 so we're going to use that random library soon but now let's learn about lists a list in python is used to store multiple items in a single variable lists are surrounded by brackets and each item is separated by a comma so here's an example i could create a variable called food and set it to this list it's going to have three items pizza carrots and eggs [Music] so this is a list of strings and then you can also get a random item from the list using we're going to use now we've imported random we can get a random item by using that that random library so i'm going to put dinner

18:28 [Music] equals random dot choice and then i'm going to pass in the the list here so using the random library we can call choice and then we can pass in a list and it's going to choose a random item from that list and and set it to equal this dinner variable so right now the computer choice always equals paper but we want it to be a random choice between rock scissors and paper so before the computer choice variable is created we'll create a new variable called options and assign it to a list of the possible options rock paper scissors then we'll set the computer choice variable to be a random choice of

19:14 one of the items in the options list okay i hope you already tried this now but let me show you how that's going to work we'll create options and we'll set it equal to this list of rock [Music] paper scissors and you can see the code editor will often pop up these boxes with more information about what we're doing to give us some some help with what we're trying to do here so we're going to set this computer choice to be random dot choice food not food i was looking at the food down there that's gonna be options

20:02 there we go and let's just um try running this program and seeing what happens so i'm going to put rock and then we see the computer chose scissor it should be scissors that's why we're testing it out i guess i spelled that wrong okay so scissors with an s so now let me try running it again and you can see it shows scissors but if we run it enough time it should now it's choosing paper because it's choosing it at random okay that's working okay so now let's just delete all this code after the get choices function we don't need to test that get choices function anymore and now let's create a new function called check

20:48 when so you shouldn't know enough how to you should know enough about how to create a function so def check [Music] when so this is just an empty function with nothing inside it yet but before we add oh with the colon so before we add any code inside the function we're going to create some arguments function can re functions can receive data when they're called the data are called arguments so when creating a function you can specify arguments inside the parentheses so we've been using this empty parentheses but i can uh put in tooth i can put in things within these parentheses when this function is called we're going

21:33 to give it two pieces of data we're going to pass two pieces of data into the function the first piece of data is going to be player the second piece of data is going to be computer so the you can basically call these anything you want uh these are just we're creating new variables but when we call these functions we'll pass in two pieces of information that will then be assigned to the variable names player and computer that we can use inside the function so for now let's finish off with to a for a complete function the function has to have some code within the function so let's just add a return statement that's just going to return a list containing the elements player and computer

22:22 so this check when function shouldn't actually return this this is just to kind of get get it quickly created it should actually return different things depending on the player and computer arguments an if statement will allow a program to do different things depending on certain conditions so an if statement will first check a condition and if the condition is true then all the lines of code under the if statement that are indented the same amount will execute so as a quick example i can say a equals three b equals five and then we can create an if statement here if a is greater than b then we will do something like print

23:11 yes or we can do if a is less than b or we can do if we want to check if a and b are equal we can do eq we we'll put two equal signs now this is very important you never want to use one equal sign because a single equal sign is the assignment operator that's how you assign what variables are equal to so if you use a single equal sign or like then if i put if a single equal sign b without a double equal sign that is going to set a to equal b which is not what we want the double equal sign is going to check if a and b are the same value basically it checks if two values values are equal now you can also do a not equal so if you use the

23:57 exclamation point that's not equal or you can use less than or equal to or you can do more than or equal to so i'm just going to delete all this for now so now we're going to update this risk turn statement uh before the return statement we want to we're going to check if player if player equals computer and if so if true will return the string it's a tie so let's do that if player equals computer and this is something that maybe you figured out yourself before you before you're watching this will return a string and the string is going to be it's a tie

24:46 okay so now it's only going to return so a function does not have to return something and for this function it's only going to return something if this is true if player equals computer if not it won't return anything and just to make make you notice this see this line is indented within the if statement which is indented within this function and just really quick thing to note for a return statement parentheses are optional so i could also add parentheses like that but you don't need them but for now i'm just gonna get rid of them [Music] so currently when there's a tie the program now returns it's a tie

25:32 but how does the player know that's true now let's have the program print which options that the player and the computer chose you can concatenate strings with the plus operator that just means you can combine strings with other strings or strings with variables so let me show you how you can print which options were chosen so i'm going to print you chose and then i'll put player so you chose and then we have to add a space here because it's going to print a space and then it will choose it will print this so if the player chose rock we'll say you chose rock

26:18 and then we can concave so we concatenated these together but we can add another plus sign and put another string here and it's going to say computer chose oh it's like being covered up here by everything computer computer chose now i'm just about to type it in but see if you can figure out what to add at the end here to put in what the computer chose so computer chose computer or the the value of this variable here so a lot of times when with programming there's a bunch of ways to do the same

27:05 thing so this is one way to combine strings and variables together there's another way that's a little simpler called an f string so an f string will allow you to make strings with and with variables and other python code so to do that you just put a variable or you just put f at the beginning of a string so let me just give you an example so we do age equals 25 we're going to create a variable and then i'm going to make an f string we'll make it a print statement and i'm going to put a string in here but instead of starting with a quotation mark it's going to start with an f and then i'm going to put gem is and then whenever you want to put a variable or any kind of python code we're going to put some curly braces and i'm just going to put the variable within the

27:52 curly braces so years old and i'll put the end of the string or let me put a period here okay so gem is age which is going to be 25 years old so the f string is just a slightly simpler way to combine the strings and the variables so what i want you to do see if you can figure out how to update this line right here so it uses an f string and it uses these curly braces instead of all these pluses up there so yeah we're going to put f and i can delete a lot of these things here [Music]

28:40 and then i'm going to put some curly braces you chose player there we go okay you cho there was a comma here you chose player computer chose computer okay so now we've been able to put in the variable within this string with the f string so we're going to test this out uh so in a code the code in this function never gets run so when we press the run button it's not going to run any of the code within the function unless the function is called within the program so we're not going to test out this

29:25 function all right now what i want you to do is see if you can add a line to call the check when function and then just call it with uh rock and paper so we're going to just do check when rock or actually we have to pass in strings here rock paper so this is going to it's going to call this function with rock in terms instead of player and paper instead of computer so let me try stride running this program you chose rock computer chose paper and just don't worry about these little icons sometimes they just block what's in there but it's still behind that little search icon so it's to see it's

30:12 doing you chose rock computer chose paper now let's get back to checking the winner so far this function is only going to check if there's a tie now we'll start adding code to check different wing conditions so let's learn about else and elif statements okay so down here i'm just going to give you i'm just going to paste an example so so here's the if statement if age is greater than or equal to 18 it's going to print this else so anytime this is not true then it's going to print you are a child okay now here i've combined it with something else the ellis statement ls just stands for else if it combines else and if so you have to put a condition so

30:57 if age is greater than or equal to 18 print you're an adult else if now we're going to check if age is more than greater than 12 you were a teenager else if age is greater than 1 print you are a child or else if none of these other things are true we'll just print you or a baby so and it's it's only going to do one of these it's going to get to the for once it gets to the first one that's true then it's not going to check the rest it's just going to kind of go to the next line of code after all these statements so it's just going to choose one and once it gets the first one that's true then it's be done with this whole section of code you can also check for two conditions at

31:44 once let me give you an example i'm just going to delete all this code and i'm going to create an alif statement here elif else if and we're going to check if player is equal to rock and i'm just going to type in the word and and computer is equal to scissors so now i'm checking if both these conditions have to be true so this condition and this condition have to be true before the following statement will happen which we're going to just put return rock smashes [Music] scissors you

32:29 you when [Music] okay now the next thing we're going to do let's see if we can figure out how to do this we're going to add another lf statement and this time we'll check if players equal the rock and computer is equal to paper and if so we'll return paper covers rock you lose so we're going to make this kind of easier by just copying this code and then i'm just going to paste in this and then i'll just change this so players equal the rock and computer is equal to paper instead of scissors paper and it's going to say paper covers rock

33:17 you lose and we won't even have an exclamation point anymore because it's not exciting to lose okay and you can kind of see there's a few we could add a few more elif statements to cover all the different situations but instead we're going to talk about refactoring refactoring is the process of restructuring code while keeping the original functionality when created pro when creating a program it's common to refactor code to make it simpler or more understandable so we are actually going to refactor this code that i've highlighted now and we are going to instead use a nested if statement a nested if statement will make the code more understandable at a quick glance

34:03 like so you can put an if statement inside another if else or else statement so you'll notice here the first elf statement is if player equals rock and the second l of statement is if player equals rock so see if you can figure out how to refactor this to not have to use the and anymore we're just going to use one if statement and one else statement and then an if statement under that elif statement if that doesn't make sense you can just see what i do right now so i'm going to just move this down a little bit i'm going to actually copy and paste some of these items but we're going to start with l if player equals rock we're not going to have this i'm going to put this on a new line and say if computer equals scissors so first

34:51 we're going to check if player equals rock and then if so we're then going to check it's going to be a nested if statement if computer equals scissors and if computer equals scissors then we're going to use this this return statement here so i have to make sure it's indented correctly it's going to re so this we have we have player if player equals rock then if computer equals scissors we'll return oh this needs to be indented one more time to be on inside that if statement and now we don't even need this elf statement this can just be an else statement else because if the computer equals scissors there's only one other option because we already know if player equals rock and computer

35:36 equals rock will have already returned it's a tie and by the way once you return something the rest of the code in a function does not run so if we're returning it to tie nothing else after that is going to run so we know that computer can't equal the rock at this point so it's either going to be scissors or paper so i don't we don't even have to check if computer equals paper because at this point computer has to equals paper and then we'll just return this this line let's see there we go return paper covers rock you lose so now we just basically have to add two more sections similar to this so this one is if player equals rock then we have to have another section if player equals paper and then if player

36:22 equals scissors and then we just have to have the the stuff inside is going to be pretty similar just corresponding to the different relationships between rock paper scissors so i'm just going to copy that and then i will paste it here and then one thing is important to make sure this elif statement lines up with this else statement and this is now going to be paper and then we are going to check if computer equals rock and a computer equals rock then we will say that paper covers rock you win or we'll say

37:08 scissors cuts paper you lose and then the final one which at this point i'm sure you can figure out on your own we're going to add one more section and this if player equals scissors and then first we're going to check if computer equals paper if so we will do scissors cuts paper we're just making sure we're just making it so every time the first one is you win the second one is you lose but you could do it the other way around and then we will do rock smashes scissors you lose

37:55 okay we're almost finished with this whole program so both the get choices function and the check win function they're both complete now let code to call the functions and play the game so first let's remove this this check when now we'll create a variable called choices and make it equal to the result of calling the get choices function and we just have to make sure it's not indented it's on the the first the first column i guess right here not ended at all so we'll do choices equals get choices [Music] and one thing about this is it's going

38:40 to return a dictionary so if we look at the get choices so it's returning choices and it's going to be a dictionary like this now let me just copy this i'm going to show you something down here i'm going to just paste it down here and we'll just make an example of what it could look like it could look like rock and paper i always use rock and paper as examples because scissors is a little harder for me to spell so so that's a little easier so so let's one thing we haven't talked about is how to uh how to access a and specific element within a dictionary so this is a dictionary so let's say if i call this um well i'll just call it choices even because we're going to delete that and

39:26 so we're only going to have this choices but if choices equals this and let's say i just want to get the the choice of the player let me show you how i would do that i'll just do p choice for player choice and i'm going to put equal choices and to get just the the value of the player i'm going to put brackets so the brackets look like that and then i have to put the the key that i want the value of so the key would be player so if i put the name of the dictionary which is this and then i put some brackets we're going to use brackets to identify what is the key that we want the value of so here's the key of the with the value of rock and here's a key with a value of paper

40:11 so this is how we can get the player choice and i'm sure you can under see how you get the computer choices if instead if we take this computer word and put it right here uh computer okay i'm just going to get rid of all this here and we're going to we have the get choices here and now listen carefully to what we're going to do next we are going to create a variable called result and make it equal to the result of calling the check win function and when we call the check win function we're going to pass in the value of the player key and the computer key of the choices dictionary so let's do that so then you'll see what

40:58 i mean a result is going to be we're going to call [Music] check when and then we are going to pass in we're going to pass in we have choices player and choices computer so because remember we had that we i showed the example that dictionary so we're getting the player key the value of the player key and the value of the computer key so now we know who wins we've now this result variable is going to be one of these strings have been returned either it's a tie rock space of

41:43 scissors paper covered rocks and so on so now we just have to print the result we're going to print the result okay we can try out this game i'm going to click the run button okay this is why it's sometimes better to test a little earlier i just forgot the semicolon on some of these so um semicolon and see there's a red arrow i should have seen that semicolon and semicolon okay now let's try it i'm going to play the program into a choice i'm going to do rock and i just noticed something else i

42:28 want to change so enter a choice here i started there's a parenthesis here there's no parentheses at the end so again i'm just going to change that really quick so enter a choice and we're going to put it in parentheses here and test again so rock okay you chose rock computer chose rock it's a tie okay i'm gonna play it again paper you chose paper computer chose scissors scissors cuts paper you lose okay we just created a python game so hopefully this gives you a better understanding of what it's like to program in python and you you now know about some of the basic concepts of python now there's a lot more to learn in python and we're going to be covering

43:14 a lot more in this course i just wanted to start with a game and a full program so just right off the bat you could go to program so in the next section i'm going to start going over in detail all the most common features of python and we're going to cover some of the features that we've already used in this game plus a lot of additional features additional common features that were not used in this game and then in the final section of the course we're going to code a more complex game a blackjack game so let's get started with the next section one of the quickest and easiest ways to get started with python is by using replit.com but you may also want to get python running on your local computer so

44:01 if you want to do that you can start by going on over to python.org and these go to the downloads menu and then you're going to just click what you want to download for it for so it's going to default to be for you the operating system you're on but you can also go to other platforms and make sure you can and then just find the platform that you want to download on and there's going to be instructions on here that's going to tell you how to go about getting installed on your specific computer so there's a few different ways to run a python programs and one of the ways is with an interactive prompt so after you get installed if you open up your terminal and type in python or sometimes it's going to be python 3 depending on how you got it installed you're going to

44:48 see this interactive prompt and then you can just this is called a python rebel it's it's different from a rebel creating with created with replit but you can start coding in python right on here so i could say name equals bow and then you have to make sure you put the the quotation marks at the end and now i've gotten a variable stored as bow and then i can just type in the variable name name and it's going to show you show me the value of the variable and you can type in most different python commands right into this inactive prompt here and then i can just quit it when i'm ready to quit it's also common to run python using visual studio code so if you just search

45:35 for visual studio code you can get to the the download page and then you can just download it for your system and there's also you can download for different systems and then once you open up visual studio code to get python working you're going to want to install the python extension so i'm going to click over here to extensions and you can search for python or it may just be listed here under popular extensions and i'm just going to click install and this is going to make it easier to work with python on visual studio code so now i can just kind of close some of this stuff here and i'm going to create a new file and i can just call the and i can just

46:21 type in name equals bow print name and then if i save this as test.pi it's going to now it's going to add the colors that correspond to python and then i'm just going to click this play button here and it's going to play it's going to open up a terminal window here and it's going to run the program and it's going to print bow that's what my program did if i zoom out a little bit you'll be able to see the difference so well we just print the name and it and it runs the program just like that and then you can see on the terminal how the the command that was used to run that so

47:07 we could use the same command on any terminal and instead of typing this whole thing for the location of python 3 i can just do python 3 and then you this is where that file is located so just copy that and i can paste it in here and it's going to run that program in this section we'll learn about the core features of python i'll go into more detail about some of the things we learned in the first project and they'll be covering a lot more concepts this section was heavily inspired by the python handbook by flavio copes and you can check that out on freecodecamp news and like the first part of the course i'll be running python in replit so once you get logged into replit just like i already showed you before you can hit the plus button here or the create

47:52 button to create a new replit and then you can search for the programming language or you can just click it down here python we'll just create a python repel and then we can instantly start creating writing python code in replit so like i showed before we got our different files here we're just going to start by using one file here and this we're going to encode and this is where it's going to appear if we we run the code so i'm going to close off the list of files here and let's just start at the beginning again so you've gotten used to coding in python through creating a rock paper scissors game but now we're going to kind of do a deep dive into all the basic commands of python so there's

48:37 going to be some review but we're going to be going into more detail about each of the elements and the first thing we're going to talk about is variables so we can create a new python variable by assigning a value to a label using the equal sign or the assignment operator so let me give you an example just like i was showing you before just name equals bo so let me just zoom in a little bit more here and so now our variable name is name and we've assigned it the value of bo and then we can also uh create we can create a variable with a number so i could do age equals 39. so a variable name can be composed of characters numbers and an underscore

49:23 character but and it cannot start with the number so it could be anything like name one it could be all capital letters it could be it could have an underscore it can start with an underscore like i said like that and you can see that these are all it's putting these red squiggly lines because it's showing that that's not actual python code if you're going to create a variable you should be assigning it to a value or you should be using a variable that already exists but i'm just showing you some different examples of different variables now so here's an example of an invalid variable name if you just start with a number like that that can't be a variable because you can't start with a number

50:10 and i couldn't put something like test exclamation point you can't use exclamation points you can't use percent signs and other than that anything is valid unless it's a python keyword so there are some keywords a keyword is something that's used to to write python like for if while import these are all words that have very specific meanings within python so you cannot use them for a variable name now there's no need to memorize them as the python editor here will alert you if you use one of those as a variable so that was just like if i say if equals hi and then you can see it's going to show you right here with these squiggly lines

50:56 that we've done something wrong invalid syntax because and then also you can see that it turns blue this word turns blue because it's a keyword you can't use it as a variable name so like i said it's going to alert you if you if you use a keyword as a variable and you'll start to gradually recognize them as part of the python programming language syntax now let's talk about talk about expressions and statements in python so an expression is any sort of code that returns a value like for instance if you do one plus one or if you just do a string like bow this is going to like this is going to return to this is going to return the string bow so a statement on the other

51:44 hand is an operation on a value so for example these are this is a statement here because we have an operation we're assigning this to the variable and then another statement would be like this print name so that's going to be a statement because it's doing something to the value now a program is formed by a series of statements and each statement is put on its own line like we have these two lines here but you can use a semicolon to have more than one statement on a single line so i i could put a semicolon here and then if i run the program it's still going to print the name and let's just do that we already learned how to run a program in replica click this button right here but we can see it's going to

52:30 print bow and if i put these on two different lines it's going to do the same thing if i run the program it's going to still do the same thing here now let's talk about comments this is something we haven't talked about in this course yet so in the python program everything after a hash mark is ignored so if i put a hash mark i can say this is a commented line and when we run the program this line is going to be completely ignored and then we can also put in inline comment if i just put the hash mark here this is an inline comment and the cool thing about most code editors including replit is it's going to put comments going to make them gray so you know that this isn't really part

53:16 of the program this is just some sort of special note that the programmer wants to put as part of the program so i want to emphasize again how important indentation is so it's very meaningful in python so you can't randomly indent things like you can't just press tab here to indent here and how this is kind of lined up here this line up here you can see this red squiggly line says unexpected expected indent so some other languages do not have meaningful white space an indentation doesn't matter but in python indentation matters so in this case if you try to run this program we can run this and you'll see an error right here showing up in red here it says indentation error

54:02 unexpected indent because indentation has a special meaning so i can just unindent that here everything indented belongs to a block like a control statement or a conditional block or a function or a class body and we'll be talking more about those different blocks now let's talk about data types python has several built-in types so for instance this is a string so anything surrounded by quotation marks is a string that's one data type and you can check the type of a variable by using the type function so i could say type and then i'll put name and to make sure to be able to see in the console i'm

54:49 going to print what the type is here and if i press if i run the program we'll see that the type is the class of str which stands for string and then we can test to see if something is a string by comparing it to str so i could do equals equals str and then if i run that it's going to say true because the type of name does equal a string and then we can also use is instance so i'm going to uh so if we instead of doing type we do is instance and then we

55:35 have to pass it two things so the first thing we're going to pass it so we have the is instance we're passing it the name that's this variable and str we're trying to see if name is an instance of a string and if i run that it should say true again so we've been testing against the str class the string class but it works the same for other data types so so there are some data types around numbers so an integer number integer numbers are represented using the int class or the int class and floating point numbers or fractions are a type of are the type float so i can say age equals 2 and then we can just check

56:22 is instance and i can pass in the age and then i can pass in an int so if i run that we're going to see that i've done something wrong oh i spelled that wrong there we go okay now i'm going to try this and we'll see true true and i can also type in float true false it's not a false or it's not a float because it doesn't have a decimal point if i did 2.9 then it should show that it is a float because it has a decimal so python automatically detects the type from the value type so it automatically knows this is a string it automatically

57:08 knows this is a float but you can also create a variable of a specific type by using the class constructor passing a value literal or a variable name like for instance we have this and we check to see if this is a float and it's saying false but i can make it a float by typing in float and just p putting the value into the flow here so we're going to make it a float so now it's true true and you can do the same thing with strings or integers or other data types and you can also convert from one data type to another by using the class constructor so so that's basically what we did we just converted this from an

57:54 integer to a float but i can also do something else i can convert something from a string to an integer so for instance i'm going to we'll just get rid of this one completely here and we'll just use this one so a string is anything in quotation marks so if i do 20 age 20 and i test if this is a an int it's going to say false it's not an n so i'm printing whether it's an instance of an int but i can convert this string into an integer by just doing integer and this let me run the program and it says true another thing about this is you don't

58:40 just have to pass in the actual data or the actual string i can pass in a variable so i can say number equals and now i'm going to make it a an x it says number but it's actually a string but i can pass in the number here and then it's going to set that to age and it's going to be true so we create the string we convert the string to an integer and we tested that that age is an integer so when we do something like this this is called casting we are it's basically trying to extract an integer from this string of course the conversion might not always work depending on the value that's passed so for instance if we

59:28 write test here in the string instead of the 20 we may get an air so let me just run this and see now we have an error it says invalid literal for for int int with base 10 test so we can't convert the word we can't convert the string test to an integer so python does its best to do the conversion but it doesn't always work there are a few other types so let me see are some other common types of types so there's the type of complex for complex numbers bool for booleans list for list tuple for tuples range for ranges dict is our dictionaries and set is a type for sets and we'll explore all these soon we'll go into more detail about about all

1:00:14 these different types of types well now let's talk about operators we've already seen one operator that's this one that's the assignment operator but there's also arithmetic operators comparison operators logical operators bitwise operators and plus some interesting ones like is and in so we're going to be going over a lot of those right now so we talked about the assignment operator which is used to assign a value to a variable or to assign a variable value to another variable now let's talk about arithmetic operators it's just what you use to do math mathematics so here are the different arithmetic operators so we have plus one plus one equals two then minus multiplication division

1:01:01 we have remainder so four divided by three equals one but there's a remainder of one we have exponents four to the power of 2 is 16 and floor division so floor division does a division problem and then just basically rounds down so floor division does the division and rounds down to the nearest whole number so actually this would be better seen if we do four five divide by two five floor division divided by two is going to be two normally be 2.5 but floor division is rounding down to the nearest integer the nearest whole number and then also note that that the minus can also be a make something a negative number

1:01:47 so i could do 4 plus negative or i mean 1 plus negative 1 and then that's just going to equal 0. and then the plus operator can also be used to concatenate string values that's something we talked about earlier but i could say scamp and then put a plus is a good dog and then like if i print this out i put the the parentheses around it i can and then we'll see the whole string here sk scamp is a good dog that was the name of my first dog when i was a kid so we can also combine these arithmetic operators with the assignment

1:02:35 operator let me show you what i mean so let me just get rid of this here and i'm going to do age equals 8 and age plus equals [Music] 8 and i'll do print age so we've so all these different operators can be assigned with it can be combined with the assignment operator and now it's going to add 8 to the age so if i run this it's 16. so this actually just means age equals age plus

1:03:20 eight so this age plus equals eight is the same as saying age equals age plus eight so it's just going to add this number to the current age and set it equal to the age and you can do that with any of these like i could do times and that would be age equals age times 8 and 64. and so on with any of these arithmetic operators okay now let's talk about comparison operators now we talked a little bit about them before but let's see some examples again so this is to compare if two things are

1:04:05 equal and then we have not equal we're comparing them to see if they're not equal or count this is if a is greater than b or more than b and then this this is less than or equal to b now let me just tell you a trick of how i keep the keep track of which one is greater than and which one is less than if you see this less than one if you kind of tilt your head a little bit it kind of looks like an l see like l and this one doesn't look like as much of an l so this less than operator kind of in some ways looks like a capital l that's kind of just squished over and that's how i keep track of which one is less than which one is greater than and so these are all going to give either a false value or a true values

1:04:53 speaking of true and false true and false are examples of boolean the boolean data type the boolean data type just means true false or true so a boolean is either going to be true or false there's only two options and there are a few boolean operators so let me show you what the boolean the boolean operators are either not and or or so when working with two or false attributes those work like logical and or and not so when you're using uh not it means it's not true you're checking you're checking to see something is not true and means they both have to be true

1:05:38 and or means either this one has to be true or this one has to be true in order for the full thing to be evaluated as true and let me show you something about or now or using an expression returns the value of the first operator operand that is not a false value or a falsie value otherwise it returns the last operand so it's going to return the first operand that is not a false value but since this is a false value it's returning the second operand since this is a false value it returns the second one since this is not a false value it will return the first one and this is considered a false value if

1:06:24 it's just an empty bracket that's false so it's going to return the second value which just happens to be false and since this is a false value it's going to return the second option which also happens to equal to false so one way to think about it for the word or is so the pi this is how the python docs describe it if x is false then why else x so this would be like x this would be y if else is false then why else x and then for and down here let's look at some examples for and and only evaluates the second argument if the first one is true so if the first argument is falsy such as false zero and empty string

1:07:11 empty brackets it returns that argument otherwise it evaluates the second argument so the way the way the python docs describe it is if x is false then x else y okay let's quickly discuss bitwise operators they're very rarely used only in very specific situations but it's worth knowing what these bitwise operators are just in case you're in the very rare situation that you need to use them and then two other types of operators are is and in now is is called the identity operator it's used to compare two objects and returns true if both are the same

1:07:56 objects if both are the same object and i'll be talking more about that later in the section on objects and then in is called the membership operator this is used to tell if a value is contained in a list or another sequence and we'll be talking more about the in operator when we're discussing lists and other sequences later in this course and the final thing i want to talk to you about is the ternary operator now the turn area operator in python allows you to quickly define a conditional so here will be like kind of the slow way to do it without a ternary operator so let's say you have a function that in this function is comparing age with 18

1:08:43 and it's going to return true or false depending on the risk result so instead of writing like this we can implement it with a ternary operator so let's do death [Music] is adult i'll call it is adult 2 because it's the second way of doing it and this time we're going to use the ternary operator it's just going to be return true if age is greater than 18 else false so you can see first we define the result if the condition is true

1:09:29 then we evaluate the condition and then we define the result if the condition is false it's basically an if else statement all on a single line okay let's talk more about strings in python so a string in python is a series of characters enclosed in quotes in double quotes or it could be single quotes as long as the type of quote is the same on both sides and we already talked about how you can assign a string to a variable [Music] and we already talked about how you can concatenate two strings using the plus operator like phrase

1:10:14 equals bo and then you can concatenate with the plus operator is my name [Music] and then also instead of putting a string here you can put the variable so i could put name is my name and we already have the variable here to equal bo so when you concatenate you can concatenate the strings or the variables you can also append to a string using the plus equal operator so let's say i want to add to this name and i'm so i'm going to say name plus equals is my name so we're adding is my name to

1:10:59 the end of this so i can say print name and then we can see what it looks like when you use the plus equal operator so bo is my name and then we already talked about how you can convert a number to a string using the str class constructor like if we had age equals we could make this a string but we passed this integer it converts to a string and now it's going to be a string now here's something new a string can be a multi what can be multi-line when defined with a special syntax so if you enclose it if you enclose the string in a set of three

1:11:45 quotes so let me show you an example get rid of all this and i'm going to print an entire string here so we're going to make this a multi-line string i'm going to put three quotation marks and then it's going to start with three quotation marks and end with three quotation marks and then i can make it multi-line so i can say bo is and then i can put some extra lines 39 years old now if i print that and you can see it's going to print the different lines here so we just made a multi-line string and you can also instead of using the double quotes you can put a single quote

1:12:31 as long as they're the same at the at the beginning and ending now a string also has a set of built-in methods let me show you an example so if i have this string bow but i'm going to put at the end of the string i'm going to put dot upper and i put parentheses at the end so if i run this now it's going to print it in all capital letters and the same thing you can use with lower so if it if i had a string that had a few capital letters okay now it's all lower now i can also type in a title and this is going to make each lut so i can say bow

1:13:17 person uh and i do this so it's going to cat it's going to a title that's going to make the first letter of each string a capital letter i can also check things like i can say is lower and it's going to check if it's all lowercase letters false but if i make it so it is all lowercase letters it's going to say true so here's just a list of a few common ones [Music] you can do is alpha to check if it contains only characters is l num to check if a string contains characters or digits and is not empty is decimal

1:14:03 lower to make it lower case is lower upper is upper title starts with to check if it starts with a specific substring to check if it ends with you can replace part of a string split a string you can strip the white space from a string you can append new letters to a string you can find the position of a substring spring string and there's a few more but these are some of the most common things you can do with a string and then one thing to know about these is that they they all return a new modified string they don't actually alter the original string so let me show you what i mean by that so let's say we have we'll do name equals bow again let me zoom in a little bit

1:14:50 and we're going to print name dot lower now i'm going to print name so if i just run this and we first figure out what went wrong here it looks like there's a few extra parentheses [Music] okay let's run this and you can see it's going to make it all lowercase but then when i print the name again it's not still lowercase because this just returns a brand new modified string it doesn't actually change anything in the original string

1:15:38 and then you can use some global functions with strings as well so one function we haven't discussed yet is the l e n function which stands for length it can give the length of a string so i'm going to type an l-e-n and then so there's just some global functions that work with a lot of

…

Share

More video summaries