Example Code Flashcards
(41 cards)
How do you do whole number division?
answer = num1 // num2
How do you do a line break?
\n
How to find the length of a variable
len(word)
Removes extra characters (in this case spaces) from the start and end of a string
text = “ This is some text. ”
print(text.strip(“ ”))
How to display certain letters in a word?
print (“Hello world”[7:10])
Changes the string into upper case.
word.upper()
Changes the string into lower case.
word.lower()
Changes a phrase so that every word has a capital letter at the beginning with the rest of the letters in the word in lower case
word.title()
To the power of
**
When using some math code what do we need to have at the start of the program?
import math
The square root of a number
math.sqrt(num)
but you must have the line import math
Gives you pi (π) to 15 decimal places
math.pi
you must have the line import math
Finds the remainder
x % y
Count up from 1 to 9
for i in range(1,10):
print(i)
counts up from 1 to 9 in 2s
for i in range(1,10,2):
print(i)
Counts down from 10 to 1 in 3s
for i in range(10,1,-3):
print(i)
Prints every letter of a variable on each line
for i in word:
print(i)
Not equal to
!=
What should you write at the top when starting to write code that uses random
import random
Selects a random floating-point number between 0 and 1 and stores it in a variable called “num”
num = random.random()
Selects a random whole number between 0 and 9 (inclusive)
num = random.randint(0,9)
Picks a random value from the options “red”, “black” or “green” and stores it as the variable “colour”
colour = random.choice([“red”,“black”,“green”])
Picks a random number between the numbers 0 and 100 (inclusive) in steps of five
num = random.randrange(0,100,5)
Creates a variable name called “fruit_tuple” which stores four pieces of fruit within it
fruit_tuple = (“apple”,“banana”,“strawberry”,“orange”)