note_stack_addVariables and Arithmetic Operatorsstat_minus_1
# Initialising variables and constants of different data types:
score = 0
PI = 3.14
message = "Hello World"
soundOn = True
# 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
# Casting a number into a String
number = 7
print("Your lucky number is " + str(number))
# Changing the case of a string
name = "james BOND"
uppercase = name.upper() # JAMES BOND
lowercase = name.lower() # james bond
titlecase = name.title() # James Bond
# Retrieving the number of characters in a string
password = "Pa55w0rd"
passwordLength = len(password) # 8
# String Slicing: Extracting characters from a string
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print("The fifth letter of the alphabet is: " + alphabet[4])
print("The first 5 letters of the alphabet are: " + alphabet[:5])
print("The next 5 letters of the alphabet are: " + alphabet[5:10])
print("The last 5 letters of the alphabet are: " + alphabet[-5:])
# Iterate through all the characters of a string
string = "Hello World"
for character in string:
print(character)
live_helpRandom Librarystat_minus_1
# 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 = ["Fred","Ali","Ines"]
randomName = random.choice(names)
# To shuffle a list
numbers = [1,2,3,4,5]
random.shuffle(numbers)
# Use ASCII codes to generate a random letter between A and Z
randomLetter = chr(random.randint(65,90))
storageData Structures: Lists, Tuples and Dictionariesstat_minus_1
# Declaring a list and accessing its values
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)
# Adding a new value at the end of a list
numbers = [1,3,5]
numbers.append(7)
# Removing a value from a list
days = ["Mon","Tue","Wed","Thu","Fri"]
numbers.remove("Wed")
# Removing a value from a list at a given position
days = ["Mon","Tue","Wed","Thu","Fri"]
numbers.pop(2) # remove the third item from this list: "Wed"
# Using a Dictionary (Hash table)
dictionary = {"One":"Un", "Two":"Deux", "Three":"Trois"}
print("One in French is " + dictionary["One"])
# Adding an extra key to a dictionary
dictionary["Four"] = "Quatre"
descriptionFile Handlingstat_minus_1
# Reading a text file, line by line
file = open("myTextFile.txt","r")
for line in file:
print(line)
file.close()
# Reading and extracting data from a CSV file, line by line
file = open("myTextFile.txt","r")
for line in file:
data = line.split(",")
print(data[0] + " - " + data[1] + " - " + data[2])
file.close()
# Overwriting the content of a text file
file = open("myTextFile.txt","w")
file.write("Hello World\n")
file.close()
# Appending data at the end of a text file
file = open("myTextFile.txt","a")
file.write("Hello World\n")
file.close()
select_check_boxInput Validationstat_minus_1
# 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)
manufacturingOOPstat_minus_1
import random
# Defining a Dice class
class Dice():
# Constructor for the Dice class
def __init__(self,numberOfSides=6):
self.numberOfSides = numberOfSides
self.value = 1