More Examples and Info - https://www.tutorialspoint.com/python/python_basic_operators.htm
A variable is a reserved space in a computers memory that can hold a specific value which is referenced by a specific name in the program. Variables can be declared with a unique name as a place holder to store a specific value. Unlike other languages you do not need to declare the variable type.
String
Integer
Float
Boolean
Lists (similar to arrays in other languages)
See examples below:
name = "john smith" #String
address = " 34 red st" #String
age = 10 #integer / number
height - 1.82 #float / number with a decimal
alive = True #boolean (true or false)
each variable must a unique name - different to other variable names
case sensitive
no spaces allowed - use underscore _ to join words
some names are not allowed to be used as they control other functions -
make variable name clear of what they are
Must start with a letter - not allowed to start with a number
#This is a comment and will not be executed in the code when run - only one line
'''
This is a
multi line comment
use 3 single quotation marks
'''
The text in the brackets will be printed to the console. The text known as a string needs be surrounded with quotation marks " "
print("Hello World")
print("Hello my name is " + name)
If you try and concatenate variable which are integers, you will need to convert each variable to a string using the str() command. See below
print("Hi, I am " + str(age) + " years old and I am " + str(height) + " metres tall")
We can concatenate strings with variables and strings using the '+' symbol.
How do you include symbols like quotations " ' in a print output. You need to put an escape \ key in front of the character.
print("My name is \" Bob \" ")
Addition (+)
answer = 10 + 12 >>> 22
Subtraction (-)
answer = 10 - 2 >>> 8
Multiplication (*)
answer = 10 * 2 >>> 20
Division ( / )
answer = 50 / 2 >>> 25
Modulus (%) - returns the remainder of a division of two numbers
answer = 3/2 >>> 1
(==) EQUAL - If the value of the two operands are equal (the same) the condition returns true
a = 1
b = 1
a == b >>> true
(!=) NOT EQUAL - If the two values are not equal the condition returns true
a = 1
b = 2
a != b >>> true
(>) GREATER THEN - If the value on the left is greater then the value on the right the condition will return true
a = 10
b = 20
a > b >>> false
b > a >>> true
(<) LESS THEN - if the value on the left is smaller then the value on the right the condition will return true
a = 10
b = 20
a <= b >>> true
b <= a >>> false
(>=) GREATER THEN OR EQUAL - If the value on the left is greater then or equal to the value on the right the condition will return true
a = 10
b = 20
a >= b >>> false
(<=) LESS THEN OR EQUAL- if the value on the left is smaller or equal to the value on the right the condition will return true
a = 10
b = 20
c = 10
a <= b >>> false
a <= c >>> true
To allow the user to input values into the program you need to use a input command. See examples below.
Gathering String Input:
player_name = input("please enter a name)
Gather Number Input: This is important if you want to do a arithmetic calculations on the input
player_age = int(input("please enter your age"))
name = input("please enter a name)
age = int(input("please enter your age"))
print("Hi, I am " + name + " and I am + str(age) + " years old")
Casting is where we can convert a type of variable to another type of variable. The most common is from a string to an integer. Remember when writing an integer to a string through the print function, you need to cast variable type to a string with the function called str() - see above example
You can cast a string to an integer using int()
In a program we can make decisions based on asking questions or testing certain conditions, then we can choose the correct output based on if the condition is true or false.
Single Statement - If the question is true we perform an action, if not true the program does nothing.
IF condition is true:
perform this action
If Else Statement. If the first condition is NOT true the program runs the second part of the code after else at each instance
IF condition is true:
perform this action 1
ELSE:
perform this action 2
Else If Statement - we can test against multiple conditions, if neither of the first two conditions are true, the program will perform the action after else. Its important to remember that logical operation is that if condition 1 is true, then the code beneath will NOT be executed.
IF condition_1 is true:
perform this action 1
ELIF condition_2 is true:
perform this action 2
ELSE:
perform this action 3
if Example
answer = 12
if answer == 12:
print("Correct")
If Else Example - don't for the colan after each if statement
answer = 5
if answer == 5:
print("Correct")
else:
print("incorrect")
If / Else If /Else Example
answer = int(input("Enter a number"))
if answer > 10:
print("too large")
elif answer <10:
print("too small")
else:
print("you entered the number 10")
To make programs more efficient we can loop code (iteration) to repeat code sections over and over again. This saves lines of code and makes life a lot easier and the program more efficient.
These loops continue repeating until the condition in the while statement is false. It then exits from the loop and continues the code below.
While condition is true
perform this action/s
count = 10
while count > 0:
print(count)
count -=1
Note: with while loops, ensure the indentation is correct
answer = 11
guess = int(input("Make a guess"))
while guess != answer:
print ("Try again")
guess = int(input("Make a guess"))
print("well done, you are correct")
Another while loop example
while qNum <= 5:
num1 = randint(1,10)
num2 = randint(1,10)
qAns = num1 + num2
print("Question: ", qNum)
ans = input("What is " + str(num1) + " + " + str(num2) + " ?: ")
if int(ans) == qAns:
print("correct")
score +=1
qNum +=1
elif int(ans) != qAns:
print("incorrect")
qNum +=1
FOR Loops repeat code for a set number of iterations. They use a counter variable to trace the number of times the block of code has been executed. These are useful for running a loop of code to repeat like counting down to zero from a specific number . Its is also important to note the count will start at zero by default and count up
Examples
#Prints out 0,1,2,3,4
print("Example of a range"
for x in range(0,5):
print(x)
#the first number in the brackets is the starting point of the loop
# the second number in the brackets is the number the counter will count to
#Prints out -2,-1,0,1,2,3
print("Example of negative -> positive")
for x in range(-2,4):
print(x)
#this example shows how the break function stops a loop when a condition is met
print("Example of a break function")
fruits = ["apple", "tomato", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
import random # must insert to work at top of code
random.randint(1, 100) # random number between 1 and 100
#print to screen
print("a random number" + str(random.randint(1,300))
You can access any part of a date or time format using the following steps in python.
import datetime
now = datetime.datetime.now()
print (now.year, now.month, now.day, now.hour, now.minute, now.second)
>>> 2018 12 13 2 30 21
- http://www.pythonforbeginners.com/basics/string-manipulation-in-python
Accessing individual Characters from a variable
word = "Hello World"
letter=word[0] >>> print letter H
Other options:
word = "Hello World"
print word[0] #get one char of the word
print word[0:1] #get one char of the word (same as above)
print word[0:3] #get the first three char
print word[:3] #get the first three char
print word[-3:] #get the last three char
print word[3:] #get all but the three first char
print word[:-3] #get all but the three last characters
len(variable or string)
x = input("Name?") >>> Bob
print(len(x) >>> 3
import time
time.sleep(2) >>> delay by two seconds
This call will delay the next step of the program by the number inside the sleep function
from termcolor import colored
print (colored("Hello World!","red"))
A larger container of variables that are indexed starting at 0.
These are useful for storing multiple values at a time without creating multiple variables.
Search and sort lists in Python: https://www.dummies.com/programming/python/how-to-search-and-sort-lists-in-python/
Search through lists in Python: https://thispointer.com/python-how-to-check-if-an-item-exists-in-list-search-by-value-or-condition/
Creation of a list
L = ['yellow', 'red', 'blue', 'green', 'black']
Print Lists
print(L)
>>> ['yellow', 'red', 'blue', 'green', 'black']
Accessing / Indexing Lists
L[0] = returns 'yellow'
Slicing
L[1:4] = returns ['red', 'blue', 'green']
L[2:] = returns ['blue', 'green', 'black']
L[:2] = returns ['yellow', 'red']
L[-1] = returns 'black'
L[1:-1] = returns ['red', 'blue', 'green']
Looping through a list with an index
for i in list_name:
print(i)
Adding an element to the list:
list_name.append(value)
Deleting an item from the list
list_name.pop()
#example - removing the number 7 from a list
for i in list_name:
if i == 7
list_name.pop()
Searching lists for a particular value:
list1 = ['cat', 'bat', 'mat', 'rat', 'pet']
print(list1)
# search for and then store the index of 'bat' in list1 in a variable called petCheck
petCheck = (list1.index('bat'))
print(petCheck)
print(list1[petCheck])
returns the values: 1, bat
Searching lists for a value input by a user using index:
# ask a user for a search string in myList,
# if the string is present it will return the index and value,
# if not it will throw an error and halt the program...
myList = ['Tom Thumb', 'Jenny Smith', 'Andrew Foster', 'Mary Johnson']
print(myList)
nameSearch = input("Search the list for a name: ")
nameCheck = (myList.index(nameSearch))
print(nameCheck)
print(myList[nameCheck])
Searching lists for a value input by a user using a manual approach:
# checks a list (this case namesList) for a user input string
# loops through until the word QUIT is input
# you could possibly use the index method above to return the value of the first instance
# of the value in the list...
checkNames = ""
while str.upper(checkNames) != "QUIT":
checkNames = input("Please type a name: ")
if (namesList.count(checkNames) >= 1):
print("The name exists in the list!")
elif (str.upper(checkNames) != "QUIT"):
print("The list doesn't contain the name.")