Python Basics
Python is powerful… and fast; plays well with others; runs everywhere; is friendly & easy to learn; is Open.
(https://www.python.org/about/)
Installing
Details on how to install Python can be found at (https://www.python.org/downloads/).
Printing
Printing lets you output something like a word or some numbers and even more. The print()
function will display the given value on screen.
You can also put mathematical expressions inside the print function and Python will solve the expression and print the answer.
This can be combined with other operators and variables (both covered further down) and it can be fun to play around with these to see what happens.
Comments
Comments allow you to type something out without Python thinking you’re writing code. Usually you’ll use comments to explain what certain methods or lines of code do. Python has 2 ways to do comments but only 1 will be shown here as the other is only really used in a situation that will be covered later.
Data Types
Python has many different ways to represent different forms of data. If you wanted to create a sentence, you would use a str
, or string, data type. Numbers can be separated into int
, or integer, for whole numbers, and float
for numbers with decimals. Another data type is called a bool
or a boolean. This type is a simple True
or False
. There are many more types than this, but these are a few of the basics ones.
String str
:
- “Hello, World!"
- "Blue"
- "1"
- "1.0"
- "True”
Integer int
:
- 1
- 10
- -1
- 0
Float float
:
- 1.0
- 0.0
- -1.0
- 3.14159
- 2.718281828
Boolean bool
:
- True
- False
Variables
Variables allow you to store values for later use. This can be helpful when you want to use the same value multiple times, and can make the code more readable.
Creating and updating variables uses the same syntax so make sure you aren’t accidentally creating a new variable instead of updating a current one, or vice versa.
This is how you create and update variables:
You can then use these later in the code. For example, if you wanted print the name
variable:
This program will display the word Alice
.
Operators
Operators allow you to create expressions that give you a result, like a mathematical equation for example. There are a few different types of operators in Python.
Arithmetic Operators
Arithmetic operators allow you to write equations that will return a value.
Examples:
+
Addition-
Subtraction*
Multiplication/
Division%
Modulus**
Exponentiation//
Floor Division
Assignment Operators
Assignment operators allow you to assign values to variables.
Examples:
=
+=
-=
*=
/=
%=
**=
//=
Comparison Operators
Comparison operators allow you to compare values and variables with each other. These will return a bool
type, a True
or False
result.
Examples:
==
Equals!=
Not Equals>
Greater Than<
Less Than>=
Greater Than or Equal To<=
Less Than or Equal To
Logical Operators
Logical operators allows you to compare bool
values with each other .
Example:
and
or
not