Week 3 - Section 1 - Data types and a bit of gaming

Site: ΕΛ/ΛΑΚ Moodle
Course: Python Lab - May 2017
Book: Week 3 - Section 1 - Data types and a bit of gaming
Printed by: Guest user
Date: Thursday, 21 November 2024, 11:07 PM

Description

In this section we will learn about lists and tuples and we will scratch the surface of pygame. Be prepared for excitement.

Chapter 4.1 - Lists

4.1 - Lists

So far we have seen three types of data :

and we learned that we can display the type of data with type function.

You can try the following to remember types :

>>> type(3)

>>> type(3.14)

>>> type("Hello")

We have also spoken about statements and we know that some are True and others are False. Try the following code :

>>> type(True)  # without quotes

>>> type(False) # without quotes

This is another type of data called Boolean and could be one of this words.

List is another type of data. We have created lists using the command range. Then we created lists of numbers.

>>> list(range(1,11))

But a list can contain multiple data. Lets try an example with numbers:

>>> my_list = [1,33,18]

>>> print (my_list) # this is a list of numbers

Chapter 4.2 - And other lists

4.2 - And other lists

So what should i do if i want to create a shopping list? Copy the following command and test it.

>>> my_shopping_list = ["apples","bananas","carrots"] 

>>> print(my_shopping_list)

The items in the list are numbered starting from 0 (as we mentioned in programming we usually start from 0).

So  the 0 item in my_shopping_list is "apples"

      the 1 item is "bananas"

and the 2 item is "carrots"

Try the following :

>>> print(my_shopping_list[0]) # in print we use parenthesis () and in lists square brackets [])

>>> print(my_shopping_list[1])

>>> print(my_shopping_list[2])

>>> print(my_shopping_list[3])

In the last example there is an error :

Traceback (most recent call last):

  File "<pyshell>", line 1, in <module>

IndexError: list index out of range

because myshoppinglist does not has an item indexed 3

we can change an item in list :

>>> my_shopping_list[0] = "apricots"

>>> print(my_shopping_list)

And we can iterate (loop) through a list. Copy the following code to Thonny:

my_friends = ["Jim", "John", "Jack", "Jane"] for item in my_friends: print (item)

We can view the number of items in a list with command len.

>>> len(my_friends)

and we can add items to a list :

>>> my_friends.append("Joe")

>>> print(my_friends)

Our list has 5 items now. Check its length.

Chapter 4.3 - Modifying and summing a list

4.3 - Modifying and summing a list

So how can we add all the items in a list?

Copy the following code to Thonny and save it as sumlist:

# Add items of a list my_list = [5,76,8,5,3,3,56,5,23] # Initial Sum should be zero list_total = 0 # Loop from 0 up to the number of elements # in the array: for i in range(len(my_list)): # Add element 0, next 1, then 2, etc. list_total += my_list[i] # Print the result print(list_total)


Take a closer look to the command range(len(my_list)). What do you think it does?

We can change the code to the following. Copy and paste it again to Thonny and save it as sumlist2 :

# Add items of a list my_list = [5, 76, 8, 5, 3, 3, 56, 5, 23] # Initial Sum should be zero list_total = 0 # Loop through array, copying each item in the array into # the Variable named item. for item in my_list: # Add each item list_total += item # Print the result print(list_total)


Try to find the differences of the two previous codes.

As an exercise write a code to create a list of all integer numbers from 11 to 81 and then calculate the sum of this list. You should find 3266

Steps

  1. create an empty list with any name (ex. new_list)
  2. with a for loop append numbers from 11 to 81 to the list
  3. create a variable total to sum the numbers and initiate it to 0
  4. with a new for loop add all items of the list to total variable

The solution can be found here.

Chapter 4.4 - Random

4.4 - Random

Random is a function that creates random numbers. It is not in the core of Python but in a library (the random library). In order to use it first we have to import the library. Copy the following code to Thonny and save it as Randomize.

import random print (random.randrange(1,50))


If we wanted to randomly select a number between 50 and 80 then the code should be :

import random print(random.randrange(50,81))


You can explore random function and how to use it in several cases here

To combine lists with random we will create a list of 20 random numbers from 1 to 80 like in the kino game.

Copy the following code to Thonny's editor and save it as kino.

# This code creates and prints 20 kino numbers import random # random is a library kino_list=[] # create an empty list for i in range(20): kino_list.append(random.randrange(1,81)) # appends a random number to the list print (kino_list)


Are the numbers in the list unique?

Chapter 4.5 - More Random

4.5 - More random

Also there is a way to pick a random item out of a list. Copy the following code to Thonny :

import random my_list = ["rock", "paper", "scissors"] random_index = random.randrange(3) print(my_list[random_index])


All of the prior code generates integer numbers. If a floating point number is desired, a programmer may use the random function.

The code below generates a random number from 0 to 1

import random my_number = random.random()


and the following code creates a random number between 10 and 45

import random my_number = random.random() * 35 + 10


Can you create a code that generates a random number between 27 and 42?

Chapter 4.6 - While

4.6 - While

A while loop is used when a program needs to loop until a particular condition occurs.

Oddly enough, a while loop can be used anywhere a for loop is used. It can be used to loop until an increment variable reaches a certain value. Why have a for loop if a while loop can do everything? The for loop is simpler to use and code. A for loop that looks like this:

for i in range(10): print(i)

...can be done with a while loop that looks like this:

i = 0 while i < 10: print(i) i = i + 1

In a while loop we have to

So a better use of the while loop is to ask for a reply from the user.

Copy the code to Thonny and save it as test_while (or whatever name you like) :

quit = "n" while quit == "n": quit = input("Do you want to quit? ")


What is the result of this code? If you reply n then the code stays in the loop and keeps asking. It is not perfect but it helps and if you can make it better it works better.

As an exercise create a code that asks the user to input his name and then his favorite color and then display a message "Hi name! Your favorite color is color! After that ask the player if he wants to play again and if he replies yes then ask again name and color if replies no exit and in any other case ask again.

Steps

  1. create a variable game and assign it True (when it turns to False game stops)
  2. create a while loop to check game variable
  3. input name and color to two variables
  4. create a variable cont to ask user if he want to continue
  5. with a while loop ask user if he wants to continue 

You can view a sample solution here.

Chapter 4.7 - The Guessing GAME

4.7 - The Guessing GAME

Copy the following code to Thonny and save it as Guess

# This is a "Guess the number game" # You have 7 attempts to find a number between 1 and 99 # Wisely your numbers choose - Master Yoda's saying # ----------------------------------------------------- import random guesses_taken = 0 # After each attempt this number is increased by 1 print("Hello! What is your name?") my_name = input() number = random.randint(1, 100) print("Well, " + my_name + ", I am thinking of a number between 1 and 99.") # An alternative way to display text using + while guesses_taken < 7: print("Take a guess.") guess = input() # Ask the player for a number guess = int(guess) # Convert text to number guesses_taken = guesses_taken + 1 # Increase the guesses_taken by one if guess < number: print("Your guess is too low.") if guess > number: print("Your guess is too high.") if guess == number: break # Break means get out of while if guess == number: guesses_taken = str(guesses_taken) print("Good job, " + my_name + "! You guessed my number in " + guesses_taken + " guesses!") if guess != number: number = str(number) print("Nope. The number I was thinking of was " + number)


We will play the game together and try to explain the steps using the Debug button.

Chapter 4.8 - Pygame

4.8 - Pygame (finally)

The basic template for the pygame code follows. Click on the link below, copy the contents of the file to Thonny and save it as pygame_basic (or with whatever name you like).

Pygame basic template

So what is all of the commands?

import pygame # it imports the library pygame

Colors are not known to Python, so we create them using Red Green and Blue (RGB) numbers from 0 to 255. So color (0, 128, 255) is no Red half(128) Green and full Blue. You can view the results here. We use CAPITAL letters for variables that don't change (we usually call them constants).

pygame.init() # starts the pygame 

size = (700,500) # Set the width and height of the screen

screen = pygame.display.set_mode(size) # creates a window and name it screen

pygame.display.set_caption("My Game") # This is the name on the top of the window

done = False # We create a variable that is called done and when this variable turns to True, during the game, the game stops.

clock = pygame.time.Clock() # It controls the refresh rate

The three following commands wait for user interaction (event). QUIT is when we press the X button on the top of the window. Then variable done changes to True and the code gets out of the loop

for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

screen.fill(WHITE) # background is WHITE. Try to change it to other defined colors.

pygame.display.flip() # update the screen

clock.tick(60) # refresh 60 times a second

When the code gets out of the loop

pygame.quit() # Close the window and quit.

In case you want to review what the commands are doing it this template you can view the following video :