This page summarises the syntax of the Python language. When using Python always remember two key rules:
- Rule #1: Python is white-space dependent; code blocks are indented using spaces.
- Rule #2: Python language is case sensitive. It matters for variables, functions and any keyword in general.
Annotations
# Single Line Comment """ Multi-line comment by 101Computing.net """
Variables & Assignment Operator
myInteger = 1 myFloat = 3.14 myString = "Hello World" myList = ["John","James","Laura"]
Input
# Text Input playerName = input("What's your name?") # Number/Integer Input playerAge = int(input("How old are you?")) # Number/Decimal Input cost = float(input("How much does it cost?"))
Output
print("Hello World") print("Hello " + playerName) print("You are " + str(playerAge) + " years old.")
Casting
str(100) # To convert a value to a string int("100") # To convert from a string to an integer float("3.14") # To convert from a string to a float score = 5 print("Your score = " + str(score))
String Manipulation
# String Concatenation playerName = "John" myString = "Hello " + playerName + "!" score = 5 print("Your score = " + str(score)) # Changing the case of a string myString = "Hello World" print(myString.upper()) # to print HELLO WORLD print(myString.lower()) # to print hello world # Extracting Characters of a String myString = "Hello World" print(myString[0]) # "H" print(myString[0:5]) # "Hello" print(myString[-5:]) # "World" # Finding out the length of a string print(len(myString)) # 11 # Splitting a string into a list of values names = "John;James;Laura" data = names.split(";") print(data[0]) # This would print: John
Random Library
#Import the random library import random #Generate a random number between 1 and 100 randomNumber = random.randint(1,100) #Pick a value in a list at random names = ["John","James","Luke"] randomName = random.choice(names)
Arithmetic Operators
x = a + b # Add x = a – b # Take away x = a / b # Divide x = a * b # Multiply x = a ** 2 # to the power of x = a // b # Quotient DIV x = a % b # Remainder MOD x += 1 # Increment x by 1 x -= 1 # Decrement x by 1 x *= 2 # Multiply x by 2 x /= 2 # Divide x by 2
Rounding a Number
pi = 3.14159 pi2 = round(pi,2) print("Pi rounded to two decimal places: " + str(pi2)) # 3.14
IF Statements / Selection
Warning: Use the 4 spaces rule!!! (Indentation)
if numberOfLives == 0: print("Game Over!") if number == 7: print("Seven") else: print("Not seven!") if number < 0: print("Negative Number") elif number == 0: print("Zero") else: print("Positive Number") if number == 7: print("Seven") elif number == 8: print("Eight") elif number == 9: print("Nine") else: print("Not seven, eight or nine")
Comparison Operators
The main comparison operators are:
Comparison Operator | Meaning | Example |
== | is equal to | 4==4 |
!= | is different from | 4!=7 |
< | is lower than | 3<5 |
> | is greater than | 9>2 |
<= | is lower or equal to | 3<=5 5<=5 |
>= | is greater or equal to | 9>=2 5>=5 |
Comparison operators are used to check if a condition is true or false.
Boolean operators such as AND, OR and NOT can also be used to check multiple conditions at the same time.
e.g.
if timer>0 and numberOfLives>0: print("Carry on playing!") else: print("Game Over")
Loops / Iteration
Warning: Use the 4 spaces rule!!! (Indentation)
for i in range(1,11): # Using a range print i for i in range(0,101,5): # Using a step - e.g. count in 5 print i daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] #Iterate through all the values of a list for i in range(0,len(daysOfTheWeek)): print(daysOfTheWeek[i]) #Iterate through all the values of a list - Alternative method for day in daysOfTheWeek : print(day) string = "Hello World" for character in string: # Using a string print(character) i=0 while i<=100: print i i = i + 1 # To exit from a loop at any time: break
Lists
days = ["Mon","Tue","Wed","Thu","Fri","Sat"] days.append("Sun") print(days[0]) # "Mon" print(days[1]) # "Tue" print(days[2]) # "Wed" … print(days[6]) # "Sun" #Finding out the number of items in a list (length of a list) print(len(days)) # 7 #Iterate through all the values of a list for i in range(0,len(days)): print(days[i]) #Iterate through all the values of a list - Alternative method for value in days: print(value)
Procedures
Warning: Use the 4 spaces rule!!! (Indentation)
def displayBanner(message) : print("---------------") print(message) print("---------------") displayBanner("Hello World!")
Functions
Warning: Use the 4 spaces rule!!! (Indentation)
def add(x, y) : sum = x + y return sum total = add(1,3) print(total) # this would display 4
File Handling – (Over)Writing a text file
file = open("myTextFile.txt","w") file.write("Hello World\n"); file.close()
Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.
File Handling – Appending data to a text file
file = open("myTextFile.txt","a") file.write("Hello World\n"); file.close()
File Handling – Reading a text file line by line
file = open("myTextFile.txt","r") for line in file: print(line) file.close()
File Handling – Reading a CSV file line by line
CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a divider symbol such as a comma “,”, a semi-colon “;” or a pipe “|”.
In this case when reading a line of the text file you can use the split() method to then access each field one by one.
file = open("myTextFile.txt","r") for line in file: data = line.split(";") print(data[0] + " - " + data[1] + " - " + data[2]) file.close()
File Handling – Reading a text file using a list
file = open("myTextFile.txt","r") lines = file.readlines() file.close() for line in lines: print(line)
Input Validation: Presence Check
name = input("Enter your name:") if name=="": print("Empty name!") else: print("Thank you!")
Input Validation: Type Check – Integer?
number = input("Type a number:") if number.isdigit(): print("This is a number") else: print("This is not a whole number")
Input Validation: Range Check
number = int(input("Type a number between 1 and 5:")) if number>=1 and number<=5: print("Valid number") else: print("Invalid number")
Input Validation: Lookup Check
drive = input("Can you drive?").lower() if drive in ["yes","no"]: print("Valid answer") else: print("Invalid answer")
Input Validation: Character Check
email = input("Type your e-mail address:") if "@" in email: print("Valid e-mail address") else: print("Invalid e-mail address")
Input Validation: Length Check
password = input("Type a password:") if len(password)>=8: print("Valid password") else: print("Invalid password")
Try Again! Using a While Loop:
name = input("Enter your name:") while name=="": print("You must enter your name! Please try again!") name = input("Enter your name:") print("Welcome " + name)
You can investigate more advance approaches to implement validation subroutines on this blog post.