### at Silver Oak Elementary School, San Jose, CA

Primary Programmers is an initiative of Parent Teacher Organization at Silver Oak Elementary (PTO). Parent volunteers have set a mission to provide elementary students with an environment where they can learn and practice how to create software applications. There are two main activities:
Primary Programming Bronze and Primary Programming Silver. The courses are open to Silver Oak Elementary Students only, but the Primary Programming Olympiad is open to any elementary students.

#### Resources

On-line Python IDE (Integrated development environment)
https://repl.it/languages/python3

On-line learning resources:

#### Primary Programmers Bronze

• Lesson 19: Bar charts with Turtle  import randomresults = [0,0,0,0,0,0,0,0,0,0,0,0]for x in range(10000): dice = random.randint(1,6) dice2 = random.randint(1,6) results[dice + dice2 -1] = results[dice + dice2-1] + 1import turtle as tnike = t.Turtle()nike.penup()nike.setposition(-200,-200)nike.pendown()nike.fd(400)nike.penup()nike.setposition(-200,-200)nike.pendown()nike.left(90)nike.fd(400)x_start = -230for r in results: x_start = x_start + 40 nike.penup() nike.setposition(x_start,-200) nike.pendown() height = (400 * r)/2000 nike.begin_fill() nike.fd(height) nike.write(r) nike.right(90) nike.fd(20) nike.right(90) nike.fd(height) nike.end_fill() nike.left(180)
Posted Mar 10, 2020, 8:02 AM by Attila Lengyel
• Lesson 18: Pixels taught by Parag Gupta  #### create a drawing area filled with pixels whose colors can be changed by clicking # initialize some stuff and create a function to draw a squareimport turtle as tgoo = t.Turtle()goo.speed(0) def draw_square (side_len): for i in range(4): goo.forward(side_len) goo.left(90) ### draw the boundary square starting from (-300, -300) with each side being 600sq_x = -300 ## starting x coordinate of squaresq_y = -300 ## starting y coordinate of squaresq_sz = 600 ## length of each side of square goo.penup()goo.setposition(sq_x, sq_y)goo.pendown()draw_square(sq_sz) ### draw the grid of pixelsrow_pixels = 8 #### adjust this to change resolution of pixels ####pixel_width = sq_sz/row_pixels ## length of each side of the pixel def draw_grid (row_pix): for i in range (row_pix): # draw a row of pixels for j in range (row_pix): draw_square(pixel_width) goo.forward(pixel_width) # go to the beginning of the next row of pixels goo.penup() goo.setposition(sq_x, goo.ycor()+pixel_width) goo.pendown() # comment the following out if you don't need the grid drawn since# it can take some time to drawdraw_grid (row_pixels) ### create a list of colors, feel free to add to or remove from the listcolors = ['black', 'white', 'red', 'gray', 'orange', 'magenta', 'green', 'blue', 'yellow', 'brown']num_colors = len(colors) ### Figure out the total number of pixels and create a list having an entry for### each pixel which keeps track of the next color when that pixel is clicked. Initialize### each entry to 0, which means the first color would be black. For example, if### a particular entry had a value of 3, that pixel would be gray when clicked next. When### a pixel gets clicked on, we would need to increment the value for that pixel in this list. num_pixels = row_pixels * row_pixels # initialize the list called pix_color to keep track of colors for each pixelpix_color = [] # set each value in the list to initially be 0for i in range(num_pixels) : pix_color.append(0) ### Define a function to fill the clicked pixel with a color, where cl_x and cl_y### are the x and y coordinates of the clicked location. The bottom left pixel is pixel 0.### The one to the right is pixel 1 and so forth. If row_pixels was 4, the first pixel### in the second row would be pixel 4 and the top right pixel would be pixel 15. We### use the pixel numbers to keep track of what color each pixel will be when clicked next. def fill_pixel(cl_x, cl_y): # only fill the pixel if the click was within the big square if ((cl_x > sq_x) and (cl_x < (sq_x + sq_sz)) and (cl_y > sq_y) and (cl_y < (sq_y + sq_sz))) : ## figure out the pixel number # calculate the x and y coordinates within our square and then divide by # the pixel width to figure out which row and column the click was in x = cl_x - sq_x pix_col = int(x / pixel_width) y = cl_y - sq_y pix_row = int(y / pixel_width) # calculate the actual pixel number from the row and column numbers pix_num = pix_col + (pix_row * row_pixels) print (pix_num) # Calculate the start coordinates of the pixel to fill by using the column, # row, pixel width, and square coordinates. fill_pix_x = (pix_col * pixel_width) + sq_x fill_pix_y = (pix_row * pixel_width) + sq_y # Figure out the fill color by looking up the pixel number in the pix_color list # and then using the value in that list to look up the actual color in the colors list. fill_color = colors[pix_color[pix_num]] goo.color(fill_color) # Increment the value for that pixel in the pix_color list. Use the mod function so # value goes back to 0 when we've reached the last color. pix_color[pix_num] = (pix_color[pix_num] + 1) % num_colors # fill the pixel with the fill color goo.penup() goo.setposition(fill_pix_x, fill_pix_y) goo.begin_fill() draw_square(pixel_width) goo.end_fill() ## When the screen is clicked, fill the pixel, and wait for the next click.screen = t.Screen()screen.onscreenclick(fill_pixel)screen.listen()
Posted Mar 4, 2020, 1:54 PM by Attila Lengyel
• Lesson 17: Practice makes master  a = int(input("Give me a number:"))b = int(input("Give me an other:"))print(a + b)print("\n\n First 100 numbers")num = []for i in range(0,101): num.append(i)print(num)print("\n\n\nEven numbers only:")num.clear();for i in range(0,101): if i%2 == 0: num.append(i)print(num)import turtle as t bob = t.Turtle()for i in range(0,4): bob.forward(100) bob.left(90)
Posted Feb 25, 2020, 8:05 AM by Attila Lengyel
• Lesson 16: Nested loops with Turtle  import turtle as timport random as rgoo = t.Turtle()goo.speed(0)colors = ['red', 'orange', 'magenta', 'green', 'blue', 'yellow']for k in range(0,8): for i in range(0,8): x = -180 + i * 50 y = 180 - k * 50 goo.penup() goo.setposition(x,y) goo.pendown() goo.color(r.choice(colors)) goo.begin_fill() for j in range(0,4): goo.right(90) goo.forward(40) goo.end_fill()for i in range(0,5): for j in range(0,5): print(i, "x", j, "=", i * j)
Posted Feb 11, 2020, 8:02 AM by Attila Lengyel
• Lesson 15: Turtle in the box  import turtle as tjohn = t.Turtle()john.shape("turtle")john.fillcolor("blue")john.pencolor("blue")screen = t.Screen()john.penup()john.setposition(-200,200)john.pendown()john.forward(400)john.right(90)john.forward(400)john.right(90)john.forward(400)john.right(90)john.forward(400)john.setposition(0,0)def geofence(): if john.ycor() > 190: return False if john.ycor() < -190: return False if john.xcor() > 190: return False if john.xcor() < -190: return False return Truedef move_forward(): speed = 10 if geofence() == False : john.setposition(0,0) john.pencolor("blue") john.forward(speed)def move_backward(): speed = 10 if geofence() == False : john.setposition(0,0) john.pencolor("white") john.backward(speed)def turn_right(): john.right(10)def turn_left(): john.left(10)def clear_screen(): john.clear()def start_draw(): john.pendown()def stop_draw(): john.penup()screen.onkey(move_forward, "Up")screen.onkey(move_backward, "Down")screen.onkey(turn_right, "Right")screen.onkey(turn_left, "Left")screen.onkey(clear_screen, "c")screen.onkey(stop_draw, "u")screen.onkey(start_draw, "d")screen.listen()
Posted Feb 4, 2020, 8:00 AM by Attila Lengyel
• Lesson 14: Controlling the turtle  import turtle as tjohn = t.Turtle()john.shape("turtle")john.fillcolor("blue")john.pencolor("blue")screen = t.Screen()def move_forward(): john.pencolor("blue") john.forward(10)def move_backward(): john.pencolor("white") john.backward(10)def turn_right(): john.right(10)def turn_left(): john.left(10)def clear_screen(): john.clear()def start_draw(): john.pendown()def stop_draw(): john.penup()screen.onkey(move_forward, "Up")screen.onkey(move_backward, "Down")screen.onkey(turn_right, "Right")screen.onkey(turn_left, "Left")screen.onkey(clear_screen, "c")screen.onkey(stop_draw, "u")screen.onkey(start_draw, "d")screen.listen()
Posted Jan 28, 2020, 8:03 AM by Attila Lengyel
• Lesson 13: Drawing letter S with Turtle  import turtledef draw_s(t, x, y): min_y = 100000 max_y = -100000 t.penup() t.setpos(x, y) t.pendown() t.left(90) for i in range(27): t.left(10) t.forward(1) if t.ycor() < min_y: min_y = t.ycor() if t.ycor() > max_y: max_y = t.ycor() for i in range(27): t.right(10) t.forward(1) if t.ycor() < min_y: min_y = t.ycor() if t.ycor() > max_y: max_y = t.ycor() print(min_y, max_y)bob = turtle.Turtle()draw_s(bob, -130,130)
Posted Jan 21, 2020, 10:08 AM by Attila Lengyel
• Lesson 12: Turtle is here... simple drawing with Python Turtle  import turtle as tjojo_siwa = t.Turtle()jojo_siwa.forward(50)jojo_siwa.right(90)jojo_siwa.forward(50)jojo_siwa.right(90)jojo_siwa.forward(50)jojo_siwa.right(90)jojo_siwa.forward(50)jojo_siwa.right(90)for i in range (0,4): jojo_siwa.forward(50) jojo_siwa.left(90)jojo_siwa.clear()for i in range(0,5): jojo_siwa.forward(50) jojo_siwa.right(144)jojo_siwa.clear()num_sides = int(input("How many sides:"))side_length = int(input("Length:"))angle = 360 / num_sidesfor i in range(0,num_sides): jojo_siwa.forward(side_length) jojo_siwa.right(angle)jojo_siwa.done()
Posted Jan 14, 2020, 8:05 AM by Attila Lengyel
• Lesson 11: Prime numbers and functions  print(10%2)for i in range(1,10): print("10 modulo", i, "is", 10%i)n = int(input("Give me a number:"))prime = Truefor i in range(2, n): if n%i == 0: prime = False breakif prime == False: print(n, "is not a prime number")else: print(n, "is a prime number")def isprime(n): prime = True for i in range(2,n): if n%i == 0: prime = False break return primeif isprime(n) == False: print(n, "is not a prime number")else: print(n, "is a prime number")for i in range (1,1000): if isprime(i): print(i)
Posted Jan 7, 2020, 8:01 AM by Attila Lengyel
• Lesson 10: Binary search  upper = int(input("Give me the max:"))lower = int(input("Give me the min:"))guess = int(input("Guess a number in between:"))while guess > upper or guess < lower: print("Wrong number! Try again.") guess = int(input("Guess a number in between:"))import mathprint(math.ceil(34.7))print(math.floor(34.7))xyx = math.floor((upper + lower)/2)while xyx != guess: print("Is it", xyx,"?") answer= input("yes or no?:") if answer == "no": answer = input("Is it lower or higher?") print(answer) if answer == "lower": upper = xyx else: lower = xyx xyx = math.floor((upper + lower)/2)
Posted Dec 17, 2019, 8:16 AM by Attila Lengyel
Showing posts 1 - 10 of 64. View more »

#### Primary Programmers Silver

• Lesson 17: Bar charts with Turtle and exponential growth  import random as r#series = [0,0,0,0,0,0]#for x in range(10000):# dice = r.randint(1,6)# series[dice-1] = series[dice-1] + 1series = [1]for x in range(14): growth= series[len(series)-1] growth= growth* 2; series.append(growth)import turtle as tst = t.Turtle()st.penup()st.setposition(-200,-200)st.pendown()st.fd(400)st.penup()st.setposition(-200,-200)st.pendown()st.left(90)st.fd(400)x = -230for s in series: x = x + 40 st.penup() st.setposition(x,-200) st.pendown() height = (400 * s) / max(series) st.begin_fill() st.fd(height) st.write(s) st.right(90) st.fd(20) st.right(90) st.fd(height) st.end_fill() st.right(180)
Posted Mar 12, 2020, 8:04 AM by Attila Lengyel
• Lesson 16: Squares with Turtle  import turtle as tbob = t.Turtle()bob.speed(30)x = [-160,-130,-100, -70, -40, -10]y = [160, 130, 100, 70, 40, 10]for a in x: for b in y: bob.penup() bob.setposition(a,b) bob.pendown() for i in range(4): bob.fd(30) bob.right(90)
Posted Mar 5, 2020, 8:02 AM by Attila Lengyel
• Lesson 14: Two turtle chasing each other in a box  ```import turtle as t john = t.Turtle() john.shape("turtle") john.fillcolor("blue") john.pencolor("blue") bob = t.Turtle() bob.shape("turtle") bob.fillcolor("red") bob.pencolor("red") bob.penup() screen = t.Screen() john.penup() john.setposition(-200,200) john.pendown() for x in range(4): john.fd(400) john.right(90) john.penup() john.setposition(-190,190) def move_forward(): john.pencolor("blue") john.forward(9) if john.xcor() < -200 and john.ycor()> 200: john.setposition(-199,199) if john.xcor() > 200 and john.ycor()> 200: john.setposition(199,199) if john.xcor() > 200 and john.ycor() < -200: john.setposition(199,-199) if john.xcor() < -200 and john.ycor()<-200: john.setposition(-199,-199) if john.ycor() > 200: john.setposition(john.xcor(), 199) if john.xcor() > 200: john.setposition(199, john.ycor()) if john.ycor() < -200: john.setposition(john.xcor(),-199) if john.xcor() < -200: john.setposition(-199, john.ycor()) def move_backward(): john.pencolor("white") john.backward(9) if john.xcor() < -200 and john.ycor()> 200: john.setposition(-199,199) if john.xcor() > 200 and john.ycor()> 200: john.setposition(199,199) if john.xcor() > 200 and john.ycor() < -200: john.setposition(199,-199) if john.xcor() < -200 and john.ycor()<-200: john.setposition(-199,-199) if john.ycor() > 200: john.setposition(john.xcor(), 199) if john.xcor() > 200: john.setposition(199, john.ycor()) if john.ycor() < -200: john.setposition(john.xcor(),-199) if john.xcor() < -200: john.setposition(-199, john.ycor()) def turn_right(): john.right(10) def turn_left(): john.left(10) def move_forward_b(): bob.pencolor("red") bob.forward(10) if bob.xcor() < -200 and bob.ycor()> 200: bob.setposition(-199,199) if bob.xcor() > 200 and bob.ycor()> 200: bob.setposition(199,199) if bob.xcor() > 200 and bob.ycor() < -200: bob.setposition(199,-199) if bob.xcor() < -200 and bob.ycor()<-200: bob.setposition(-199,-199) if bob.ycor() > 200: bob.setposition(bob.xcor(), 199) if bob.xcor() > 200: bob.setposition(199, bob.ycor()) if bob.ycor() < -200: bob.setposition(bob.xcor(),-199) if bob.xcor() < -200: bob.setposition(-199, bob.ycor()) def move_backward_b(): bob.pencolor("white") bob.backward(10) if bob.xcor() < -200 and bob.ycor()> 200: bob.setposition(-199,199) if bob.xcor() > 200 and bob.ycor()> 200: bob.setposition(199,199) if bob.xcor() > 200 and bob.ycor() < -200: bob.setposition(199,-199) if bob.xcor() < -200 and bob.ycor()<-200: bob.setposition(-199,-199) if bob.ycor() > 200: bob.setposition(bob.xcor(), 199) if bob.xcor() > 200: bob.setposition(199, bob.ycor()) if bob.ycor() < -200: bob.setposition(bob.xcor(),-199) if bob.xcor() < -200: bob.setposition(-199, bob.ycor()) def turn_right_b(): bob.right(10) def turn_left_b(): bob.left(10) def clear_screen(): john.clear() def start_draw(): john.pendown() def stop_draw(): john.penup() screen.onkey(move_forward, "Up") screen.onkey(move_backward, "Down") screen.onkey(turn_right, "Right") screen.onkey(turn_left, "Left") screen.onkey(clear_screen, "c") screen.onkey(stop_draw, "u") screen.onkey(start_draw, "d") screen.onkey(move_forward_b, "e") screen.onkey(move_backward_b, "d") screen.onkey(turn_right_b, "f") screen.onkey(turn_left_b, "s") screen.listen()```
Posted Feb 13, 2020, 8:04 AM by Attila Lengyel
• Lesson 13: Turtle and lots of ifs  import turtle as tjohn = t.Turtle()john.shape("turtle")john.fillcolor("blue")john.pencolor("blue")screen = t.Screen()john.penup()john.setposition(-200,200)john.pendown()for x in range(4): john.fd(400) john.right(90)john.penup()john.setposition(0,0)def define_action(john): if john.xcor() < 200 and john.ypos()> 200: return 1 if john.xcor() > 200 and john.ypos()> 200: return 3 if john.xcor() > 200 and john.ypos() < -200: return 5 if john.xcor() < -200 and john.ypos()<-200: return 7 if john.ycor() > 200: return 2 if john.xcor() > 200: return 4 if john.ycor() < -200: return 6 if john.xcor() < -200: return 8 return 9def action(john): item = define_action() john.write(item, font=("Arial", 64, "normal")) if item == 1: john.setposition(-199,199) if item == 3: john.setposition(199,199) if item == 5: john.setposition(199,-199) if item == 7: john.setposition(-199,-199) if item == 2: john.setposition(john.xcor(), 199) if item == 4: john.setposition(199, john.ycor()) if item == 6: john.setposition(john.xcor(),-199) if item == 8: john.setposition(-199, john.ycor()) def move_forward(): john.pencolor("blue") john.forward(10)def move_backward(): john.pencolor("white") john.backward(10)def turn_right(): john.right(10)def turn_left(): john.left(10)def clear_screen(): john.clear()def start_draw(): john.pendown()def stop_draw(): john.penup()screen.onkey(move_forward, "Up")screen.onkey(move_backward, "Down")screen.onkey(turn_right, "Right")screen.onkey(turn_left, "Left")screen.onkey(clear_screen, "c")screen.onkey(stop_draw, "u")screen.onkey(start_draw, "d")screen.listen()
Posted Feb 6, 2020, 8:05 AM by Attila Lengyel
• Lesson 12: Controlling the Turtle  import turtle as tjohn = t.Turtle()john.shape("turtle")john.fillcolor("blue")john.pencolor("blue")screen = t.Screen()def move_forward(): john.pencolor("blue") john.forward(10)def move_backward(): john.pencolor("white") john.backward(10)def turn_right(): john.right(10)def turn_left(): john.left(10)def clear_screen(): john.clear()def start_draw(): john.pendown()def stop_draw(): john.penup()screen.onkey(move_forward, "Up")screen.onkey(move_backward, "Down")screen.onkey(turn_right, "Right")screen.onkey(turn_left, "Left")screen.onkey(clear_screen, "c")screen.onkey(stop_draw, "u")screen.onkey(start_draw, "d")screen.listen()
Posted Jan 30, 2020, 8:00 AM by Attila Lengyel
• Lesson 11: Python Turtle  import turtlebob = turtle.Turtle()bob.forward(80)bob.left(90)bob.forward(80)bob.left(90)bob.forward(80)bob.left(90)bob.forward(80)bob.clear()bob.shape("turtle")bob.pencolor("red")for i in range(4): bob.left(90) bob.forward(80) bob.clear()bob.left(90)for i in range(5): bob.fd(80) bob.right(144)bob.clear()sides = int(input("How many sides?:"))side_length = int(input("Length?:"))for i in range(sides): bob.forward(side_length) bob.right(360/sides)
Posted Jan 16, 2020, 9:05 AM by Attila Lengyel
• Lesson 10: First 100 prime numbers  print(10%3)print(15%6)n = int(input("Give me a number:"))isprime = Truefor i in range(2,n): if n%i == 0: isprime = False breakif isprime: print(n, "is a prime number")else: print(n, "is not a prime number")def spoungebob(n): isprime = True for i in range(2,n): if n%i == 0: isprime = False break return isprimeif spoungebob(n): print("Spounge Bob says", n, "is a prime number")else: print("Spounge Bob says", n, "is not a prime number")counter = 0n = 0while counter <= 1000: n = n + 1 if spoungebob(n): print(counter, n) counter = counter + 1
Posted Jan 9, 2020, 8:00 AM by Attila Lengyel
• Lesson 9: Binary search  target = int(input("Think of a number:"))lower = 1upper = 100while target < 1 or target > 100: print("Please think between 1 and 99!") target = int(input("Try again:"))guess = 0import mathwhile guess != target: guess = lower + math.floor((upper - lower)/2) print("Is the number", guess, "? (yes/lower/higher):") answer = input() if answer == "yes": print("I knew it!!!") elif answer == "lower": upper = guess - 1 elif answer == "higher": lower = guess + 1
Posted Dec 19, 2019, 8:02 AM by Attila Lengyel
• Lesson 8: Rolling the dice  import random as rprint("Let's roll the dice!")roll = r.randint(1,6)print("I rolled ", roll)rolls = [0,0,0,0,0,0]for x in range(0, 100): roll = r.randint(1,6) rolls[roll-1] = rolls[roll-1] + 1print(rolls)rolls2 = [0,0,0,0,0,0,0,0,0,0,0,0]for x in range(0,1000000): roll1 = r.randint(1,6) roll2 = r.randint(1,6) num = roll1 + roll2 rolls2[num-1] = rolls2[num-1] + 1for x in range(0,12): print(x + 1, ":", rolls2[x])
Posted Dec 12, 2019, 7:59 AM by Attila Lengyel
• Lesson 7: Fibonacci sequence with for loop and list  a = 1b = 1c = a + bprint(a,b,c)a = bb = cc = a + bprint(c)a = bb = cc = a + bprint(c)print("I'm the while loop")x = 0while x < 10: a = b b = c c = a + b print(c) x = x + 1a = 1b = 1c = a + bprint("I'm the for loop")for x in range(0,10): a = b b = c c = a + b print(x, ":", c)print("I'm the list")f = [1,1,2]for x in range(0,11): f.append(f[len(f)-1] - 2 * f[len(f)-2])print(f)
Posted Dec 5, 2019, 8:55 AM by Attila Lengyel
• Lesson 6: While loop and multiplications  a = 4b = 5print(a * b)a = int(input("Give me a:"))b = int(input("Give me b:"))print(a * b)import random as ra = r.randint(0, 10)b = r.randint(0, 10)print(a, "*", b, "=", a * b)a = r.randint(3,20)b = r.randint(3,20)task = "What is " + str(a) + " * " + str(b) + "? "answer = int(input(task))if answer == a * b: print("Good job!")else: print("Incorrect! It is", a * b)i = 0while i < 10: print(i) a = r.randint(12,30) b = r.randint(12,30) task = "What is " + str(a) + " * " + str(b) + "? " answer = int(input(task)) if answer == a * b: print("Good job!") else: print("Incorrect. It is ", a * b) i = i + 1
Posted Nov 21, 2019, 8:04 AM by Attila Lengyel
• Lesson 5: The big IF  a = int(input("give me a number:"))if a < 10: print("a is smaller than 10")elif a == 10: print("a equals to 10")else: print("a is greater than 10")print("the task is done")print(10%2)print(9%2)if a % 2 == 0: print("a is an even number")else: print("a is an odd number")if a % 2 == 0 and a < 10: print("a is a even number smaller than 10 ")
Posted Nov 14, 2019, 7:58 AM by Attila Lengyel
• Lesson 4: Lists  silver = ["Zubin", "Nadezda"]print(silver)silver.append("Sumukh")print(silver)print(silver[1])silver.append("Enna")silver.append("Anika")silver.append("Sarah")silver.append("Eesha")silver.append("Tanisha")silver.append("Claire")silver.append("Katie")silver.append("Sumedh")silver.append("Micah")silver.append("Alex")silver.append("Mihir")print(silver)print(len(silver))silver.sort()print(silver)silver.reverse()print(silver)import randomiplayer1 = random.randint(0, len(silver) - 1)player1 = silver[iplayer1]silver.remove(player1)iplayer2 = random.randint(0, len(silver) - 1)player2 = silver[iplayer2]silver.remove(player2)print(player1, "play against", player2)print(silver)
Posted Nov 7, 2019, 7:54 AM by Attila Lengyel
• Lesson 3 - Halloween game  print("Halloweeeeeeen is here...tatata")print("Come in if you dare...print("Don't be scared...question = input("Tell me, why are you here?:")import randomanswer = random.randint(0,2)if question == "trick or treat": if answer == 0: print("Boooooooooooooooooooo") if answer == 0: print("Here is your candy!") if answer == 0: print("Get off my lawn!!!")if question == "to scare you": if answer == 0: print("Roaaaaaaaaarrrr....") if answer == 0: print("Here is your candy, don't scare me!") if answer == 0: print("The one who should be scared is you... ")
Posted Oct 31, 2019, 10:47 AM by Attila Lengyel
• 2019-2020 - Lesson 1  import randomguess = random.randint(0,2)if guess == 0: print("Rock")if guess == 1: print("Paper")if guess == 2: print("Scissors")
Posted Oct 17, 2019, 11:00 AM by Attila Lengyel
• Lesson 22: Draw THANK with turtle  import turtle as ttt = t.Turtle()def draw_t(bob,x,y): bob.penup() bob.goto(x,y) bob.pendown() bob.forward(50) bob.left(180) bob.forward(25) bob.left(90) bob.forward(60) bob.left(90)def draw_h(bob,x,y): bob.penup() bob.goto(x,y) bob.pendown() bob.right(90) bob.forward(60) bob.left(180) bob.forward(30) bob.right(90) bob.forward(30) bob.left(90) bob.forward(30) bob.left(180) bob.forward(60) bob.left(90)def draw_a(bob, x,y): bob.penup() bob.goto(x,y) bob.pendown() bob.goto(x + 15, y + 60) bob.goto(x + 30, y + 0) bob.penup() bob.goto(x,y + 30) bob.pendown() bob.goto(x + 30, y + 30)def draw_n(bob, x, y): bob.penup() bob.goto(x,y) bob.pendown() bob.left(90) bob.forward(60) bob.goto(x + 30, y) bob.forward(60) bob.right(90)def draw_k(bob, x, y): bob.penup() bob.goto(x,y) bob.pendown() bob.right(90) bob.forward(60) bob.right(180) bob.forward(25) bob.goto(x + 30 ,y) bob.goto(x,y -35) bob.goto(x + 30 ,y - 60) draw_t(tt, -200, 200)draw_h(tt, -140, 200)draw_a(tt, -100, 140)draw_n(tt, -60, 140)draw_k(tt, -20, 200)
Posted Jun 7, 2019, 8:07 AM by Attila Lengyel
• Lesson 21: Turtle in corners  import turtleimport timeimport randomt = turtle.Turtle()def draw(x,y, delay, s): t.clear() t.penup() t.goto(x,y) t.pendown() t.speed(s) for x in range(0,3): t.forward(50) t.left(120) time.sleep(delay)time.sleep(2)draw(0,0,3, 5)for x in range(0,10): time.sleep(1) corner = random.randint(1,4) if corner == 1: draw(200,200,0,0) elif corner == 2: draw(-200, 200,0,0) elif corner == 3: draw(-200, -200,0,0) else: draw(200, -200,0,0) time.sleep(2) draw(0,0,3)
Posted May 31, 2019, 8:00 AM by Attila Lengyel
• Lesson 20: Catch me if you can  import turtle as tplayer1 = t.Turtle()player1.shape("turtle")player1.pencolor("white")player1.fillcolor("blue")player2 = t.Turtle()player2.shape("turtle")player2.fillcolor("red")player2.pencolor("white")player2.goto(-180, 180)speed = 10angle = 10screen = t.Screen()def draw_rectangle(player, x, y, width, height, color): startpos = player.pos() startcolor = player.pencolor() player.pencolor(color) player.up() player.goto(x, y) player.down() player.forward(width) player.left(90) player.forward(height) player.left(90) player.forward(width) player.left(90) player.forward(height) player.left(90) player.up() player.goto(startpos) player.down() player.pencolor(startcolor)draw_rectangle(player1, -210, -210, 420, 420, "black")def position(player): if player.xcor() >= 200 : player.up() player.goto(199, player.ycor()) player.down() return False if player.xcor() <= -200: player.up() player.goto(-199, player.ycor()) player.down() return False if player.ycor() >= 200: player.up() player.goto(player.xcor(), 199) player.down() return False if player.ycor() <= -200: player.up() player.goto(player.xcor(), -199) player.down() return False return Trueimport mathdef catch(playera, playerb): x1 = playera.xcor() y1 = playera.ycor() x2 = playerb.xcor() y2 = playerb.ycor() c = math.pow(x1-x2,2) + math.pow(y2-y1,2) c = math.sqrt(c) if c < 10: playera.fillcolor("red") playerb.fillcolor("blue") def f(): if position(player1): player1.forward(speed)def b(): if position(player1): player1.backward(speed)def r(): player1.right(angle)def l(): player1.left(angle)screen.onkey(f, "Up")screen.onkey(b, "Down")screen.onkey(r, "Right")screen.onkey(l, "Left")def f2(): if position(player2): player2.forward(speed) catch(player1, player2)def b2(): if position(player2): player2.backward(speed) catch(player1, player2)def r2(): player2.right(angle)def l2(): player2.left(angle)screen.onkey(f2, "q")screen.onkey(b2, "a")screen.onkey(r2, "x")screen.onkey(l2, "z")screen.listen()
Posted May 10, 2019, 8:04 AM by Attila Lengyel
• Lesson 18: Turtle in a box  import turtle as tplayer1 = t.Turtle()player1.shape("turtle")player1.pencolor("white")speed = 10angle = 10screen = t.Screen()def draw_rectangle(player, x, y, width, height, color): startpos = player.pos() startcolor = player.pencolor() player.pencolor(color) player.up() player.goto(x, y) player.down() player.forward(width) player.left(90) player.forward(height) player.left(90) player.forward(width) player.left(90) player.forward(height) player.left(90) player.up() player.goto(startpos) player.down() player.pencolor(startcolor)draw_rectangle(player1, -210, -210, 420, 420, "red")def position(player): if player.xcor() >= 200 : player.up() player.goto(199, player.ycor()) player.down()    return False if player.xcor() <= -200: player.up() player.goto(-199, player.ycor()) player.down()    return False if player.ycor() >= 200: player.up() player.goto(player.xcor(), 199) player.down()    return False if player.ycor() <= -200: player.up() player.goto(player.xcor(), -199) player.down()    return False return Truedef f(): if position(player1): player1.forward(speed)def b(): if position(player1): player1.backward(speed)def r(): player1.right(angle)def l(): player1.left(angle)screen.onkey(f, "Up")screen.onkey(b, "Down")screen.onkey(r, "Right")screen.onkey(l, "Left")screen.listen()
Posted May 10, 2019, 7:28 AM by Attila Lengyel
• Lesson 17: Drawing with Turtle  import turtlebob = turtle.Turtle()bob.forward(50)bob.left(90)bob.forward(50)bob.left(90)bob.forward(50)bob.left(90)bob.forward(50)bob.clear()for i in range(4): bob.forward(100) bob.right(90)bob.clear()bob.pencolor("red")num_side = 6side_length = 100angle = 360 / num_sidefor i in range(num_side): bob.forward(side_length) bob.right(angle)bob.clear()for i in range(5): if i == 1 or i == 3: bob.penup() bob.forward(50) bob.right(144) if i == 1 or i == 3: bob.pendown()bob.clear()for i in range(10): bob.forward(i * 20) bob.right(144)bob.clear()bob.penup()bob.setposition(0,0)bob.pendown()bob.speed(2) colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow'] for x in range(100): bob.pencolor(colors[x%6]) bob.circle(5*x) bob.circle(-5*x) bob.left(x)
Posted Apr 12, 2019, 8:12 AM by Attila Lengyel
• Lesson 16: What is a palindrome?  def eliminate(w): tmp = "" for i in w: if i.isalnum(): tmp = tmp + i.lower() return tmpword = input("Give me a word:")word = eliminate(word)reverse = ""for i in word: reverse = i + reverseprint(reverse)if word == reverse: print("This is a palindrome")else: print("This is not a palindrome")
Posted Apr 5, 2019, 8:04 AM by Attila Lengyel
• Lesson 15: Hangman v1  cl = ""wl = " "def draw(word, cl, wl): a = "" for c in word: if c in cl: a += c + " " else: a += "_ " print(a) if "_" not in a: return "win" elif len(wl) > 7: return "lost" else: return "next" word = input("Give me a word:")status = draw(word, cl, wl)while status == "next": g = input("Guess a letter:") if g in word and g not in cl: cl += g elif g not in wl: wl += g status = draw(word, cl, wl) if status != "next": print(status)
Posted Mar 29, 2019, 8:00 AM by Attila Lengyel
• Lesson 14: Odd, even and prime numbers with modulo  import random as rnumber = r.randint(0,1000)if number % 2 == 0: print(number, "is an even number")else: print(number, "is odd number")#list up prime numbersprime = [2,3,5,7,11]while len(prime) < 1000: nextnum = prime[len(prime) - 1] stop = False while stop == False: nextnum += 1 isPrime = True for i in prime: if nextnum % i == 0: isPrime = False break if isPrime: prime.append(nextnum) stop = True print(prime)
Posted Mar 22, 2019, 7:56 AM by Attila Lengyel
• Number guessing game user vs computer  def guessgame(guess, n): if guess == n: return 0 elif guess < n: return -1 else: return 1import random as rn = r.randint(0,100)counter = 0guessed = Falsewhile (guessed == False): guess = int(input("What number did I think of?:")) counter += 1 result = guessgame(guess, n) if result == 0: guessed = True elif result == -1: print("Too low") else: print("Too high")print("Good guess! The number is", n, " You tried", counter, "times")import mathprint("Now you think of a number between 0 and 100!")upper = 100lower = 0answer =""while answer != "good": guess = lower + math.floor((upper - lower)/2) print("Is it", guess, "? (high/low/good):") answer = input() if answer == "high": upper = guess elif answer == "low": lower = guess else: print("I made it!!! The number is", guess)
Posted Mar 15, 2019, 11:03 AM by Attila Lengyel
• Scrambled words: the rset can be a toatl mses and you can sitll raed it wouthit porbelm  import randomdef randomize(word): if len(word) < 3: return word chars = [] for i in word: #this stores every characters in a list chars.append(i) result =[] result.append(chars[0]) # stores the first character del chars[0] #deletes from the list result.append(chars[len(chars)-1]) # stores the last character del chars[len(chars)-1] #delets the last character while len(chars) != 0: r = random.randint(0,len(chars)-1) result.insert(1, chars[r]) #inserts into the second position del chars[r] randomword = "" for i in result: #appends the random list of characters randomword += i return randomword #returns randomwordtext = "the rest can be a total mess and you can still read it without problem"sentance = ""for i in text.split(" "): sentance += randomize(i) + " " print(sentance)
Posted Feb 15, 2019, 8:05 AM by Attila Lengyel
• Lesson 12: Rolling the dice  import random as rprint(r.randint(1,6))rolls = []for i in range(0, 10000): rolls.append(r.randint(1,6))print(rolls)for i in range(1,7): print(i,rolls.count(i))#This is to list all the possible combinations of rolling 2 dicefor i in range(1,7): for j in range(1,7): print(i,j, i + j)rolls.clear()#Roll the two dice 10,000 times and store in rolls listprint("Rolling two dice")for i in range(0,78099): a = r.randint(1,6) b = r.randint(1,6) rolls.append(a + b)for i in range(2,13): print(i, rolls.count(i), rolls.count(i) / len(rolls))
Posted Feb 1, 2019, 7:57 AM by Attila Lengyel
• Lesson 11: Bubble sort  names = ["Attila"]name = ""while name != "exit": name = input("Give me a name:") if name == "exit": continue if name in names: print("You already have this name!") continue for i in range(0, len(names)): if name < names[i]: names.insert(i, name) break if i == len(names) - 1: names.append(name) print(names)
Posted Jan 25, 2019, 8:05 AM by Attila Lengyel
• Lesson 10: Lists  names = ["Kayden"]names.append("Soham")names.append("Jerry")names.append("Kian")names.append("Mahin")names.append("Anshay")names.append("Karthik")names.append("William")names.append("Sumedh")names.append("Yahia")print(names)for name in names: print("Hello", name, "!!!")print("There are", len(names) - 1, "students in the class!")print(names[0])names.insert(2, "Attila")print(names)if "Mahin" in names: print(names.index("Mahin")) print(names[names.index("Mahin")])names.sort()print(names)names.sort(reverse=True)print(names)import random, timeprint(.9**20)length = len(names)for i in range(length): select = random.randint(0, len(names)-1) print(names[select], "stand up!!!") names.remove(names[select]) time.sleep(3)
Posted Jan 18, 2019, 8:03 AM by Attila Lengyel
• Lesson 9: Fibonacci series and more  a = 0b = 1c = 1print(a)print(b)print(c)for i in range(0,100): d = a + b + c print(d) a = b b = c c = d
Posted Jan 11, 2019, 7:58 AM by Attila Lengyel
• Lesson 8: 4 corners game and "What year were you born"? - Strings & Dates  import time, random, datetimefor j in range(0,0): for i in range(1,11): print(i) time.sleep(1) corner = random.randint(1,4) print("If you are in corner", corner, "you are out")today = str(datetime.date.today())year = int(today[0] + today[1] + today[2] + today[3])month = today[5] + today[6]day = today[8] + today[9]today = month + "/" + dayanswer = input("Were you born before or on " + today + "?: ")age = int(input("How old are you?: "))if answer == "yes": print("You were born in", year - age)else: print("You were born in", year - age - 1)
Posted Dec 21, 2018, 8:00 AM by Attila Lengyel
Posted Dec 14, 2018, 8:01 AM by Attila Lengyel
• Lesson 6: Head or tail?  import randomprint("Let's practice!")wins = 0losses = 0for i in range(0,5): coin = random.randint(0,1) side = "Head" if coin == 1: side = "Tail" guess = input("Head or Tail?").upper() if side.upper() == guess: print(side, "Ouch... :-( ... you won! ") wins = wins + 1 else: print(side, "Hurray... I won, you lost!!!") losses = losses + 1print("Wins:", wins, "Lost rounds:", losses)if wins > losses: print("Congrat! You won the game.")elif wins == losses: print("It's a tie!")else: print("Looser!!!")
Posted Dec 7, 2018, 7:59 AM by Attila Lengyel
• Lesson 5: Multiplication test with for loop  print("Let's practice! What is 4 x 9?")answer = int(input())print("Your answer is", answer)if answer == 36: print("Correct!")else: print("Incorrect. Please practice math!")import randomprint("Are you ready for a test?")for i in range(1,11): a = random.randint(2,9) b = random.randint(2,9) print("Question", i,": What is", a, "x", b, "?") answer = int(input()) if answer == a * b: print("Correct!") else: print("Incorrect! The answer is", a * b)
Posted Nov 30, 2018, 7:54 AM by Attila Lengyel
• Lesson 4: Control Flow  print("Control flow")a = int(input("Give me a number:"))if a < 10: print("The number is smaller then 10") print("This is block 1")elif a == 10: print("The number is 10") print("This is block 2")else: print("The number is greater then 10") print("This is block 3")print ("This is the main flow")b = int(input("Give me a second number:"))op = input("Give me an operation:")if op == "+": print(a, "+", b, "=", a+b)elif op == "-": print(a, "-", b, "=", a-b)elif op == "*": print(a, "*", b, "=", a*b)elif op == "/": print(a, "/", b, "=", a/b)
Posted Nov 16, 2018, 8:01 AM by Attila Lengyel
• 2018-19 Lesson 3: Strings, Integers and Float  print("Hello World!!!")first_name = input("What is your name?")print("Hello", first_name, "How are you?")first_name = "Test"print("Hello", first_name, "How are you?")print("I can do math!")a = int(input("Give me a number:"))b = int(input("Give me a second number:"))print("The sum is", a + b)print("The difference is", a - b)print("The product is", a * b)print("The quotient is", a / b)print("a on the power of b", a ** b)a = a / bprint(a)import mathc = float(input("Give me c:"))d = float(input("Give me d:"))print("The sum is", c + d)print("The difference is", c - d)print("The product is", c * d)print("The quotient is", c / d)print("a on the power of b", c ** d)print("Square root of c", math.sqrt(c))print("Square root of d", math.sqrt(d))
Posted Nov 9, 2018, 7:58 AM by Attila Lengyel
• 2018-19 Lesson 2: Cooking eggs  print("Let's fry eggs!")num_peo = input("How many people will you serve?")print("Really?", int(num_peo), "people?")eggs_per = input("How many eggs per person?")total_eggs = int(num_peo) * int(eggs_per)print("Get", total_eggs, "eggs from the fridge!")
Posted Nov 7, 2018, 8:05 AM by Attila Lengyel
• Lesson 26: Riddle  riddle = "hVObYomcioTcfoZSOfbWbUodfcUfOaaWbU"abc = "abcdefghijklmnopqrstuvwxyz !@#\$%^&*()_+:?> length - 1: y = y % length  return abc[y]def crypt(text, password, x):  key = getkey(password)  encryptedtext = ""  for c in text:    encryptedtext += shift(c, x * key)  return encryptedtext  def crack(text, num, x):  encryptedtext = ""  for c in text:    encryptedtext += shift(c, x * num)  return encryptedtext  text = input("Give me a text:")password = input("Give me a password:")secretmsg = crypt(text,password, 1)print(secretmsg)print(crypt(secretmsg, password, -1))riddle = input("Give me a text to crack:")for x in range(0, len(abc)):  input()  print(str(x) + ": " + crack(riddle, x, 1))
Posted May 17, 2018, 8:03 AM by Attila Lengyel
• Lesson 25: Simple encryption  abc = "abcdefghijklmnopqrstuvwxyz !@#\$%^&*()_+:?> length - 1: y = y % length  return abc[y]def crypt(text, password, x):  key = getkey(password)  encryptedtext = ""  for c in text:    encryptedtext += shift(c, x * key)  return encryptedtext  text = input("Give me a text:")password = input("Give me a password:")secretmsg = crypt(text,password, 1)print(secretmsg)print(crypt(secretmsg, password, -1))
Posted May 11, 2018, 8:00 AM by Attila Lengyel
• Lesson 24: Morse code  import morsedict as mtext = input("Give me a text:")morsecode = ""for c in text:  morsecode += m.morsetab[c] + " "  print(morsecode)morsetab2 = {}for key,val in m.morsetab.items():  morsetab2[val] = keymorsecode = input("Give me morse:") t = ""for c in morsecode:  if c == " ":    print(morsetab2[t])    t=""  else:    t += c
Posted May 3, 2018, 8:03 AM by Attila Lengyel
• Lesson 23: Playing with timers  from datetime import datetimeimport time, mathfor x in range(0,3):  print(datetime.now())  time.sleep(1)def sectimer(seconds):  secperday = 60 * 60 * 24  days = math.floor(seconds / secperday)  seconds = seconds - days * secperday  secperhour = 60 * 60  hours = math.floor(seconds / secperhour)  seconds = seconds - hours * secperhour  secpermin = 60  minutes = math.floor(seconds / secpermin)  seconds = seconds - minutes * secpermin    strtime = ""  if days < 10: strtime += "0"  strtime += str(days) + ":"  if hours < 10: strtime += "0"  strtime += str(hours) + ":"  if minutes < 10: strtime += "0"  strtime += str(minutes) + ":"  if seconds < 10: strtime += "0"  strtime += str(seconds)    return strtime  start = datetime.now()counter = 0for x in range(0, 30):  print(sectimer(counter))  time.sleep(1)  counter += 1end = datetime.now()print (end - start)
Posted Apr 19, 2018, 8:02 AM by Attila Lengyel
• Lesson 22: Working with dates and converter between Fahrenheit and Celsius  from datetime import datetimenow = datetime.now()print(now)mm = str(now.month)print(mm)dd = str(now.day)print(mm + "/" + dd)yyyy = str(now.year)print(mm + "/" + dd + "/" + yyyy)hour = str(now.hour)print(mm + "/" + dd + "/" + yyyy + " " + hour)mi = str(now.minute)print(mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi)ss = str(now.second)print(mm + "/" + dd + "/" + yyyy + " " + hour + ":" + mi + ":" + ss)import geocoderg = geocoder.ip('me')print(g.latlng)Celsius = float(input("Celsius:"))Fahrenheit = 9/5 * Celsius + 32print(Fahrenheit, "Fahrenheit")Fahrenheit = float(input("Fahrenheit:"))Celsius = (Fahrenheit - 32)*5/9print(Celsius, "C")
Posted Apr 12, 2018, 8:00 AM by Attila Lengyel
• Lesson 21: (Combined with Bronze) Random numbers  import random, timedef wait():  for x in range(0,9):    print("...")    time.sleep(1 - x * 0.1)v = input("Head or Tail?:")print("You guessed", v, "!")r = random.randint(0,100)coin = ""if r < 50:  coin = "Tail"else:  coin = "Head"wait()if v == coin:  print("It is", coin ,"You won!!!")else:  print("It is", coin ,"You lost...")  for x in range(0, 100):  print(random.randint(1,6))
Posted Mar 29, 2018, 8:00 AM by Attila Lengyel
• Lesson 20: Revisiting basics  word = input("Give me a word:")for w in word:  print(w)  while(input("How are you doing?").lower()=="good"):  print("Really?")print("I'm doing GOOOOD too")tree=""for l in range(0,3):  for x in range(0,6):    for y in range(0,11):      if y > 6 - x and y < 6 + x:         tree += "*"      else:        tree += " "    print(tree)      tree = ""
Posted Mar 22, 2018, 8:04 AM by Attila Lengyel
• Lesson 19 - How accurate our Hangman algorithm is?  import word_dict, randomdef drawhangman(missedGuesses):  if missedGuesses <= 0: return  print("     _____________")  if missedGuesses > 1:    print("      |          |")  else: print("      |")  if missedGuesses > 2:    print("      |          O")  else: print("      |")  if missedGuesses > 3:    print("      |         /|\\")  else: print("      |")  if missedGuesses > 4:    print("      |          |")  else: print("      |")  if missedGuesses > 5 :    print("      |         / \\")  else: print("      |")  print("      |")  print("      |")  print("      |_____________")  def lengthwords(searchspace, length):  returnspace = []  for w in searchspace:    if len(w) == length:      returnspace.append(w.lower())        return returnspacedef match(searchspace, pattern):  returnspace = []  for w in searchspace:    add = True    for x in range(0, len(w)):      if pattern[x] != "_" and w[x] != pattern[x]:          add = False          break    if add:      returnspace.append(w)  return returnspacedef eliminatemissed(searchspace, missedletters):  returnspace = []  for w in searchspace:    add = True    for l in w:      if missedletters.find(l) != -1:        add = False        break    if add:      returnspace.append(w)  return returnspacedef stat(searchspace, pattern):  abc = "abcdefghijklmnopqrstuvwxyz"  lstat = {}  for c in abc:    lstat[c] = 0  for w in searchspace:    letters = ""    for c in w:      if letters.find(c) == -1:        letters += c    for c in letters:      lstat[c] += 1  count = 0  letter = ""  for c in abc:    if pattern.find(c) == -1:      if lstat[c] > count:        count = lstat[c]        letter = c  return letterdef guess(wordlength, pattern, eliminatedletters):  space = lengthwords(word_dict.db, wordlength)  space = match(space, pattern)  space = eliminatemissed(space, eliminatedletters)  lstat = stat(space, pattern)  return lstatdef play(word, draw):    good_letters = ""  eliminated_letters =""  word_dash = ""  for x in range(0, len(word)):    word_dash += "_ "  if draw: print (word_dash)    missed_guesses = 0    while missed_guesses < 7 and word_dash.find("_") != -1:    automatedguess = guess(len(word), word_dash.replace(' ',''), eliminated_letters)    if draw: print("Let me guess:", automatedguess)    if len(automatedguess) == 0: missed_guesses += 1    if word.find(automatedguess) > -1:      if draw: print("Correct guess!")      good_letters += automatedguess    else:      eliminated_letters += automatedguess      if draw: print("Wrong guess!")      missed_guesses = missed_guesses + 1      if draw: drawhangman(missed_guesses)    word_dash = ""    for x in range(0, len(word)):      if good_letters.find(word[x]) > -1:        word_dash += word[x] + " "      else:        word_dash += "_ "    if draw: print(word_dash)  if draw: print("The word is", word)  return missed_guesses#This is the main programspace = lengthwords(word_dict.db, 9)totalgames = 0lostgames = 0for w in space:  totalgames += 1  guesses = play(w, False)   if guesses == 7: lostgames += 1  print(w, guesses)print(totalgames, lostgames)size = len(word_dict.db)print("Let's play Hangman")question = input("Do you want to pick a word? (yes/no):")if question == "yes":  word = input("Give me a word:")  play(word, True)else:  wordindex = random.randint(0, size)  randomword = word_dict.db[wordindex]  randomword = randomword.lower()  play(randomword, True)
Posted Mar 15, 2018, 8:04 AM by Attila Lengyel
• Lesson 18 - Hangman computer player  import word_dict, randomdef drawhangman(missedGuesses):  if missedGuesses <= 0: return  print("     _____________")  if missedGuesses > 1:    print("      |          |")  else: print("      |")  if missedGuesses > 2:    print("      |          O")  else: print("      |")  if missedGuesses > 3:    print("      |         /|\\")  else: print("      |")  if missedGuesses > 4:    print("      |          |")  else: print("      |")  if missedGuesses > 5 :    print("      |         / \\")  else: print("      |")  print("      |")  print("      |")  print("      |_____________")  def lengthwords(searchspace, length):  returnspace = []  for w in searchspace:    if len(w) == length:      returnspace.append(w.lower())        return returnspacedef match(searchspace, pattern):  returnspace = []  for w in searchspace:    add = True    for x in range(0, len(w)):      if pattern[x] != "_" and w[x] != pattern[x]:          add = False          break    if add:      returnspace.append(w)  return returnspacedef eliminatemissed(searchspace, missedletters):  returnspace = []  for w in searchspace:    add = True    for l in w:      if missedletters.find(l) != -1:        add = False        break    if add:      returnspace.append(w)  return returnspacedef stat(searchspace, pattern):  abc = "abcdefghijklmnopqrstuvwxyz"  lstat = {}  for c in abc:    lstat[c] = 0  for w in searchspace:    letters = ""    for c in w:      if letters.find(c) == -1:        letters += c    for c in letters:      lstat[c] += 1  count = 0  letter = ""  for c in abc:    if pattern.find(c) == -1:      if lstat[c] > count:        count = lstat[c]        letter = c  return letterdef guess(wordlength, pattern, eliminatedletters):  space = lengthwords(word_dict.db, wordlength)  space = match(space, pattern)  space = eliminatemissed(space, eliminatedletters)  lstat = stat(space, pattern)  return lstatdef play(word):    good_letters = ""  eliminated_letters =""  word_dash = ""  for x in range(0, len(word)):    word_dash += "_ "  print (word_dash)    missed_guesses = 0    while missed_guesses < 7 and word_dash.find("_") != -1:    automatedguess = guess(len(word), word_dash.replace(' ',''), eliminated_letters)    print("Let me guess:", automatedguess)    if word.find(automatedguess) > -1:      print("Correct guess!")      good_letters += automatedguess    else:      eliminated_letters += automatedguess      print("Wrong guess!")      missed_guesses = missed_guesses + 1      drawhangman(missed_guesses)    word_dash = ""    for x in range(0, len(word)):      if good_letters.find(word[x]) > -1:        word_dash += word[x] + " "      else:        word_dash += "_ "    print(word_dash)    print("The word is", word)#This is the main programsize = len(word_dict.db)print("Let's play Hangman")wordindex = random.randint(0, size)randomword = word_dict.db[wordindex]randomword = randomword.lower()play(randomword)
Posted Mar 8, 2018, 10:03 AM by Attila Lengyel
• Lesson 16: Automated letter guess  import word_dictdef wordlength(searchspace, length):  space = []  for w in searchspace:    if len(w) == length:      space.append(w)  return spacedef patternmatch(searchspace, pattern):  space = []  for w in searchspace:    add = True    for x in range(0, len(w)):      if pattern[x] != "_" and pattern[x] != w[x]:        add = False        break    if add: space.append(w)  return spacedef eliminatemissed(searchspace, missedletters):  space = []  for w in searchspace:    add = True    for l in w:      if missedletters.find(l) > -1:        add = False        break    if add: space.append(w)  return spacedef letterstat(searchspace):  abc = "abcdefghijklmnopqrstuvwxyz"  lstat = {}  for l in abc:    lstat[l] = 0  for w in searchspace:    letters = ""    w = w.lower()    for l in w:      if letters.find(l) == -1:        letters += l    for l in letters:      lstat[l] += 1        return lstat  space = wordlength(word_dict.db, 4)space = patternmatch(space, "_ee_")space = eliminatemissed(space,"ns")print (space)space = letterstat(space)print (space)
Posted Feb 15, 2018, 8:03 AM by Attila Lengyel
• Lesson 15: Finding words with a pattern  import word_dictdef wordlength(x):  searchspace = []  for w in word_dict.db:    if len(w) == x:      searchspace.append(w)  return searchspacedef lengthstat(searchspace):  maxlength = 0  for w in searchspace:     if len(w) > maxlength:      maxlength = len(w)  lstat = {}  for x in range(0,maxlength + 1):    lstat[x] = 0  for w in searchspace:    lstat[len(w)] += 1  return lstat  def letterstat(searchspace):  abc = "abcdefghijklmnopqrstuvwxyz"  lstat = {}  for l in abc:    lstat[l] = 0  for w in searchspace:    letters = ""    w = w.lower()    for l in w:      if letters.find(l) == -1:        letters += l    for l in letters:      lstat[l] += 1        return lstatdef match(searchspace, pattern):  space = []  for w in searchspace:    addword = True    for x in range(0, len(w)):      if pattern[x] != "_":        if pattern[x] != w[x]:          addword = False          break    if addword:       space.append(w)        return space  space = wordlength(4)space = match(space, "j__l")print(space)lstat = letterstat(space)for l in "abcdefghijklmnopqrstuvwxyz":  if lstat[l] != 0: print(l, "=", lstat[l])
Posted Feb 8, 2018, 8:05 AM by Attila Lengyel
• Lesson 14: Hashmaps  import word_dictdef wordlength(x):  searchspace = []  for w in word_dict.db:    if len(w) == x:      searchspace.append(w)  return searchspacedef lengthstat(searchspace):  maxlength = 0  for w in searchspace:     if len(w) > maxlength:      maxlength = len(w)  lstat = {}  for x in range(0,maxlength + 1):    lstat[x] = 0  for w in searchspace:    lstat[len(w)] += 1  return lstat  def letterstat(searchspace):  abc = "abcdefghijklmnopqrstuvwxyz"  lstat = {}  for l in abc:    lstat[l] = 0  for w in searchspace:    w = w.lower()    for l in w:      lstat[l] += 1  return lstatspace = wordlength (16)print(space)print(lengthstat(word_dict.db))lstat = letterstat(word_dict.db)for l in "abcdefghijklmnopqrstuvwxyz":  print(l, "=", lstat[l])
Posted Feb 1, 2018, 8:02 AM by Attila Lengyel
• Lesson 13: Hangman revised post class  #main.pyimport hangmanprint("Let's play Hangman")word = hangman.getWord()good_letters = ""missed_letters = ""missedGuess = 0word_dash = hangman.getDashedWord(word, good_letters)safe = Falsehanged = Falsewhile safe == False and hanged == False:  searchspace = hangman.wordLength(len(word))  searchspace = hangman.eliminateMissed(searchspace, missed_letters)  print(searchspace)  print(len(searchspace))  print(word_dash)  guess = input("Guess a letter:")  if word.find(guess) > -1 and good_letters.find(guess) == -1:    print("Correct guess!")    good_letters += guess    word_dash = hangman.getDashedWord(word, good_letters)    if word_dash.find("_") == -1:      safe = True  else:    print("Wrong guess!")    missedGuess += 1    if missed_letters.find(guess) == -1:      missed_letters += guess    hanged = hangman.drawHangman(missedGuess)  print("The correct word is ", word)if hanged:  print("Sorry you are hanged...")else:  print("You are safe!!!")#hangman.py please download the file from #https://sites.google.com/site/primaryprogrammers/files/hangman.py?attredirects=0&d=1import randomdef wordLength(length):  searchspace = []  for w in db:    if len(w) == length:      searchspace.append(w)  return searchspacedef eliminateMissed(words, missed_letters):  searchspace = []  for w in words:    add = True    for y in missed_letters:      if w.find(y) != -1:        add = False    if add:      searchspace.append(w)  return searchspacedef getWord():  select = random.randint(0,len(db))  return db[select]def getDashedWord(word, good_letters):  word_dash = ""  for x in range(0, len(word)):    if good_letters.find(word[x]) > -1:      word_dash += word[x] + " "    else:      word_dash += "_ "  return word_dash  def drawHangman(missedGuesses):  if missedGuesses <= 0: return  print("     _____________")  if missedGuesses > 1:    print("      |          |")  else: print("      |")  if missedGuesses > 2:    print("      |          O")  else: print("      |")  if missedGuesses > 3:    print("      |         /|\\")  else: print("      |")  if missedGuesses > 4:    print("      |          |")  else: print("      |")  if missedGuesses > 5 :    print("      |         / \\")  else: print("      |")  print("      |")  print("      |")  print("      |_____________")  return bool(missedGuesses > 6)
Posted Jan 25, 2018, 3:27 PM by Attila Lengyel
• Lesson 13: Hangman searchspace  import word_dictimport randomdef drawHangman(missedGuess):    if missedGuess > 0:        print("       _________")    else:        print("")    if missedGuess > 1:        print("       |        |")    else:         print("       |        ")    if missedGuess > 2:        print("       |        0")    else:         print("       |        ")    if missedGuess > 3:        print("       |       /|\\")        else:         print("       |        ")    if missedGuess > 4:        print("       |        |")    else:         print("       |        ")            if missedGuess > 5:        print("       |       / \\")    else:         print("       |        ")        print("       _________")    print("")    if missedGuess > 6:        return True    else:        return Falsedef wordlength(length):  searchspace = []  for w in word_dict.db:    if len(w) == length:      searchspace.append(w)  return searchspacedef eliminateMissed(searchspace, missed_letters):  searchspace2 = []  for w in searchspace:    add = True    for y in missed_letters:      if w.find(y) != -1:        add = False    if add:      searchspace2.append(w)  print(searchspace2)  print(len(searchspace2))  return searchspace2  eliminateMissed(wordlength(4), "aeiurso")print("Let's play Hangman")select = random.randint(0,len(word_dict.db))word = word_dict.db[select]word_dash = ""for x in range(0, len(word)):  word_dash += "_ "  print (word_dash)cont = Truelost = Falsegood_letters = ""missed_letters = ""missedGuess = 0  while cont:  guess = input("Guess a letter:")    if word.find(guess) > -1 and good_letters.find(guess) == -1:    print("Correct guess!")    good_letters += guess  else:    print("Wrong guess!")    missedGuess += 1    missed_letters += guess    lost = drawHangman(missedGuess)            cont = False    word_dash = ""  for x in range(0, len(word)):    if good_letters.find(word[x]) > -1:      word_dash += word[x] + " "    else:      word_dash += "_ "      cont = True  if lost:    cont = False  print(word_dash)  print("The correct word is ", word)if lost:  print("Sorry you are hanged...")else:  print("You are safe!!!")
Posted Jan 25, 2018, 8:03 AM by Attila Lengyel
• Lesson 11 b: Hangman v2  import word_dictimport randomdef drawHangman(missedGuess):    if missedGuess > 0:        print("       _________")    else:        print("")    if missedGuess > 1:        print("       |        |")    else:         print("       |        ")    if missedGuess > 2:        print("       |        0")    else:         print("       |        ")    if missedGuess > 3:        print("       |       /|\\")        else:         print("       |        ")    if missedGuess > 4:        print("       |        |")    else:         print("       |        ")            if missedGuess > 5:        print("       |       / \\")    else:         print("       |        ")        print("       _________")    print("")    if missedGuess > 6:        return True    else:        return Falseprint("Let's play Hangman")select = random.randint(0,len(word_dict.db))word = word_dict.db[select]word_dash = ""for x in range(0, len(word)):  word_dash += "_ "  print (word_dash)cont = Truelost = Falsegood_letters = ""missedGuess = 0  while cont:  guess = input("Guess a letter:")    if word.find(guess) > -1 and good_letters.find(guess) == -1:    print("Correct guess!")    good_letters += guess  else:    print("Wrong guess!")    missedGuess += 1    lost = drawHangman(missedGuess)        cont = False    word_dash = ""  for x in range(0, len(word)):    if good_letters.find(word[x]) > -1:      word_dash += word[x] + " "    else:      word_dash += "_ "      cont = True  if lost:    cont = False  print(word_dash)  print("The correct word is ", word)if lost:  print("Sorry you are hanged...")else:  print("You are safe!!!")
Posted Jan 11, 2018, 8:00 AM by Attila Lengyel
• Lesson 11 a : Functions  def listup(word):  for x in word:    print(x)    word3 = input("Give me a word:")listup(word3)word2 = input("Give me a word:")listup(word2)listup(word2)
Posted Jan 11, 2018, 7:28 AM by Attila Lengyel
• Lesson 10: Hangman & Data mining...  import word_dictimport randomanalytics = []count = []count.append(0)count.append(0)for x in range(0, len(word_dict.db)):  for y in word_dict.db[x]:    if (y == 'a'):      count[0] += 1    if (y == 'e'):      count[1] += 1print(count)print("Let's play Hangman")select = random.randint(0,len(word_dict.db))word = word_dict.db[select]word_dash = ""for x in range(0, len(word)):  word_dash += "_ "  print (word_dash)cont = Truegood_letters = ""  while cont:  guess = input("Guess a letter:")    if word.find(guess) > -1:    print("Correct guess!")    good_letters += guess  else:    print("Wrong guess!")    cont = False    word_dash = ""  for x in range(0, len(word)):    if good_letters.find(word[x]) > -1:      word_dash += word[x] + " "    else:      word_dash += "_ "      cont = True    print(word_dash)
Posted Dec 21, 2017, 7:58 AM by Attila Lengyel
• Lesson 9: Rock-Paper-Scissors  import timeimport randomprint("Let's play Rock-Paper-Scissors")time.sleep(3)print("Ready???")time.sleep(1) print("Rock")time.sleep(1) print("Paper")time.sleep(1)print("Scissor")choices = ["Rock", "Paper", "Scissors"]selection = random.randint(0,2)print(choices[selection])user = input("What is your choice?:")if choices[selection] == user:  print("Draw")elif (choices[selection] == "Rock" and user == "Paper") or (choices[selection] == "Scissor" and user == "Rock") or (choices[selection] == "Paper" and user == "Scissor"):  print ("You won!!!")else:  print("You lost!!!")
Posted Dec 14, 2017, 8:05 AM by Attila Lengyel
• Lesson 8: While loop and binary search  import random lowerlimit = 0upperlimit = random.randint(5,10)print("Think a number between 0 and", upperlimit)answer = "no"while answer != "yes":  number = (lowerlimit + upperlimit) / 2  number = round(number,0)    print("Is the number", number, "? Or it is greater/less?")  answer = input()    if answer == "greater":    lowerlimit = number  if answer == "less":    upperlimit = number      if answer == "yes":    print("I did it!!!")
Posted Dec 7, 2017, 8:02 AM by Attila Lengyel
• Lesson 7: Fibonacci sequence  fibonacci = []fibonacci.append(0)fibonacci.append(1)print("Fibonacci sequence:", fibonacci)print("Length:", len(fibonacci))fibonacci.append(fibonacci[0] + fibonacci[1])print("Fibonacci sequence:", fibonacci)print("Length:", len(fibonacci))for x in range (0,100):  length = len(fibonacci)  new = fibonacci[length - 1] + fibonacci[length - 2]  fibonacci.append(new)print("Fibonacci sequence:", fibonacci)print("Length:", len(fibonacci))
Posted Nov 30, 2017, 8:00 AM by Attila Lengyel
• Lesson 6: Multiplication timed test  import randomimport timecorrectanswer = 0totalanswer = 0start = time.time()for x in range(0,10):  totalanswer += 1  a = random.randint(0,12)  b = random.randint(0,12)    print("What is ",a,"by",b,"is equal to?:")  answer = input()    if a * b == int(answer):    print("Correct!!!")    correctanswer += 1  else:    print("You missed it!!!")    print("Your score is", (correctanswer / totalanswer)*100)end = time.time()print("It took you", end - start, "seconds")
Posted Nov 9, 2017, 7:58 AM by Attila Lengyel
• Lesson 5: Listing up all prime numbers using for loop  ------------------------------------------------------------------------------------------------Developed version in class------------------------------------------------------------------------------------------------total = 0for x in range(2,100):  prime = True  for y in range(2,x):    if x % y == 0:      prime = False  if prime == True:    print (x, "is a prime number")    total = total + 1    print("There are", total, "number of prime number")------------------------------------------------------------------------------------------------Optimized version post-class ------------------------------------------------------------------------------------------------total = 0iterations = 0upper = 100000primelist = []for x in range(2,upper):  prime = True  for y in primelist:    iterations += 1    if x % y == 0:      prime = False      break  if prime == True:    total += 1    primelist.append(x)    print("There are", total, "prime numbers till", upper)print("I've have found them in ", iterations, "interatitons")print("They are ", primelist)
Posted Nov 2, 2017, 10:47 AM by Attila Lengyel
Posted Oct 26, 2017, 7:58 AM by Attila Lengyel
• Lesson 3: Control flow using if... elif...else...  import matha = input("Give me a number:")sign = input("Give me a sign:")b = input("Give me another number:")result = 0if sign == "+":  result = int(a) + int(b)  print("You asked for the sum")  print(a,"plus", b, "is", result)elif sign == "-":  result = int(a) - int(b)  print("You asked for the difference")  print(a,"minus", b, "is", result)elif sign == "*":  result = int(a) * int(b)  print("You asked for the product")  print(a,"multilpied by", b, "is", result)elif sign == "/":  result = int(a) / int(b)  print("You asked for the quotient")  print(a,"divided by", b, "is", result)elif sign == "power":  result = math.pow(int(a),int(b))  print("You asked for the power")  print(a,"on the power of", b, "is", result)else:  print("Sorry, I don't know that sign!")
Posted Oct 19, 2017, 8:01 AM by Attila Lengyel
• Lesson 2: Variables 1.0  a = input("Give me a number:")print("a is", a)b = input("Give me an other:")print("b is", b)c = int(a) + int(b)print("The sum is ", c)
Posted Oct 12, 2017, 8:43 AM by Attila Lengyel
• Lesson 1 - Hello World!  print("Hello World")message = "Hello World"print(message)message = message + " today"print(message)message = input("How are you doing?")print (message)
Posted Oct 5, 2017, 7:54 AM by Attila Lengyel
• Week 24 - Prime numbers  def prime(number):  if number > 1:    for x in range(2,number):      if (number % x) == 0:        return False    else:      return Truesum = 0for x in range(1, 10000):  if prime(x):    sum += xprint (sum)for x in range(700,799):  if prime(x):    sX = str(x)    prod = int(sX[0]) * int(sX[1]) * int(sX[2])    print(sX, prod)
Posted Jun 2, 2017, 1:14 PM by Attila Lengyel
• Week 23 - Modulo  n = 0a = int(input("Lower:"))b = int(input("Upper:"))for x in range(a,b):  if x%7 == 0 or x%3 == 0 or x%13 == 0:    n += 1print(n)text = input("Text:")print(text.count('a') + text.count('A'))
Posted Jun 2, 2017, 1:14 PM by Attila Lengyel
• Week 22 - Working with time  import timeprint(time.localtime(time.time()))print(time.localtime(0))print(time.asctime(time.localtime(time.time())))print(time.asctime(time.localtime(0)))print(time.tzname)start = time.time()string = input("Write something:")end = time.time()print(end - start)for x in range(1,11):  print(x)  time.sleep(1)
Posted May 12, 2017, 8:03 AM by Attila Lengyel
• Week 21 - Calculating average, min and max  iCount = int(input("How many numbers?:"))iSum = 0iMin = 0iMax = 0lNumbers = []for x in range(0, iCount):  iNum = int(input("Give me a number:"))  lNumbers.append(iNum)  if x == 0:    iMin = iNum    iMax = iNum  else:    if iNum < iMin: iMin = iNum    if iNum > iMax: iMax = iNum  iSum += iNumlNumbers.sort()print(lNumbers)print("The average is", iSum/iCount)print("The minimum: ", iMin)print("The maximum: ", iMax)
Posted May 5, 2017, 7:56 AM by Attila Lengyel
• Week 20 Tic-tac-toe v1.0  import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return False############## Get computer mark ############def opponent(sUser):  if sUser == "O":    return "X"  return "O"############## Strategy to move random ############def randommove(board, sUser):  emptystep = []  for x in range(0,9):    if board[x] == " ":      emptystep.append(x)    move = random.randint(0,len(emptystep)-1)  move = emptystep[move]  return move############## Strategy to win or block ############def nextMoveWin(board, sUser):  for x in range(0,9):    if board[x] == " ":      board[x] = sUser      isWin = win(board, sUser)      board[x] = " "      if isWin:        return x  return -1    ############## Move center ##################def moveCenter(board):  if board[4] == " ":    return 4  return -1############## Move Corner ##################def moveCorner(board):  if board[1] == " " and board[3] == " " and board[0] == " ":    return 0  if board[1] == " " and board[5] == " " and board[2] == " ":    return 2  if board[5] == " " and board[7] == " " and board[8] == " ":    return 8  if board[3] == " " and board[7] == " " and board[6] == " ":    return 6    if board[0] == " ":    return 0      if board[2] == " ":    return 2  if board[6] == " ":    return 6  if board[8] == " ":    return 8  return -1############## Check for tie ##################def checktie(board):  isTie = True  for x in range(0,9):    if board[x] == " ":      isTie = False    return isTie############## Head or Tail ######################def headtail():  bet = input("Head or Tail:")  flip = random.randint(0,1)  if flip == 0:    coin = "Head"  else:    coin = "Tail"    if bet == coin:    return True    return False############## User move ##################def usermove(board, user):  move = input("Make your move (1~9):")  if board[int(move) - 1] != " ":    print("You lost your move!!!")  else:    board[int(move) - 1] = user    drawBoard(board)    if win(board, user):    print("The user ", user, "won!!!")    return True    if checktie(board):    print("It is a tie")    return True      return False  ############## 2 ways block ##################def twowaysblock(steps, board, user):  empty = 0  x = 0  o = 0    for i in steps:    if board[i] == ' ': empty += 1    if board[i] == 'X': x += 1    if board[i] == 'O': o += 1      if user == 'X' and empty == 3 and x == 2:    for i in steps:      if board[i] == ' ':        return i    if user == 'O' and empty == 3 and o == 2:    for i in steps:      if board[i] == ' ':        return i    return -1  ############## Scanning for 2 ways ############def scan2ways(board, user):  steps = [0,2,8,1,5]  move = twowaysblock(steps, board, user)  if move != -1: return move    steps = [2,8,6,5,7]  move = twowaysblock(steps, board, user)  if move != -1: return move    steps = [8,6,0,7,3]  move = twowaysblock(steps, board, user)  if move != -1: return move  steps = [6,0,2,3,1]  move = twowaysblock(steps, board, user)  if move != -1: return move  return -1  ############## Computer move ##################def computermove(board, user):    movetype = ""    move = nextMoveWin(board, opponent(user))  if move == -1:    move = nextMoveWin(board, user)  else:    if movetype == "": movetype = "Computer moves to win!"    if move == -1:    move = scan2ways(board, user)  else:    if movetype == "": movetype = "Computer moves to win!"  if move == -1:    move = moveCenter(board)  else:    if movetype == "": movetype = "Computer blocks your win!"  if move == -1:    move = moveCorner(board)  else:    if movetype == "": movetype = "Computer moves center!"  if move == -1:    move = randommove(board,opponent(user))  else:    if movetype == "": movetype = "Computer moves corner!"  if movetype == "": movetype = "Computer moves random!"  print(movetype)  board[move] = opponent(user)  print("Computer moves", move + 1)    drawBoard(board)    if win(board, opponent(user)):    print("The computer", opponent(user), "won!!!")    return True    if checktie(board):    print("It is a tie!")    return True    return False################## Main Program ##################tttBoard = [" "] * 9drawBoard(tttBoard)#if headtail():#  print("You won, you will be X")user = "X"#else:#  print("You lost, you will be O")# user = "O"#print("The computer is", opponent(user))while(True):    if user == "X":    if usermove(tttBoard, user):break    if computermove(tttBoard, user): break  else:    if computermove(tttBoard, user):break    if usermove(tttBoard, user):break
Posted Apr 12, 2017, 4:40 PM by Attila Lengyel
• Week 19  import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return False############## Get computer mark ############def opponent(sUser):  if sUser == "O":    return "X"  return "O"############## Strategy to move random ############def randommove(board, sUser):  emptystep = []  for x in range(0,9):    if board[x] == " ":      emptystep.append(x)    move = random.randint(0,len(emptystep)-1)  move = emptystep[move]  return move############## Strategy to win or block ############def nextMoveWin(board, sUser):  for x in range(0,9):    if board[x] == " ":      board[x] = sUser      isWin = win(board, sUser)      board[x] = " "      if isWin:        return x  return -1    ############## Move center ##################def moveCenter(board):  if board[4] == " ":    return 4  return -1############## Move Corner ##################def moveCorner(board):  if board[1] == " " and board[3] == " " and board[0] == " ":    return 0  if board[1] == " " and board[5] == " " and board[2] == " ":    return 2  if board[5] == " " and board[7] == " " and board[8] == " ":    return 8  if board[3] == " " and board[7] == " " and board[6] == " ":    return 6    if board[0] == " ":    return 0      if board[2] == " ":    return 2  if board[6] == " ":    return 6  if board[8] == " ":    return 8  return -1############## Check for tie ##################def checktie(board):  isTie = True  for x in range(0,9):    if board[x] == " ":      isTie = False    return isTie############## Head or Tail ######################def headtail():  bet = input("Head or Tail:")  flip = random.randint(0,1)  if flip == 0:    coin = "Head"  else:    coin = "Tail"    if bet == coin:    return True    return False############## User move ##################def usermove(board, user):  move = input("Make your move (1~9):")  if board[int(move) - 1] != " ":    print("You lost your move!!!")  else:    board[int(move) - 1] = user    drawBoard(board)    if win(board, user):    print("The user ", user, "won!!!")    return True    if checktie(board):    print("It is a tie")    return True      return False  ############## 2 ways block ##################def twowaysblock(board, user):  empty = 0  x = 0  o = 0    steps = [0,1,2,5,8]    for i in steps:    if board[i] == ' ': empty += 1    if board[i] == 'X': x += 1    if board[i] == 'O': o += 1      if user == 'X' and empty == 3 and x == 2:    for i in steps:      if board[i] == ' ':        return i  return -1  ############## Computer move ##################def computermove(board, user):    movetype = ""    move = nextMoveWin(board, opponent(user))  if move == -1:    move = nextMoveWin(board, user)  else:    if movetype == "": movetype = "Computer moves to win!"    if move == -1:    move = twowaysblock(board, user)  else:    if movetype == "": movetype = "Computer moves to win!"  if move == -1:    move = moveCenter(board)  else:    if movetype == "": movetype = "Computer blocks your win!"  if move == -1:    move = moveCorner(board)  else:    if movetype == "": movetype = "Computer moves center!"  if move == -1:    move = randommove(board,opponent(user))  else:    if movetype == "": movetype = "Computer moves corner!"  if movetype == "": movetype = "Computer moves random!"  print(movetype)  board[move] = opponent(user)  print("Computer moves", move + 1)    drawBoard(board)    if win(board, opponent(user)):    print("The computer", opponent(user), "won!!!")    return True    if checktie(board):    print("It is a tie!")    return True    return False################## Main Program ##################tttBoard = [" "] * 9drawBoard(tttBoard)#if headtail():#  print("You won, you will be X")user = "X"#else:#  print("You lost, you will be O")# user = "O"#print("The computer is", opponent(user))while(True):    if user == "X":    if usermove(tttBoard, user):break    if computermove(tttBoard, user): break  else:    if computermove(tttBoard, user):break    if usermove(tttBoard, user):break
Posted Apr 7, 2017, 8:04 AM by Attila Lengyel
• Week 18  import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return False############## Get computer mark ############def opponent(sUser):  if sUser == "O":    return "X"  return "O"############## Strategy to move random ############def randommove(board, sUser):  emptystep = []  for x in range(0,9):    if board[x] == " ":      emptystep.append(x)    move = random.randint(0,len(emptystep)-1)  move = emptystep[move]  return move############## Strategy to win or block ############def nextMoveWin(board, sUser):  for x in range(0,9):    if board[x] == " ":      board[x] = sUser      isWin = win(board, sUser)      board[x] = " "      if isWin:        return x  return -1    ############## Move center ##################def moveCenter(board):  if board[4] == " ":    return 4  return -1############## Move Corner ##################def moveCorner(board):  if board[1] == " " and board[3] == " " and board[0] == " ":    return 0  if board[1] == " " and board[5] == " " and board[2] == " ":    return 2  if board[5] == " " and board[7] == " " and board[8] == " ":    return 8  if board[3] == " " and board[7] == " " and board[6] == " ":    return 6    if board[0] == " ":    return 0      if board[2] == " ":    return 2  if board[6] == " ":    return 6  if board[8] == " ":    return 8  return -1############## Check for tie ##################def checktie(board):  isTie = True  for x in range(0,9):    if board[x] == " ":      isTie = False    return isTie############## Head or Tail ######################def headtail():  bet = input("Head or Tail:")  flip = random.randint(0,1)  if flip == 0:    coin = "Head"  else:    coin = "Tail"    if bet == coin:    return True    return False############## User move ##################def usermove(board, user):  move = input("Make your move (1~9):")  if board[int(move) - 1] != " ":    print("You lost your move!!!")  else:    board[int(move) - 1] = user    drawBoard(board)    if win(board, user):    print("The user ", user, "won!!!")    return True    if checktie(board):    print("It is a tie")    return True      return False  ############## Computer move ##################def computermove(board, user):    movetype = ""    move = nextMoveWin(board, opponent(user))  if move == -1:    move = nextMoveWin(board, user)  else:    if movetype == "": movetype = "Computer moves to win!"  if move == -1:    move = moveCenter(board)  else:    if movetype == "": movetype = "Computer blocks your win!"  if move == -1:    move = moveCorner(board)  else:    if movetype == "": movetype = "Computer moves center!"  if move == -1:    move = randommove(board,opponent(user))  else:    if movetype == "": movetype = "Computer moves corner!"  if movetype == "": movetype = "Computer moves random!"  print(movetype)  board[move] = opponent(user)  print("Computer moves", move + 1)    drawBoard(board)    if win(board, opponent(user)):    print("The computer", opponent(user), "won!!!")    return True    if checktie(board):    print("It is a tie!")    return True    return False################## Main Program ##################tttBoard = [" "] * 9drawBoard(tttBoard)if headtail():  print("You won, you will be X")  user = "X"else:  print("You lost, you will be O")  user = "O"print("The computer is", opponent(user))while(True):    if user == "X":    if usermove(tttBoard, user):break    if computermove(tttBoard, user): break  else:    if computermove(tttBoard, user):break    if usermove(tttBoard, user):break
Posted Mar 24, 2017, 10:09 AM by Attila Lengyel
• Week 17 - Tic Tac Toe Start by Flipping Coin  import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return Falsedef opponent(sUser):  if sUser == "O":    return "X"  return "O"############## Strategy to move random ############def randommove(board, sUser):  emptystep = []  for x in range(0,9):    if board[x] == " ":      emptystep.append(x)    move = random.randint(0,len(emptystep)-1)  move = emptystep[move]  return move############## Strategy to block win ############def blockuser(board, sUser):  for x in range(0,9):    if board[x] == " ":      board[x] = sUser      isWin = win(board, sUser)      board[x] = " "      if isWin:        return x  return -1    ############## Check for tie ##################def checktie(board):  isTie = True  for x in range(0,9):    if board[x] == " ":      isTie = False    return isTie############## Head or Tail ######################def headtail():  bet = input("Head or Tail:")  flip = random.randint(0,1)  if flip == 0:    coin = "Head"  else:    coin = "Tail"    if bet == coin:    return True    return False############## User move ##################def usermove(board, user):  move = input("Make your move (1~9):")  if board[int(move) - 1] != " ":    print("You lost your move!!!")  else:    board[int(move) - 1] = user    drawBoard(board)    if win(board, user):    print("The user ", user, "won!!!")    return True    if checktie(board):    print("It is a tie")    return True      return False  ############## Computer move ##################def computermove(board, user):  move = blockuser(board, user)  if move == -1:    move = randommove(board,opponent(user))    board[move] = opponent(user)  print("Computer moves", move + 1)    drawBoard(board)    if win(board, opponent(user)):    print("The computer", opponent(user), "won!!!")    return True    if checktie(board):    print("It is a tie")    return True    return False################## Main Program ##################tttBoard = [" "] * 9drawBoard(tttBoard)if headtail():  print("You won, you will be X")  user = "X"else:  print("You lost, you will be O")  user = "O"print("The computer is", opponent(user))while(True):    if user == "X":    if usermove(tttBoard, user):break    if computermove(tttBoard, user): break  else:    if computermove(tttBoard, user):break    if usermove(tttBoard, user):break
Posted Mar 17, 2017, 8:26 AM by Attila Lengyel
• Week 16 - Tic Tac Toe Block User Win  import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return Falsedef opponent(sUser):  if sUser == "O":    return "X"  return "O"############## Strategy to move random ############def randommove(board, sUser):  emptystep = []  for x in range(0,9):    if board[x] == " ":      emptystep.append(x)    move = random.randint(0,len(emptystep)-1)  move = emptystep[move]  return move############## Strategy to block win ############def blockuser(board, sUser):  for x in range(0,9):    if board[x] == " ":      board[x] = sUser      isWin = win(board, sUser)      board[x] = " "      if isWin:        return x  return -1    ############## Check for tie ##################def checktie(board):  isTie = True  for x in range(0,9):    if board[x] == " ":      isTie = False    return isTie################## Main Program ##################tttBoard = [" "] * 9drawBoard(tttBoard)user = input("X or O?:")if user != "O" and user != "X":  print("You will be X")  user = "X"print("The computer is", opponent(user))while(True):  ############## User move ##################  move = input("Make your move (1~9):")  if tttBoard[int(move) - 1] != " ":    print("You lost your move!!!")  else:    tttBoard[int(move) - 1] = user    drawBoard(tttBoard)  if win(tttBoard, user):    print("The user ", user, "won!!!")    break    if checktie(tttBoard):    print("It is a tie")    break  ############## Computer move ##################  move = blockuser(tttBoard, user)  if move == -1:    move = randommove(tttBoard,opponent(user))    tttBoard[move] = opponent(user)  print("Computer moves", move + 1)    drawBoard(tttBoard)    if win(tttBoard, opponent(user)):    print("The computer", opponent(user), "won!!!")    break    if checktie(tttBoard):    print("It is a tie")    break
Posted Feb 17, 2017, 8:03 AM by Attila Lengyel
• Week 16 - Tic tac toe random move  import randomdef drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return Falsedef opponent(sUser):  if sUser == "O":    return "X"  return "O"  def randommove(board, sUser):  emptystep = []  for x in range(0,9):    if board[x] == " ":      emptystep.append(x)    move = random.randint(0,len(emptystep)-1)  move = emptystep[move]  return movetttBoard = [" "] * 9drawBoard(tttBoard)user = input("X or O?:")if user != "O" and user != "X":  print("You will be X")  user = "X"print("The computer is", opponent(user))while(True):  move = input("Make your move (1~9):")  if tttBoard[int(move) - 1] != " ":    print("You lost your move!!!")  else:    tttBoard[int(move) - 1] = user    drawBoard(tttBoard)  if win(tttBoard, user):    print("The", user, "won!!!")    break    move = randommove(tttBoard,opponent(user))  tttBoard[move] = opponent(user)  print("The Attila moves", move + 1)    drawBoard(tttBoard)    if win(tttBoard, opponent(user)):    print("The", opponent(user), "won!!!")    break
Posted Feb 10, 2017, 8:00 AM by Attila Lengyel
• Week 15 Tic-tac-toe verison 1  def drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return False  tttBoard = [" "] * 9drawBoard(tttBoard)user = input("X or O?:")if user != "O" and user != "X":  print("You will be X")  user = "X"while(True):  move = input("Make your move (1~9):")  tttBoard[int(move) - 1] = user    drawBoard(tttBoard)  if win(tttBoard, user):    print("The", user, "won!!!")    break
Posted Feb 3, 2017, 7:48 AM by Attila Lengyel
• Check winner tic-tac-toe  def drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  def win(board, player):  if board[0] == player and board[1] == player and board[2] == player:    return True  if board[3] == player and board[4] == player and board[5] == player:    return True  if board[6] == player and board[7] == player and board[8] == player:    return True  if board[0] == player and board[3] == player and board[6] == player:    return True  if board[1] == player and board[4] == player and board[7] == player:    return True  if board[2] == player and board[5] == player and board[8] == player:    return True  if board[0] == player and board[4] == player and board[8] == player:    return True  if board[2] == player and board[4] == player and board[6] == player:    return True    return False  board = [" "] * 9drawBoard(board)user = input("X or O?:")if user != "O" and user != "X":  print("You will be X")  user = "X"move = input("Make your move (1~9):")board[int(move) - 1] = userdrawBoard(board)
Posted Feb 3, 2017, 7:43 AM by Attila Lengyel
• Draw tic-tac-toe board  def drawBoard(board):  print("    |   |   ")  print(" ",board[0],"|",board[1],"|",board[2])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[3],"|",board[4],"|",board[5])  print("    |   |   ")    print("-------------")  print("    |   |   ")  print(" ",board[6],"|",board[7],"|",board[8])  print("    |   |   ")  board = ["X"] * 9drawBoard(board)
Posted Feb 3, 2017, 7:29 AM by Attila Lengyel
• Tic-tac-toe grid  print("   |   |   ")print("   |   |   ")print("   |   |   ")print("-----------")print("   |   |   ")print("   |   |   ")print("   |   |   ")print("-----------")print("   |   |   ")print("   |   |   ")print("   |   |   ")
Posted Feb 3, 2017, 7:22 AM by Attila Lengyel
• Week 14 Random numbers and binary search  import randomprint(random.uniform(0,100))print(random.randint(0,100))print(random.randint(1,6))print("I thought of a number.")number = random.randint(0,100)counter = 0while(True):  guess = int(input("Try to guess:"))  counter += 1  if guess == number:    print("What a chance? You nailed it!")    print("It took you", counter, "guesses")    break  elif guess < number:    print("It is less than what I thought of")  else:    print("It is greater than what I thought of")  if counter == 7:    print("You do not have the right strategy!")    print("   +---+ ")    print("   |   |")    print("   O   |")    print("  /|\  |")    print("  / \  |")    print("       | ")    print("=========")    break
Posted Feb 2, 2017, 7:58 AM by Attila Lengyel
• Week 13: Sum of basics  y = 0z = 0digit = input("Give me a digit:")digits = int(input("How many digits:"))for x in range(10**(digits-1), 10**(digits)):  if str(x).count(digit) > 0:    y = y + 1  z = z + str(x).count(digit)  print("Number of found:", y)print("Total", digit, "s:", z)
Posted Jan 27, 2017, 7:58 AM by Attila Lengyel
• Week 12 - Math Olympiad through Brute Force Search  number = 2 * 3 * 5 * 7 * 11for x in range(1, 6):  guess = number * 2 * x  sGuess = str(guess)  if len(sGuess) != 4: continue   if sGuess.count("6") > 0: continue  if sGuess.count("9") != 1: continue  print(guess)  multipliers = input("How many multipliers?")multi = []for x in range(1, int(multipliers) + 1):  multi.append(int(input("Give me a multi:")))print(multi)digits = int(input("How many digits:"))lower = 10**(digits-1)upper = 10**(digits)-1okdigit = input("What digit you look for?:")notokdigit = input("What digit you don't look for?:")for x in range(lower, upper + 1):  found = True    for y in multi:    if x%y != 0:       found = False      break  if found == False: continue    if str(x).count(okdigit) == 0: continue  if str(x).count(notokdigit) != 0: continue      if found: print(x)
Posted Jan 13, 2017, 8:03 AM by Attila Lengyel
• Week 11 - Math Olympiad  number = 2 * 3 * 5 * 7 * 11for x in range(1, 6):  guess = number * 2 * x  sGuess = str(guess)  if len(sGuess) != 4: continue   if sGuess.count("6") > 0: continue  if sGuess.count("9") != 1: continue  print(guess)  42multipliers = input("How many multipliers?")multi = []for x in range(1, int(multipliers) + 1):  multi.append(input("Give me a multi:"))print(multi)
Posted Jan 6, 2017, 8:09 PM by Attila Lengyel
• Week 10 - Xmas tree sample program  def xmastree(layer, stop):  stars = 1  for x in range(1,stop):    print(" " * (layer - 1 - x) + "*" * stars)    stars = stars + 2    height = 7for y in range(3, height):   xmastree(height,y)
Posted Dec 16, 2016, 8:03 AM by Attila Lengyel
Posted Nov 18, 2016, 8:04 AM by Attila Lengyel
• Week 6 Sample Program  for i in range(0, 100): print(i)list = []list.append(input("Give me a word to remember:"))for i in range(10): list.append(input("Give me an other:"))for i in list: print(i)text = input("Give me sentance:")i = 0while(i < len(text)): print(text[i]) i = i + 2 for j in range(0, len(text), 1): print(text[j])
Posted Nov 10, 2016, 8:05 AM by Attila Lengyel
• Week 5 Sample Program  We learned from this book. http://www.openbookproject.net/books/bpp4awd/index.html We used this little program to discuss integers and floats, conditions and control flows.innum = float(input("Give me a number:"))print(innum)if (innum > 10): print("The number is greater than 10")elif (innum < 10): print("The number is less than 10")else: print("The number is equal to 10")
Posted Nov 4, 2016, 9:00 PM by Attila Lengyel
• Week 4 Sample Program  print("I will help you to sum numbers up")sum = 0while (sum < 30): sum = sum + int(input("Give me a number:")) print(sum) if (sum >= 30):  print("Reached the limit!") while (1): answer = input("How are you?") if (answer == "Great!"): print("Glad to hear!") break
Posted Oct 28, 2016, 8:01 AM by Attila Lengyel
• Week 3 Sample Program  first = int(input("Give me a number:"))second = int(input("Give me a second number:"))print("The first number is ", first,". The second is ", second)summ = first + secondprint("Their sum is:", summ)sign = input("Give me a +, -, * or /:")if sign == "+": print (first + second)elif sign == "-": print (first - second)elif sign == "*": print (first * second)elif sign == "/": print (first / second)else: print("Are you sure you know math?")answer = input("How was the class today?")if (answer == "OK"): print("Sure...")elif(answer == "Good"): print("Excellent!")elif(answer == "Horrible"): print("I'm sorry, I will do better next time!")
Posted Oct 21, 2016, 8:05 AM by Attila Lengyel
• Week 2 Sample for Silver  print("How are you doing?")firstname = input("Give me your name:")print("Hello", firstname, "! It is nice to meet you!")lastname = input("Can you give me your last name?")print(firstname, lastname)year = int(input("Which year were you born?"))print(year)age = 2016 - yearprint("You are", age, "years young!")if age < 19: print("Stop this chat!!!!!!!")else: print("Oh... you like on-line chat... but still watch out!!! :-) ")
Posted Oct 14, 2016, 8:01 AM by Attila Lengyel
• Week 1 Sample Program Posted Oct 7, 2016, 10:46 AM by Attila Lengyel
• Programming classes starting this week Oct 5 Wed (Bronze) and Oct 7 Fri (Silver) at 7:15AM  Dear Parents, I would like to thank you for signing your child up to participate in our Primary Programming classes. This program has over 4 years of history at Silver Oak Elementary and we try to introduce changes every year to keep up with the latest development in technology and improve the classes. Also, for first time we have decided to offer the classes at no charge this year. The classes will be open to anyone to join and try out programming throughout the year. This does not mean that we are not committed to the classes. We will be teaching programming following the method we have developed for this class with the highest quality. Not charging for the classes and make it open enables students to think about programming more freely and invite any of their friends to join if they like. We plan to create a "workshop" like experience where algorithmic thinking is in focus. Development tools, programming languages and design methods come and go so quickly, that at the age of our students what matter is to develop the right thinking approach to systematic problem solving.Please see the details of Primary Programming below:Room: D-14 (Mrs. Hoshino's room)Time: 7:15AM to 8AMBronze days: WednesdaysSilver days: FridaysComputers: Chromebooks provided by the school - do not bring your own device, WiFi will not workDevelopment tool: https://www.nitrous.io/ cloud IDE - works on any device from anywhere with an internet connection and 50 hours usage per month is freeProgramming language: Python 3What to do for this week?1) Create a https://www.nitrous.io/ account. Please choose an account/password for your child to remember easily or write it down on a paper. If you are not able to do it in-time for tomorrow or this week, we will be using http://www.codeskulptor.org/ as back-up. 2) Try to bring your child by 7:15AM3) Due to walk to school week, we will be releasing them at 7:50AM, so that they will be able to run a lap before the school startsVolunteersManadher Kharroubi - InstructorAttila Lengyel - InstructorYvonne French Classroom helper Bronze GroupShireen Alinani - Classroom helper Silver GroupWe are looking forward to continuing Primary Programming at Silver Oak in 2016-17 School Year. Best regards,Attila
Posted Oct 4, 2016, 6:32 PM by Attila Lengyel
• Stock prices from Yahoo  from urllib.request import urlopenimport jsonimport timesymbol = input("Give me a stock symbol:")sURL = "http://finance.yahoo.com/webservice/v1/symbols/"sURL += symbolsURL += "/quote?format=json&view=detail"while True:    html = urlopen(sURL)    response = html.read()    html.close    json_data = json.loads(response.decode())    stock = json_data['list']['resources'][0]['resource']['fields']    print(symbol, " price is ", stock["price"])    for key in stock:        print(key, "=", stock[key])        if float(stock["chg_percent"]) < 0:        print("Your stock is falling!!!! Sorry....")    else:        print("You are making money!!!")    time.sleep(5)
Posted May 24, 2016, 9:48 AM by Attila Lengyel
• translator  dictonary = open("dict.txt", "r")wordmap = {}while True:    line1 = dictonary.readline().rstrip()    line2 = dictonary.readline().rstrip()    if line1 =="": break    print(line1, "in Hungarian is", line2)    wordmap[line1] = line2  while True:    word1 = input("Give me a word in English:")    if word1 == "exit": break    print(word1, "in Hungarian is", wordmap[word1])
Posted May 17, 2016, 8:01 AM by Attila Lengyel
• dictionary file  dictonary = open("dict.txt","a")while True:    word1 = input("Give me a word in English:")    if word1 == "exit":        break    word2 = input("Give me the word in Hungarian:")    dictonary.write(word1)    dictonary.write("\n")    dictonary.write(word2)    dictonary.write("\n")    dictonary.close()
Posted May 17, 2016, 7:45 AM by Attila Lengyel
• May 10 Sample Program  import randomimport timeimport osdef rps():    guess = random.randint(1,3)    if guess == 1:        print("ROCK")    elif guess == 2:        print("PAPER")    elif guess == 3:        print("SCISSORS")for x in range(1,15):    time.sleep(1)    os.system("clear")    time.sleep(1)    print("...Rock...")    time.sleep(1)    print("...Paper...")    time.sleep(1)    print("...Scissors...")    time.sleep(1)    rps()
Posted May 10, 2016, 7:57 AM by Attila Lengyel
• May 03 Sample programs  #Four corners gameimport randomimport timefor x in range(0,100):    time.sleep(1)    print(x)    if x%5 == 0 and x != 0:        print("The loosing corner is ", random.randint(1,4))#Fibonacci sequencev1 = 0v2 = 1v3 = v2 * v1  print(v1)print(v2)for x in range(0,100):    print(v3)    v1 = v2    v2 = v3    v3 = v2 * v1
Posted May 3, 2016, 4:52 PM by Attila Lengyel
• Game  import randommyList1 = [4, 8, 12, 15, 20]myList2 = [len(myList1), 3, 5, 2, 10]numPlayers = int(input("How many people in the class?: "))while True:    t = input("Press enter for student number or q for exit")    if (t == "q"):        break    print("Student number " + str(random.randint(1, numPlayers)))        input("Press Enter for question...")        n1 = random.randint(0, len(myList1) - 1)    n2 = random.randint(0, len(myList2) - 1)        print("myList1[" + str(n1) + "] " + "%" + " myList2[" + str(n2) + "]")        input("Press enter for the answer....")        print(myList1[n1]%myList2[n2])
Posted Apr 26, 2016, 7:43 AM by Attila Lengyel
• class  abc = "abcdefghijklmnopqrstuvwxyz"def encoding(cChar):    i = -1    for x in range(0, len(abc)):        if abc[x] == cChar:            i = x            break        if i == -1:        return cChar        return abc[i - 2]text = input("Give me a message to encode:")sMsg = ""for x in range (0, len(text)):    sMsg = sMsg + encoding(text[x])    print(sMsg)
Posted Mar 22, 2016, 7:53 AM by Attila Lengyel
• Hangman v1.0  def counter(sWord, sChar):    iCount = 0    for x in range (0,len(sWord)):        if sWord[x] == sChar:            iCount += 1    return iCountdef drawHangman(missedGuess):    if missedGuess > 0:        print("       _________")    else:        print("")    if missedGuess > 1:        print("       |        |")    else:         print("       |        ")    if missedGuess > 2:        print("       |        0")    else:         print("       |        ")    if missedGuess > 3:        print("       |       /|\\")        else:         print("       |        ")    if missedGuess > 4:        print("       |        |")    else:         print("       |        ")            if missedGuess > 5:        print("       |       / \\")    else:         print("       |        ")        print("       _________")    print("")    if missedGuess > 6:        return True    else:        return False    def printWord(sWord, sCorrectLetter):    returnString = ""    iShownLetters = 0        for x in range(0, len(sWord)):        if counter(sCorrectLetter, sWord[x]) == 0:            returnString += "*"        else:            returnString += sWord[x]            iShownLetters += 1        print(returnString)    if iShownLetters == len(sWord):        return True    else:        return False    print("This will be my hangman game")iMissed = 0sCorrectLetter = ""import getpasssWord = getpass.getpass("Give me a word:")sName = input("What is your first name?:")print("Hello ",sName, "How are you doing? Today you have to fight for your life!")sGuess = ""while sGuess != "stop":    sGuess = input("Guess a letter:")        if counter(sWord, sGuess[0]) == 0:        iMissed += 1        print("Sorry,",sName," You have missed.")    else:        sCorrectLetter += sGuess[0]        print("Excellent! ", sName, " It was a good guess!")        if drawHangman(iMissed):        print(sName, "You lost! Try again!")        break        if printWord(sWord, sCorrectLetter):        print(sName, " Congratulation!!! You have won!")        break
Posted Feb 25, 2016, 7:56 AM by Attila Lengyel
• Hangman v4  def counter(sWord, sChar):    iCount = 0    for x in range (0,len(sWord)):        if sWord[x] == sChar:            iCount += 1    return iCountdef drawHangman(missedGuess):    if missedGuess > 0:        print("       _________")    else:        print("")    if missedGuess > 1:        print("       |        |")    else:         print("       |        ")    if missedGuess > 2:        print("       |        0")    else:         print("       |        ")    if missedGuess > 3:        print("       |       /|\\")        else:         print("       |        ")    if missedGuess > 4:        print("       |        |")    else:         print("       |        ")            if missedGuess > 5:        print("       |       / \\")    else:         print("       |        ")        print("       _________")    print("")    if missedGuess > 6:        return True    else:        return False    def printWord(sWord, sCorrectLetter):    returnString = ""    iShownLetters = 0        for x in range(0, len(sWord)):        if counter(sCorrectLetter, sWord[x]) == 0:            returnString += "*"        else:            returnString += sWord[x]            iShownLetters += 1        print(returnString)    if iShownLetters == len(sWord):        return True    else:        return False    print("This will be my hangman game")iMissed = 0sCorrectLetter = ""sWord = input("Give me a word:")sGuess = ""while sGuess != "stop":    sGuess = input("Guess a letter:")        if counter(sWord, sGuess[0]) == 0:        iMissed += 1    else:        sCorrectLetter += sGuess[0]        if drawHangman(iMissed):        print("You lost! Try again!")        break        if printWord(sWord, sCorrectLetter):        print("Congratulation!!! You have won!")        break
Posted Feb 11, 2016, 8:03 AM by Attila Lengyel
• Hangman v3  def counter(sWord, sChar):    iCount = 0    for x in range (0,len(sWord)):        if sWord[x] == sChar:            iCount += 1    return iCountdef drawHangman(missedGuess):    if missedGuess > 0:        print("       _________")    else:        print("")    if missedGuess > 1:        print("       |        |")    else:         print("       |        ")    if missedGuess > 2:        print("       |        0")    else:         print("       |        ")    if missedGuess > 3:        print("       |       /|\\")        else:         print("       |        ")    if missedGuess > 4:        print("       |        |")    else:         print("       |        ")            if missedGuess > 5:        print("       |       / \\")    else:         print("       |        ")        print("       _________")    print("")def printWord(sWord, sCorrectLetter):    returnString = ""    for x in range(0, len(sWord)):        if counter(sCorrectLetter, sWord[x]) == 0:            returnString += "*"        else:            returnString += sWord[x]    print(returnString)    print(len(sWord))print("This will be my hangman game")iMissed = 0sCorrectLetter = ""sWord = input("Give me a word:")sGuess = ""while sGuess != "stop":    sGuess = input("Guess a letter:")        if counter(sWord, sGuess[0]) == 0:        iMissed += 1    else:        sCorrectLetter += sGuess[0]        drawHangman(iMissed)    printWord(sWord, sCorrectLetter)
Posted Feb 9, 2016, 7:16 AM by Attila Lengyel
• Hangman v2  def counter(sWord, sChar):    iCount = 0    for x in range (0,len(sWord)):        if sWord[x] == sChar:            iCount += 1    return iCountdef drawHangman(missedGuess):    if missedGuess > 0:        print("       _________")    else:        print("")    if missedGuess > 1:        print("       |        |")    else:         print("       |        ")    if missedGuess > 2:        print("       |        0")    else:         print("       |        ")    if missedGuess > 3:        print("       |       /|\\")        else:         print("       |        ")    if missedGuess > 4:        print("       |        |")    else:         print("       |        ")            if missedGuess > 5:        print("       |       / \\")    else:         print("       |        ")        print("       _________")    print("")    print("This will be my hangman game")drawHangman(0)drawHangman(1)drawHangman(2)drawHangman(3)drawHangman(4)drawHangman(5)drawHangman(6)iMissed = 0sWord = input("Give me a word:")sGuess = ""while sGuess != "stop":    sGuess = input("Guess a letter:")    if counter(sWord, sGuess[0]) == 0:        iMissed += 1        drawHangman(iMissed)
Posted Jan 28, 2016, 8:00 AM by Attila Lengyel
Showing posts 1 - 100 of 106. View more »