
Getting Started with Python Code
Walk through on the first steps to set up your computer to be ready to write Python code. How to install Python on a Mac and Windows Machine. How to set up and prepare your code editor for writing Python Code.
Mac OS install and Setup of Python
open terminal with CMD+Spacebar for the spotlight then type Terminal
Once terminal is open type python --version which will show the default python install typically Version 2
Type python3 --version which will show the version of Python 3 installed
Type python3 to open shell interpreter for Python code
Type 5+5 and note the result
type help() to open the Python help utility
Enter quit anytime to exit the help utility
to exit the shell interpreter type either quit() or exit() this will bring you back to the terminal command prompt
Simple Command Prompt Commands on a MAC
pwd shows current directory path
cd changes to a directory within the current folder
ls lists all files within the current directory
cs ../ moves down one level from the current directory
Windows OS install and Setup of Python
open search and type command prompt
Once terminal is open type python --version which will show the default python install typically Version 2
Type python3 --version which will show the version of Python 3 installed
Type python3 to open shell interpreter for Python code
Type 5+10 and note the result
to exit the shell interpreter type either quit() or exit() this will bring you back to the terminal command prompt
Creating a Python file in your editor
Using print create a string value that you want displayed on the screen. print(“hello”)
Save the file as filename.py
To run the python file you can type python filename.py
also to run in python3 you suffix the word python with 3 python3 filename.py
Python uses indentation and how it works is that the indentation indicates a block of code. In Python indentation is very important.
Commenting in Python Code
Comments can explain code, making it more readable and also great for testing when you want lines of code not to execute. You can also provide information that can be used later and referred to at a later date by yourself or other developers.
Variables -
One of the most important concepts of programming. Variables are at the core of programming. They are containers that can hold information, which can then be easily referenced within the code and returned when needed. Think of a variable as a way to reference something that might change, like a box where you can put items into it and return back the contents of that box by selecting the box label.
Strings can be single or double quote
Variable names are case-sensitive
Rules -
Must start with letter or _ underscore
Can use a-zA-Z0-9_ alpha numeric characters within the variable name
Case sensitive
Use Camel case to indicate words in variable name
Get type of data
type(“variable”)
How to assign multiple values in variables by comma separation of variable names and assigning to comma separated values. Comma separate for multiple variables in one line
You can also assign the same value to all variable names using the = sign
Using a collection you can assign those values to a number of variables within one statement
Python Data Types
More Data type within Python
Boolean can be either True or False - must be capitalized
Variables can also store multiple items in various collections.
Four built in data types to store multiple items are Tuple, Set, List and Dictionary.
Python List
Lists - created with square brackets testList = [50,"100",True,50,"50"]
have defined order and the order does not change when in the list
You can add new items and remove items from the list. The list can be changed
Duplicate values are allowed within the list.
Use index value to identify and retrieve values from within the List. Indexes are zero based, values start at zero.
Use the len() function to determine the number of items within the list.
Get Values -
tempList = [“one”,”two”,”three”,”four”]]
Use the index value example 1 to return the value in a list.
tempList[1] will return “two”
tempList[1] = “NEW” - will assign a new value of NEW to index item 1
tempList[-1] will return “four” last item in the list
tempList[2:3] will return ,”three”,”four”] - if no end value is provided will return all the items until the end.
tempList[:3] will return all expect the item with index 3
tempList.index(“two”) - gets the index value of the item
check if in list print("two" in testList) will return a boolean result
tempList.append(“last”)
tempList.insert(1,“last”)
tempList.remove(“last”)
tempList.pop(1) no index removes the last item in the list
del tempList[0]
del tempList - removes the entire list
tempList.clear() - empties list
tempList.sort() list sorts ascending and alphanumerically - change sort order .sort(reverse = True)
copyList = tempList.copy()
Python Tuple
Tuple - created using rounded brackets testTuple = (50,"100",True,50,"50")
Does allow duplicates since just like lists they are indexed.
ordered is defined and does not change
cannot change or remove items from the tuple after it's created
Zero based and can use functions like len() to get the number of items
Allowed data types are strings, integers, and booleans
Get Values -
Using the index just like lists.
Python Set
Sets - created using curly brackets testSet = {50,"100",True,50,"50",50,100,100,"a"}
no order they are unordered. They have no set order that they appear in.
values cannot be changed after its set although you can add to it and remove from it
Allowed data types are strings, integers, and booleans
Get Values
check if it exists using (“value” in testSet )
testSet.add(“Last”)
testSet.remove(“Last”)
testSet.pop() removes random item
Dictionary - named key value pairs using curly brackets testDic = {"first":50,"second":"100","third":True,"a":50,"a":"LAST"}
order does not change as they are not indexed and accessed using the key value
Can be changed and updated as needed referencing the key value. Add and remove new items into the dictionary
Cannot have more than one item using the key name
Dictionaries can contain nested dictionaries in a child parent format
Get Values
testDic[“first”] or to change use testDic[“first”]=
testDic.keys() - gets all the keys
testDic[“newKey”] = “to add new items”
testDic.pop(“first”) to remove items
testDic.clear to clear all items
Get User Input in terminal assign to a Variable
Within your code you can request the user provide an input. The input will be a string data type by default. You can assign the response of the user input to a variable that can be used within your code.
String methods can be helpful in checking to see if they can be converted to an integer.
You can use a condition to check and run a block of code depending on the boolean value of a variable.
The isnumeric() method returns True if all the characters in the string value are numeric (0-9), otherwise it will return a value of False.
Exercise Create a simple Calculator
Using the input, ask the user for two numbers, take the numbers and convert them to integers so that you can add them together. Create an output message to the user with the total and the equation for the two numbers added together.
Conditions and Logic If .. Else Statements
Conditions allow us to apply logic into our Python code.
Indentation is important as it help Python understand the block of code that needs to run if the condition is true.
Exploring shorthand methods that can be written in one statement
Bouncer Exercise Project - Code bouncer allowed in or not?
Create an application that will ask the user their age. Depending on the age, first check if the response is a number. If its not a number reject them and provide a message back. If its a number then check to see if the value is allowed in and can drink which is 21+, if they are 18-20 they can come in but not drink and lastly if they are 17 or less they should not be allowed in. Create the application to follow these rules!
Loops while loop
While loop allows us to run blocks of code multiple times. There are options using the keyword continue to skip an iteration as well as using the keyboard break to leave and stop the loop. In addition to the loop there is also an option to provide an alternative output once the loop condition is no longer true and run an else block of code.
For Loop for lists and dictionary items
Using a for loop can output the contents of a list or a dictionary.
Exercise Number Guessing Game
Using a while loop create a game that allows the user to make a guess at the hidden value of a number.
Start off create secret number in a variable
Set a variable that will limit the number of guesses
Create a variable to hold the number of guesses made by the user.
Setup a while loop that compares guess value to the secret number
Print provide the user how many guesses they have left
Capture the input from the users guess as a integer
If the users guess is correct set the final message as a WIN
Provide feedback to the user if their guess incorrect guess was too high or too low
Increment the counter and check if the count is at the max guesses, if it is break from the while loop
Output the WIN or LOSE message to the player
Functions core part of programming
You can reuse blocks of code invoking them anytime within the code to run the function block of code. Function can have arguments that are values passed and assigned to the variable names used within the function arguments. These values can then be used within the function. You can also return values with functions, those values can then be assigned to variables and used within your Python Code.
Lambda
Shorter anonymous functions written as one statement
Function scope
Values can be accessed locally with the block of code that is assigning the values. Each block of code has its own scope, the main block of code is called the global scope. You can use variables from the parent block scope but you cannot update the variable values within the child scope. There are keywords to access and update the global scope, you can use global to reference the variable you want to use. That opens the variable up to be updated within the child scope. You can also use the keyword nonlocal to access the parent scope variables to update them within a child local scope.
Python built in Methods
Built in functions within Python
Python Modules
You can use functions and data from other python files in your main file. Allows you to import functionality referencing the module
Import Modules Python
datetime is a stand module that you can use to get date values
String Functions Python
We can update and manipulate the string values with useful built in string methods that can be applied to strings
Projects with Python
Create a countdown timer
create a function that will decrease a val
Using Modulus and Floor Division calculate the minutes and seconds
Create a string output value using format to structure it as minutes and seconds
Using the time module import the sleep method slowing the output with a 1 second delay
Subtract from the total seconds
Once the while loop completes print the time is up and invoke the start function again
Create a starting function that gets the users inputs for the countdown timer in total seconds. Check if the input is numeric if it is send the total second value to the countdown function
Dice game in Python
Play against the computer, role the dice get a random value and see who scores more. The highest role wins the game. Perfect game to practice and learn more about using random in game logic, and applying conditions to check for a winner
Import the random module
setup default variables for score and set the values of the roles from min to max.
Create a function to house the game coding
Setup a while loop that will run the block of game code
Game code generates random values for both the player and computer.
Apply conditions to check who wins
output the feedback and results to the player. Keeping score of the rounds.
Allow player to exit and end game
Rock Paper Scissors Python coding Game
Rock paper scissors, played between the player and the computer. Setup the game make a selection and see who wins. Rock beats Scissors and crushes them, Paper covers the rock and wins, Scissors can cut up the paper to win.
import the random module
setup the default values and array
create the gameplay function
create a loop within the gameplay function
Get the user selection and generate a random selection for the computer
Apply logic to see who wins
Let the player exit the game or go for another round.
Python Online Course For Beginners online course to introduce beginners to writing Python code and creating applications.
Enroll now to get instant access to:
4+ hours of premium lessons
31 page downloadable workbook source code, tips, resources and challenges
Premium instructor support to help you learn
Lifetime access to course updates
Python is an excellent language to start programming with, its powerful and reality easy to get started with. You can see results and run the code right away and most computers require very little setup to start coding.
Includes several Python projects and loaded with code examples , you will travel through every essential element of programming and understand how the entire programming of python really works.
Python is perfect for both small and large scale projects. Designed to help programmers write clear and logical code made to be human readable.
Common uses for Python include, task automation, data analysis and visualization and development web applications. Due to the ease of getting started with Python it also gets commonly adopted by many non-programmers to help with tasks.
One of the most popular programming languages. Small learning curve, you can get started with Python quickly. Powerful and straightforward. So many people are learning Python, doing cool things and you can get started with Python quickly.
Python for Beginners - perfect language to learn how to code.
How to get setup and ready to code using Python, setup your development environment.
Start directly on your computer you already have everything you need to write Python
Python is perfect for both small and large scale projects
Code that is written is easy to read because of the use of indentation and object oriented approach.
Ease of getting started with Python - great for non programmers who want to learn
Small learning curve, you can get started with Python quickly
One of the most popular programming languages.
Most PCs and Mac will come with Python installed already
So many people are learning Python, doing cool things and you can get started with Python quickly.
Help everyone learn coding -
How to setup your coding environment and start writing Python on your computer today.
Everything you need to know about Getting Started with Python Code
Walk through on the first steps to set up your computer to be ready to write Python code. How to install Python on a Mac and Windows Machine. How to set up and prepare your code editor for writing Python Code.
Introduction to setting up your machine to write Python Code
Mac OS and Windows install and Setup of Python
Editor Setup for Coding Python.
Fundamentals of Coding with Python
Python uses indentation and how it works is that the indentation indicates a block of code. In Python indentation is very important.
Commenting in Python Code Multi line comments
Python Code Variables How to create variables and use them in code
Python Data Types Strings Integers Booleans Lists Sets Dictionaries
How to get the User input in the terminal and assign it to a variable
Project - Python Calculator
Project - Favorite Number Messages
Python How to apply logic with conditions
Project - Code bouncer allowed in or not?
Coding Loops and iterations while and for
Python Project Number Guessing Game
How Python Functions work
What is Python Lambda and how it works
Python Function Scope.
Python built in Methods
How to use Python Modules Create your own modules to use in your code
Coding Projects to you can create with Python
Get coding and creating simple projects with Python to practice what you've learned and develop your skills
Python Coding Project Countdown timer code
Python Coding Project Dice game in Python highest roll wins
Python Coding Project Rock Paper Scissors Python coding Game
Create a countdown timer
create a function that will decrease a val
Using Modulus and Floor Division calculate the minutes and seconds
Create a string output value using format to structure it as minutes and seconds
Using the time module import the sleep method slowing the output with a 1 second delay
Subtract from the total seconds
Once the while loop completes print the time is up and invoke the start function again
Create a starting function that gets the users inputs for the countdown timer in total seconds. Check if the input is numeric if it is send the total second value to the countdown function
Dice game in Python
Play against the computer, role the dice get a random value and see who scores more. The highest role wins the game. Perfect game to practice and learn more about using random in game logic, and applying conditions to check for a winner
Import the random module
setup default variables for score and set the values of the roles from min to max.
Create a function to house the game coding
Setup a while loop that will run the block of game code
Game code generates random values for both the player and computer.
Apply conditions to check who wins
output the feedback and results to the player. Keeping score of the rounds.
Allow player to exit and end game
Rock Paper Scissors Python coding Game
Rock paper scissors, played between the player and the computer. Setup the game make a selection and see who wins. Rock beats Scissors and crushes them, Paper covers the rock and wins, Scissors can cut up the paper to win.
import the random module
setup the default values and array
create the gameplay function
create a loop within the gameplay function
Get the user selection and generate a random selection for the computer
Apply logic to see who wins
Let the player exit the game or go for another round.