50-Introductory-Codes-for-Python
50-Introductory-Codes-for-Python
What is Python?
Python is a high-level, interpreted programming language that is widely used for a variety of
applications. It was first released in 1991 and has since become one of the most popular
programming languages in use today.
Python is known for its simplicity and ease of use, making it a popular choice for beginners
learning to program. It features a clear syntax and an extensive library of built-in functions
and modules that make it useful for a wide range of tasks, from web development to
scientific computing and artificial intelligence.
Python is an interpreted language, meaning that the code is executed line by line, as opposed
to compiled languages like C++ and Java. This allows for quicker development and testing, and
makes it easy to write scripts and prototypes.
Python is also an open-source language, which means that its source code is freely available
and can be modified and redistributed by anyone. This has contributed to the growth of a
large and supportive community of developers and users, who have created many useful
libraries and tools that are freely available for use by anyone.
Problem-solving skills
Coding involves breaking down complex problems into smaller, more manageable tasks. By
learning to code, children can develop their problem-solving skills and learn how to approach
challenges in a logical and systematic way.
Debugging
Debugging is a key skill in programming, as it requires children to identify and fix errors in
their code. This can be frustrating at times, but it also teaches children to be patient and
persistent as they work through problems.
Project completion
Learning Python can help children see a project through from start to finish, which can be a
valuable lesson in resilience. By working on a project over time and overcoming obstacles
along the way, children can learn the importance of perseverance and dedication.
Transferable skills
The skills children learn from coding, such as logical thinking, problem-solving, and attention
to detail, are transferable to other subjects and areas of life. These skills can help children
succeed in school, work, and everyday life.
print("Hello, World!")
This code simply prints the text "Hello, World!" to the console.
print("\U0001F600")
Unicode escape sequences are a way to represent Unicode characters in a string using a
backslash followed by the Unicode code point in hexadecimal. The Unicode code point for an
emoji depends on the specific emoji.
Here are some commonly used emojis and their corresponding Unicode code points in
Python:
Smiling face: \U0001F600
Thumbs up: \U0001F44D
Heart: \U00002764
Crying face: \U0001F622
Face with tears of joy: \U0001F602
Fire: \U0001F525
Clapping hands: \U0001F44F
Party popper: \U0001F389
Thinking face: \U0001F914
Rocket: \U0001F680
To use these Unicode escape sequences, simply include them in a string with a print
statement or use them in any other string manipulation as needed.
import calendar
year = 2023
month = 2
print(calendar.month(year,month))
Next: Ask the user for the year and month they would like printing.
Getting the current time
import time
current_time = time.time()
print(current_time)
This code imports the time library and uses the time() function to get the current time in
seconds since Unix time started, and then prints it to the console. Unix time is a
representation used widely in computing. It measures time by the number of seconds that
have elapsed since 00:00:00 UTC on 1st January, 1970.
Next: Print the current time with a message, such as ‘The Unix time is…’.
Formatting the current time
import time
current_time = time.localtime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", current_time)
print(formatted_time)
This code imports the time library and uses the localtime() function to get the current time as
a struct_time object, and then uses the strftime() function to format the time as a string and
prints it to the console.
Next: Combine this script with the Hello World script at the beginning.
Converting a string to a time object
import time
This code imports the time library and uses the strptime() function to convert a date string in
the format of "YYYY-MM-DD HH:MM:SS" to a time object, and then prints it to the console.
Next: Include a string of text with the time when printed.
Sum of two numbers
num1 = 5
num2 = 7
sum = num1 + num2
print("The sum of", num1, "and", num2, "is", sum)
Next: Change the return text so that it quotes the two numbers entered by the user.
Multiply two numbers
Next: Print the full times tables along with the answer. The algorithm to be used is below.
Generate the multiplication table for a number
Next: Change the range for the tables so that it prints beyond 1 – 11.
Divide two numbers
This code defines two variables num1 and num2, assigns them the values 5 and 7,
respectively, adds them together, and then prints out the result in a sentence.
Next: Add a welcome message before asking for the two numbers.
Calculate the remainder of two numbers
Next: Add another calculation that is processed using the user’s numbers. Print the answer to
this alongside the answer to the division.
Generate a random number
import random
print(random.randint(1, 10))
Next: Change the text that the user sees at the start and end of the script.
Generate a list of even numbers
even_numbers = []
for i in range(1, 11):
if i % 2 == 0:
even_numbers.append(i)
print(even_numbers)
Next: Because the even number are also in the two times tables, also print this.
Generate a list of odd numbers
odd_numbers = []
for i in range(1, 11):
if i % 2 != 0:
odd_numbers.append(i)
print(odd_numbers)
numbers = [5, 2, 8, 1, 7]
numbers.sort()
print(numbers)
numbers = [5, 2, 8, 1, 7]
numbers.sort(reverse=True)
print(numbers)
Next: Add a message when printing the numbers at the end of the script.
Check if a number is prime
numbers = [1, 5, 2, 7, 3]
max_number = max(numbers)
print("The largest number is: " + str(max_number))
numbers = [1, 5, 2, 7, 3]
min_number = min(numbers)
print("The smallest number is: " + str(min_number))
num = -3
if num > 0:
print(num, "is positive")
else:
print(num, "is negative”)
This code assigns the value -3 to the variable num, then checks if num is greater than 0. If it is,
it prints out a message saying that num is positive. Otherwise, it prints out a message saying
that num is negative. In this case, since num is negative, the output would be: -3 is negative.
Next: Ask the user to input one or more numbers
Calculating the area of a rectangle
length = 5
width = 3
area = length * width
print("The area of the rectangle is:", area)
This code calculates the area of a rectangle with length 5 and width 3, and then prints out the
result.
celsius = 20
fahrenheit = (celsius * 9/5) + 32
print(celsius, "degrees Celsius is equal to", fahrenheit, "degrees
Fahrenheit”)
This code converts a temperature in Celsius (in this case, 20 degrees Celsius) to Fahrenheit,
and then prints out the result.
import random
num = random.randint(1, 10)
print("Random number:", num)
This code generates a random integer between 1 and 10 (inclusive) using the random module,
and then prints out the result.
num = 7
if num % 2 == 0:
print(num, "is even")
else:
print(num, "is odd”)
This code checks if a number (in this case, 7) is even or odd using the modulo operator (%),
and then prints out a message accordingly.
This code counts the number of characters in the string "Hello, World!" using the len()
function, and then prints out the result.
Next: Ask for user input and rename the output as ‘word count’.
Reversing a string
This code reverses the string "Hello, World!" using slicing, and then prints out the result.
Next: Ask for user input and rename the user output as ‘mirror words’.
Swapping two variables
a = 5
b = 7
a, b = b, a
print("a:", a)
print("b:", b)
This code swaps the values of two variables (a and b) using tuple unpacking, and then prints
out the new values of a and b.
num1 = 10
num2 = 5
if num1 % num2 == 0:
print(num1, "is a multiple of", num2)
else:
print(num1, "is not a multiple of", num2)
This code checks if num1 is a multiple of num2 using the modulo operator, and then prints
out a message accordingly.
import math
a = 3
b = 4
c = math.sqrt(a**2 + b**2)
print("Length of hypotenuse:", c)
This code uses the Pythagorean theorem to find the length of the hypotenuse of a right
triangle with legs of length 3 and 4, and then prints out the result using the math.sqrt()
function.
nums = [1, 2, 3, 4, 5]
reversed_nums = nums[::-1]
print("Reversed list:", reversed_nums)
This code reverses a list [1, 2, 3, 4, 5] using slicing, and then prints out the result.
Next: Ask the user if they want the list reverse to it’s original order and then execute the
command.
Checking if a list contains a specific element
This code checks if the list fruits contains the element "banana", and then prints out a
message accordingly.
Next: Add more fruit to the list; check if the list contains more than one fruit.
Counting the number of elements in a list
nums = [1, 2, 3, 4, 5]
num_elements = len(nums)
print("Number of elements in list:", num_elements)
This code asks the user for their age using the input() function, converts the input to an
integer using int(), and then prints out a message based on the user's age.
This code asks the user for a password using the input() function, and then checks if the
password is correct. If the password is correct, it prints out "Access granted." If the password
is not correct, it prints out "Access denied."
Next: Ask the user to choose a password at the start of the script.
Asking the user to enter a sentence and printing its length
This code asks the user to enter a sentence using the input() function, counts the number of
characters in the sentence using the len() function, and then prints out the length of the
sentence.
Next: Include a maximum and minimum length for the sentence. Produce an error message if
the length is outside of the parameters set.
Drawing a square
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.done()
This code imports the turtle library, moves the turtle forward and turns it right four times to
draw a square.
import turtle
turtle.circle(50)
turtle.done()
This code imports the turtle library and uses the circle() function to draw a circle with a radius
of 50.
import turtle
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.left(120)
turtle.forward(100)
turtle.done()
This code imports the turtle library, moves the turtle forward and turns it left three times to
draw a triangle.
Next: Observe the angles in the script and change these in order to alter the appearance of
the triangle.
Drawing a spiral
import turtle
for i in range(50):
turtle.forward(i * 5)
turtle.right(90)
turtle.done()
This code imports the turtle library, uses a for loop to draw a spiral by moving the turtle
forward and turning it right with increasing distance and angle.
Next: Change the variables to alter the appearance of the spiral pattern.
Drawing a star
import turtle
for i in range(5):
turtle.forward(100)
turtle.right(144)
turtle.done()
This code imports the turtle library and uses a for loop to draw a star with 5 points by moving
the turtle forward and turning it right by 144 degrees.
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(50)
turtle.done()
This code imports the turtle library, moves the turtle forward and turns it right twice to draw
a rectangle.
import turtle
for i in range(6):
turtle.forward(100)
turtle.right(60)
turtle.done()
This code imports the turtle library, uses a for loop to draw a hexagon by moving the turtle
forward and turning it right by 60 degrees.
Next: Can you make a pentagon based on what you know about a hexagon?
Drawing a smiley face
import turtle
turtle.circle(50)
turtle.penup()
turtle.goto(-20, 60)
turtle.pendown()
turtle.circle(10)
turtle.penup()
turtle.goto(20, 60)
turtle.pendown()
turtle.circle(10)
turtle.penup()
turtle.goto(0, 40)
turtle.pendown()
turtle.right(90)
turtle.circle(20, 180)
turtle.done()
This code imports the turtle library and draws a smiley face by using the circle() function to
draw the head and eyes, and then drawing a smile with circle() and right() functions.
Next: Using turtle.penup() and turtle.pendown(), give the smiley face a body.
Drawing a snowflake
import turtle
for i in range(8):
turtle.forward(50)
turtle.backward(50)
turtle.right(45)
turtle.right(90)
turtle.forward(50)
turtle.backward(50)
turtle.left(45)
for i in range(8):
turtle.forward(50)
turtle.backward(50)
turtle.left(45)
turtle.right(45)
turtle.forward(50)
turtle.backward(50)
turtle.right(90)
turtle.forward(50)
turtle.backward(50)
turtle.left(45)
for i in range(8):
turtle.forward(50)
turtle.backward(50)
turtle.right(45)
turtle.done()
This code imports the turtle library and uses a series of forward(), backward(), right(), and
left() functions to draw a snowflake.
Next: Can you develop the snowflake so that it has more detail?
Delaying for a certain number of seconds
import time
print("Hello")
time.sleep(2)
print(“World!")
This code imports the time library and uses the sleep() function to delay the program for 2
seconds after printing "Hello", and then prints "World!".
import random
Next: Alter the game so that it is a random number between 1 and 20.
Guess the number game with loop
import random
while True:
guess = int(input("Guess a number between 1 and 10: "))
if guess == number:
print("Congratulations! You guessed the number.")
break
else:
print("Sorry, you guessed the wrong number. Please try
again.")
This code uses a while loop to keep prompting the user for guesses until they get the correct
answer. If the user guesses correctly, the code congratulates them and exits the loop using
the break statement. If the user guesses incorrectly, the loop continues and the user is
prompted to guess again. Once the loop exits, the code prints a final message to thank the
user for playing.
Rock, Paper, Scissors game
import random
if player_choice == computer_choice:
print("Tie!")
elif player_choice == "rock" and computer_choice == "scissors":
print("You win!")
elif player_choice == "paper" and computer_choice == "rock":
print("You win!")
elif player_choice == "scissors" and computer_choice == "paper":
print("You win!")
else:
print("Computer wins!”)
This code is a simple rock, paper, scissors game where the user plays against the computer. It
uses a series of if-else statements to determine the winner based on the choices made.
Next: Make the game futuristic – turn it into ‘Hammer, Mirror, Laser!’
Hangman game
import random
This code is a simple Hangman game where the user has to guess a randomly chosen word by
guessing letters one at a time. It uses a while loop and sets to keep track of the guessed
letters and the letters in the word.
Next: Add more words to the game so that it is harder for the player.
Password generator
import random
import string
def generate_password(length):
letters = string.ascii_letters + string.digits +
string.punctuation
return ''.join(random.choice(letters) for i in range(length))
if len(password) < 8:
print("Password is too short")
else:
print("Password is valid”)
Next: When the student finds out they have failed, inform them how many more marks they
need to reach the pass mark.
A code that checks if a year is a leap year
print("Nice to meet you, " + name + ". How are you doing today?")
response = input()
Next: Add more responses to the chatbot and explore the use of if-else statements.