Learn to Code via Tutorials on Repl.it!

← Back to all posts
Learn to code Python! Part 4: Modules!
CoderBean (11)

Welcome to Part 4 of my learning Python tutorial. In this tutorial we are going to quickly finish our e-banking thing, then we will make a dice rolling game.

So first things first go to your e-banking file and head on down to the third if statement. We are going to ask the user to input the name of the account they want to check the balance of. So,

acc = input("account: ")

Real easy. Then we run a for loop through the list accounts to find the index number, because the balance of that account should be at the same index position. So once making the for loop put this inside

index = accounts.index(items)

My for loop looks like this, yours should look similar, if you have different variables thats ok

for items in accounts:
    index = accounts.index(items)

.index() gets the index position and is returned as int. Then exit the for loop and print the balance.

acc = input("account: ")
for items in accounts:
    if items == acc:
       index = accounts.index(items)
print(index)

Apologise but I forgot the if statement. Anyway really easy. Congrats! Your e-banking thingo is done! By now you should have a grasp on variables, if statements and iterating!

Modules

Now lets move onto our dice game! Modules, what are they? Good question padawan, a module is an installed library of code that someone else has made. To add this library of code to our file we use import or from (module) import (function). Because Python is an interpreted language we import modules at the top because if you call a function from a module before you import the module Python won't recognise it.

So for our dice game we want to import random at the top of our file. This will allow us to make things happen randomly, like the number our dice produces. So we want to ask our user to roll the dice. So

input("Press enter to roll the dice")

We don't actually want them to provide input but it doesn't matter if they do or don't, we are just using input because when Python runs over input it pauses and waits for input, when you press enter it moves on to the next line.

Now we want to roll the dice, so copy this,

diceRoll = random.randint(1, 6)

diceRoll is equal to a random number between 1 and 6. randint is random integer, and we type random. to let Python know where to look for randint. So then we can just print diceRoll.

diceRoll = random.randint(1, 6)
print(diceRoll)

Check out pyip to find a library of all of Python's modules.

I hope you learnt something and had fun, until next time good coding!

P.S In the last tutorial I asked you to make an infinite counter, well here is what it should look like

i = 0
While True:
     print(i)
     i += 1 # or i = i + 1

Here is your next challenge, make a code that asks for your name, and prints it backwards.

Cheers,
ChickenTendys
Part 1
Part 2
Part 3