Basic Python code examples

This piece of code prints a message:

print("Hello, World!)

This piece of code asks the user their name, and then says hello:

name = raw_input("What is your name? ")
print("Hello " + name)

This code asks for a number and then tells the user what the square of the number is. The important part of this example is that the user’s input has to be converted to a number before we can do mathematical operations with it, and then converted back to a string before we print it.

number = raw_input("Enter a number: ")
number = int(number)
square = number * number
print("The square of that number is: " + str(square))

This code asks the user to enter a password and keeps asking until they get it right.

password = "secret"
userTyped = raw_input("Enter the password: ")
while userTyped != password:
    print("Password incorrect.")
    userTyped = raw_input("Enter the password: ")
print("Password correct.")

This code simulates rolling a pair of dice:

import random
dice1 = random.randrange(1,7)
dice2 = random.randrange(1,7)
print("You rolled " + str(dice1 + dice2))

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s