Finished!!

The 5 weeks of Grok programming is over.Throughout each week I learnt the basics of python coding. I found that Grok had its good bits and bad bits. The first couple of weeks were really good,I got used to programming and the basic functions. The information was clear and easy enough to follow but still challenged you. Then the last couple week I felt like were a bit of a jump or they didn't explain the tasks in enough detail, so that I could understand and code. Since I was a beginner at python I would say that Grok did help me get started on python. What I found from going through each week and blogging from it was that when I didn't get the code and looked back on the solutions, it was easy to look where I went wrong. In conclusion Grok wasn't a bad program but just needs a bit of tweaking.

Week 5

All the function learnt this week 

Storing multiple values
When storing more than one value it an get repetitive
Example - 
author1 = "J.K. Rowling"
author2 = "P. Pullman"
author3 = "S. Collins"
print(author1)
print(author2)

print(author3)
Instead we can make lists using a for loop
Example - 
authors = ["J.K. Rowling", "P. Pullman", "S. Collins"]
for author in authors:

  print(author)
or 
odds = [1, 3, 5, 7, 9]
print(odds)
Reading in Lists
Example - 
data = input("Enter your subjects: ")
subjects = data.split()
print(subjects)
Enter your subjects: hv kb jb
['hv', 'kb', 'jb']
or put it in a for loop to print it in a vertical list

Lists

Acessing list items:
Example - 
colours = ['red', 'blue', 'green', 'yellow']
print(colours[1])
print(colours[-1])

Changing list items; 
Example - 
colours = ['red', 'blue', 'green', 'yellow']
colours[0] = 'crimson'
colours[-2] = 'lime'
print(colours)
Sorting 
Use these functions for sorting data out, use  sort to sort alphabetically and in number order or append and add a variable into the brackets to sort from that variable. Also reverse will do the opposite. 
Append: 
Example - 
pets = ['dog', 'mouse', 'fish']
pets.append('cat')
print(pets)
['dog', 'mouse', 'fish', 'cat']
Sort:
Example - 
pets = ['dog', 'mouse', 'fish', 'cat']
pets.sort()
print(pets)
['cat', 'dog', 'fish', 'mouse']
Reverse; 
Example - 
pets = ['cat', 'dog', 'fish', 'mouse']
pets.reverse()
print(pets)
['mouse', 'fish', 'dog', 'cat']
List of words or characters 
Characters:
Example - 
print(list('hello'))
['h', 'e', 'l', 'l', 'o']
Words: 
Example - 
line = 'hello world'
words = line.split()
print(words)
['hello', 'world']

Creating sublists and finding indexes
Sublist:
Example - 
colours = ['red', 'blue', 'green', 'yellow']
fewer_colours = colours[:2]
print(fewer_colours)
['red', 'blue']
Indexes: 
Example - 
words = ['the', 'fox', 'jumped', 'over', 'the', 'dog']
print(words.index('fox'))
print(words.index('dog'))
1
5
Joining & Splitting 
Joining with spaces; 
Example - 
values = ['a', 'b', 'c', 'd', 'e']
print(' '.join(values))
a b c d e
Joining with seprator:
Example - 
sep = ':'
values = ['a', 'b', 'c', 'd', 'e']
print(sep.join(values))
a:b:c:d:e

Week 4

All the function learnt this week 

While :
While loops if we need to put a condition on the how many times we want to repeat it.
(this loop says while i is less than 3, print i.)
Example -  
i = 0while i < 3:  print(i)  i = i + 1012
Looping Breakdown: 
Starting: Are there any variables we need to setup before the loop starts (loop initialisation)? In our example, this was the line:
i = 0
Stopping: How do we know when to stop? called the stopping or termination condition. In our example, this was:
while i < 3:
Doing: What do we want to repeat? This will become the body of the loop control structure. In our example, this was:
print(i)
Changing: Do the instructions change in the state in any way in each repetition? For example, we might need to keep track of how many times we have repeated the body (the number of iterations). In our example, this was:
i = i + 1
Bigger than 1 -Looping :
Example - 
i = 1
while i < 7:
  print(i)
  i = i + 2
1
3
5

Counting
Example - 
j = 6
while j > 3:
  print(j)
  j = j - 1
6
5
4
Checking a string
Example -
msg = 'e'
while msg != 'eeeee':
  print(msg)

  msg = msg + 'e'
Reading multiple lines from the user
Example -
command = input('Enter a command: ')
while command != 'quit':
  print('Your command was:', command)

  command = input('Enter a command: ')
Enter a command: help
Your command was: help
Enter a command: Grok
Your command was: Grok
Enter a command: quit
Looking for blank lines 
Example -
line = input('Enter line: ')
while line:
    print('Still running')
    line = input('Enter line: ')

print('Stopped')
Enter line: f
Still running
Enter line: 

Stopped
Counters Counters count how many times it with loop in while
Example -
guess = input('Guess my favourite colour: ')
counter = 1
while guess.lower() != 'yellow':
  counter = counter + 1 # adds one to the counter
  guess = input('Try again: ')
print('You got it in', counter, 'tries.')
Guess my favourite colour: red
Try again: blue
Try again: orange
Try again: yellow
You got it in 4 tries.
Lopping over characters This combines len functions with the while loop.
Example -
word = 'Grok'
i = 0
while i < len(word):
  print(i, word[i])
  i = i + 1
0 G
1 r
2 o
3 k
Do you use for or while when looping 
When you know how many iterations you need it is easier to use for. It is quicker to write but if not the same program can be written in a while loop, which is longer to write about 4 lines compared to 2.When you don't know how many iterations using while is the better option.

Comments 
If you ever need to write some notes or comments in your coding then use the # sign and python will ignore it.
Example -
# read in a number from the user

Week 3

All the function learnt this week - Week 3

Individual Characters : 
This function is used to get individual characters but is it is better to use the for loop as it will error out if there isn't the same amount of letters.
This form of the example will print it vertical as  h
Example -                                                              e
msg = "hello world"
print(msg[0])
print(msg[1])

Looping 

This will loop through the coding until it either finds the answer or input the computer was looking for or is stopped. This function uses for in the variable which is what loops it.
Example -
name = input('Enter your name? ')
for c in name:
  print(c.upper())

Upper &Lower Case  
To print the program in either lower or upper case simply use the variable that you want to be in lower or upper case and add .lower or .upper with brackets.
Example -  
 print(c.upper())  or print(.lower())

 On the same line 
When you use for to loop it always print vertically and not on the same line. To print it on the same line we use end=.  or output it which is the better way of doing it 
Example -  
The end= way 
for i in "Hello":
  print(i, end=" ")
The output way 
output = ''
for i in "Hello":
  output += i + ' '
output += 'same line'
print(output)

 Range 
Range is used to break or stop the program from looping again. It is used with the for statement. 
Example -  
for n in range(5, 9):
  print(n)
Which will print the numbers 5,6,7,8
Step by Step 
Adding a third argument to range - such as 2 for even numbers.When entering the numbers it range take it as "Print the numbers from 2 up to (but not including) 12, in steps of 2"
Example -
for i in range(2, 12, 3):
  print(i)
2
5
8
11
 Backwards
To loop it in reverse you simply go to make the third argument a negative
Example - 
for i in range(5, 0, -1):
  print(i)

4

2
1
Same Line Continued 
When using output in this example it leaves a white space at the end
Example -
output = ""
for i in range(10):
  output = output + str(i) + ' '
print(output)
To fix this we can use either rstrip or string slicing.
Example -
print(output[:-1])
or 
print(output.rstrip())

Maths with looping 
To do maths in looping we can use for and a variable of  0.
Example - 
result = 0
for i in range(100):
  result = result + i
print(result)

Changing integer into float 

If we did not convert them when dividing the answer will always be in a float even when not necessary. Such as 10/ 2 would  = 5.0
Example -
i = 10
print(i)
f = float(i)
print(f)
10
10.0

Changing float into integer 
To do this we simply need to use the int function.
Example -
i = int(5.0)
print(i)
5
**Note that if the decimal is like 4.5 it wont round it up or down it will simply chop it off
Example -
print(int(4.8))
4

Calculating remainders
To calculate the remainder we use the percentage sign like this remainder = 10 % 3
print(remainder)
Example -  In a program
answer = int(290327/36)
remainder = 290327 % 36
print(answer)
print(remainder)
8064
23

Import 
Import is used to import math functions for python 
Example -
import math
print(math.sqrt(4))
Functions & Other Math
Round a number:
print(round(4.6))
Square a number: 
import math
print(math.sqrt(4))
Pi:
import math
print(math.pi)

Advance String Looping 
Advance string will show a index of the letters in the loop 
Example -
y = 'hello'
for i in range(len(y)):
  line = "Letter " + str(i) + " is " + y[i]
  print(line)

Letter 0 is h
Letter 1 is e
Letter 2 is l
Letter 3 is l
Letter 4 is o

Checking the Start and End Of a String
This checks whether the string you have entered is at the start or the end of the input. s.startswith() or s.endswith()
Example -
s = "hello world"
print(s.startswith('hello'))
print(s.endswith('rld'))

True
True

String Methods 
Removing white space: 
Example -
s = "   abc  "
print(s.strip())
print(s.lstrip())
print(s.rstrip())

abc
abc  
   abc
Finding the Index of a Character:
Example -
s = "hello world"
print(s.find('w'))
print(s.find('x'))
6
-1
** If the character is not in the string it will come up as -1

Chopping up a string 
This means you can access parts of the string rather then the whole thing 
Example -
x = 'hello world'
print(x[0:5])
print(x[6:11])
hello
world
Short Cut :
x = 'hello world'
print(x[:5])
print(x[6:])
hello
world
If you want to replace a part of the string by slicing it you will have to create a new string.
Example -
x = 'hello world'
x = 'X' + x[1:]
print(x)
'Xello world'

Week 2

All the function learnt this week - Week 2

if 
The if function is used when you are asking a question or statement and you want a specific reply to each answer. With this you have to be careful with the indentation making sure they line up with your programming, otherwise your coding wont work.
Example -
food = input("What food do you like? ")   ----or--         raining = input("Is it raining (yes/no)? ")
if food == "cake":                                                            if raining == "yes":
  print("Wow, I love cake too!")                                        print("You should take the bus to work.")
  print("Did I tell you I like cake?")                                 if raining == "no":
                                                                                           print("You should walk to work.")

Nothing appearing :
When you want to make sure nothing appears other than the coding use empty quotations at the end of your code .
 Example -
text= input("Text: ")
if text == "Marco!":
  print("Polo!")
  if text == "":
    print("")

True/ False:

In python they use true and false with if functions and other parts of the coding.
 Example -
x = 3
print(x > 10)
False
Else :       
Else is better for simplifying if because you can use it to apply a certain answer to any other input other than the expected answer.
Example -
raining = input("Is it raining (yes/no)? ")
if raining == "yes":
  print("You should take the bus to work.")
else:
  print("You should walk to work.")

Comparing : 
In else you can use operations to compare. This is available because the program wont always make sense so with these you can make it conditional to the coding.
OperationOperator
equal to==
not equal to!=
less than<
less than or equal to<=
greater than>
greater than or equal to>=
Example -
x = 5
if Charge <=5:
  print("Connect your charger!")
else:
    print("All good.")

Decisions with multiple options (elif): 
When you need to make more than one option you can use else and if to create the other option but it can get a bit mess or instead you can use elif as a abbreviation 
Example - 
Using elif                                                        Not using elif 
x = 5                                                              else: 
if x < 3:                                                            if x == 3:
  print("x is less than three")                             print("x is equal to three")
elif x == 3:
  print("x is equal to three")
else:
  print("x is greater than three")

String within a string
Example -
msg = 'hello world' 
print('h' in msg) 
True 

Sub string within a string
Example -
msg = 'concatenation is fun'
print('cat' in msg) 
print('dog' in msg)
True
False

Making Decisions 
Using if with a variable/string means you limit what you are looking for.
Example -
name = input('Enter your name? ') 
if 'x' in name:
  print('Your name contains an x!')
else:
  print('No "x" in your name.') 

String Methods 
Changing to lowercase:
Example -
msg = "I know my ABC" 
print(msg.lower())
or
msg = "I know my ABC" 
newmsg = msg.lower()
print(newmsg)
Changing to uppercase:
msg = "I know my ABC" 
newmsg = msg.upper()
print(newmsg)
or
For printing statements:
msg = "I know my ABC"
print("Original:", msg)
print("Lowercase:", msg.lower())
print("Uppercase:", msg.upper())
Original: I know my ABC
Lowercase: i know my abc
Uppercase: I KNOW MY ABC

Checking the case:
Example -
msg = "a lowercase string!" 
print(msg.islower()) 
print(msg.isupper())

For first letter capital and rest not use name.capitalize():
name = input('Enter your name: ') 
print('Name converted to:', name.capitalize())
Enter your name: XAVIER
Name converted to: Xavier

Replacing String 
Using this function will let you replace parts of the string.
Example -
msg = 'hello world'
print(msg.replace('l', 'X'))
heXXo worXd
or
msg = 'hello world'
msg = msg.replace('hello', 'goodbye')
msg = msg.replace('o', 'X')
print(msg)
gXXdbye wXrld
Counting Characters in a string 
This will check how many characters are in that string you an also use double letter such as ll.
Example -
msg = "hello world" 
print(msg.count("l"))
3

Week 1

All the function learnt this week 

Print : 
Print, does what it implies, it prints what ever you put with in those brackets.
Example - print("Hello, World!")

SyntaxError or NameError:
Syntax or Name error, pops up in red and highlights where or which line the computer cant read. These errors can be spelling, grammar or the wrong function 
Example - print "Hello" -- Here the brackets are left out and wont print

Variables :
Variables are simply used for storing data and use the operator = . Using a word or character of your choice you can store all the data, to use in other parts of your code 
Example -   msg = "Hi there"   This can make code neat and easier when you have multiple variables 
                    print(msg)

Grammar - Quotation & Commas:
Commas are used to separate different variables or phrases 
Example -  print(firstname, lastname)

Quotation marks are used a lot in python. Use can use either singe or double quotation marks, but just make sure to close with the same type. Also if you use double on the outer if you want quotation for grammar use single inside. quotations can also be used for spaces when using print. 
Example -  print("Harry" + " " + "Potter") ---or----- 'One does not simply "' + verb + '" into Mordor!'

Input: 
Input is mainly used for asking a question or to get data from the user. It is always used with brackets and a variable so it can be used in the print function. 
Example - name = input("What is your name? ")
                  print(name)
Joining messages:
To join different variables or phrases you can use + 
Example- ( word +" "+ word +" "+ word) 

Maths in Python:

addition
-subtraction
*multiplication
/division
**to the power of
Example-    n = 10
                    print(n**2)

Maths with words
Example-  print("ab"*5)

Length:
The length function counts the length of the string. len is used with brackets 
Example-  print(len('Hello World!'))---- or------  a = "abcdefghijklmnopqrstuvwxyz"
                                                                               print(len(a))
Converting Strings to Numbers  (int)
When using string as a number you have to convert it into integer using int, use this function with brackets.
Example-    number = int(input('Enter a number: '))
                    new_number = number - 1
                    print(new_number)

Converting Numbers to Strings  (str)
This is simply converting the integer into a string 

Example-  answer = 5
                  print("the answer is " + str(answer))




Grok learning is a website where you can learn coding from scratch. Our school entered into the NCSS challenge (beginners) which started on August 4th 2014 and for the next 5 weeks I will be completing the challenge. The program involves completing tasks in the programming language python. You earn points for each task completed, which they use to scale you against other students competing. This blog will have entries from my experiences each week, from what I found hard to what I found easy.Since my programming experience is minimal, I hope by the end of this challenge I will have some new skills in the programming world.