Python :) Flashcards
If/else if/else structure in python
if condition : #statements elif condition : #statements else: #statements
For loop in python
for identifier in range (int,int): #statements
This is non inclusive (eg in range (0,5) will only run where the identifier is 0,1,2,3 and 4)
Can also be used like
for identifier in range (int,int,increment): #statements
Also non inclusive for the second int
for identifier in StringExp: # statements
Starts counting from 0, and ends on 1 less than the number of letters in the word
Userinput in python
Identifier = input(input prompt)
Modulus in python
%
Eg 5%2 would return 1
Integer division in python
// Eg 5//2 evaluates to 2
Output in python
Print (Exp)
Random number in python
from random import rand range
randrange( IntExp, IntExp)
The second IntExp is exclusive
Eg.
from random import randrange num1 = randrange(3, 7) # generates an integer between 3 and 6
Less than in python
Exp < Exp
Eg.
4 <6
“A” < “B”
“adam” < “adele”
Greater than (pyth)
Exp > Exp
Equal to (pyth)
Exp == Exp
Not equal to (pyth)
Exp != Exp
Less than or equal to (pyth)
Exp <= Exp
Greater than or equal to
Exp >= Exp
Relational operators can be used on (pyth)
Numbers strings and characters
Logical AND (pyth)
BoolExp and BoolExp
Eg,
(3 == 3) and (3 <= 4)
Logical OR (pyth)
BoolExp or BoolExp
Logical NOT
not BoolExp
While loop (pyth)
while BoolExp: # indented statements here
Repeat until loop (pyth)
# statements here while BoolExp: # copy of statements here (indented)
Length of array
len(Identifier)
For loop for the length of an array
for Identifier in ListExp: # indented statements here
Defining Subroutine in python
def Identifier(parameters): # indented statements here
Subroutine return value
return Exp
Calling subroutines
Identifier(parameters)
String length
len(StringExp)
Position of a character
StringExp.find(CharExp)
Substring of a string
StringExp[IntExp:IntExp]
Last IntExp is exclusive
Starts counting from 0
Accessing a single character in a string
StringExp[IntExp]
Starts counting from 0
String concatenation
StringExp + StringExp
Convert string to integer
int(StringExp)
Convert string to real
float(StringExp)
Convert integer to string
str(IntExp)
Convert real to string
str(RealExp)
Converting character to character code
ord(CharExp)
Converting character code to character
chr(IntExp)
Input in python
input(StringExp)
StringExp is the prompt
Output in python
print(Exp, …,Exp)
Eg
print (“a”, “g”) will output
a g
print("Mary had ", end="") print("a little lamb") # will print the text on the same line due to end=“”
Formatted output
f”…{identifier}…{identifier}…”
Eg.
name = "BT" staff = 125000 print(f"{name} has {staff} staff") # outputs "BT has 125000 staff"