Cheatography
https://cheatography.com
Data types
name |
value |
string |
"anything1234!@£$%" |
integer |
1234 |
float |
1.2345 |
bool |
True/False |
Variable naming rules
1. Easy to remember |
2. Short |
3. No spaces |
4. Cannot start with a number |
5. Can only contain letters, numbers and underscores |
Collections and generics
Name |
Usage |
Code |
List |
Multiple items in one variable |
["apple", "banana", "strawberry"] |
Dictionary |
Multiple key-value pairs in one variable |
{"hello": "world"} |
|
|
Casting
cast |
what it does |
str() |
converts to a string |
int() |
converts to an integer |
float() |
converts to a float |
Casting is used to convert between values. It needs to occur before doing any mathematical calculations with an input() from a user because user input is always strings.
Variable assignment
name = "abcdef123"
age = 18
height = 3.14
|
Useful python functions
print("text") |
outputs text to screen |
input("text") |
prints text and allows input from a user |
round(3.14) |
rounds a float down to an integer |
|
|
Comparators
symbol |
meaning |
== |
equal to |
> |
larger than |
< |
less than |
>= |
larger than or equal |
<= |
less than or equal |
!= |
not equal |
Boolean operators
and |
both values must be true |
or |
either value may be true |
xor |
either value may be true, but not both |
Arithmetic operators
+ |
add |
- |
subtract |
* |
multiply |
/ |
divide |
** |
power |
% |
modulus |
|
|
Conditionals
value = 3
if value < 4:
print("less than 4")
elif value > 2:
print("larger than 2")
else:
print("some other value")
|
else and elif must follow an if. Else cannot come before elif. Whitespace before the print statements indicates they are only to print if the condition is met
Loops
# infinite loop
while True:
print("cheese!")
# counter loop - 0-9
for i in range(10):
print(i)
# iterating a list
collection = ['apple', 'orange', 'banana']
for value in collection:
print(value)
|
|
Created By
Metadata
Favourited By
Comments
No comments yet. Add yours below!
Add a Comment