50 Practical and Simple Python Codes for Beginners

Want to learn Python in a simple and practical way? Here are 50 easy-to-understand Python examples with short explanations. These will help you grasp Python basics quickly and effectively.


Section 1: Basics (1 – 10)

  1. Print text on the screen

print("Hello, Python!")

Prints the text between the quotes on the screen.

  1. Add two numbers

x = 5
y = 3
print(x + y)

Prints the sum of the numbers (8).

  1. User input

name = input("Enter your name: ")
print("Hello, " + name)

Takes input from the user and prints a greeting.

  1. Check variable type

num = 10
print(type(num))

Prints the variable type (int).

  1. Convert text to number

age = int(input("How old are you? "))
print(age * 2)

Converts the input to a number and multiplies it by 2.

  1. If condition

score = 60
if score >= 50:
print("Pass")
else:
print("Fail")

Checks if the score is passing or failing.

  1. For loop

for i in range(5):
print("Number:", i)

Prints numbers from 0 to 4.

  1. While loop

count = 1
while count <= 3:
print("Attempt:", count)
count += 1

Repeats the process until count reaches 3.

  1. Simple function

def greet():
print("Hello, Programmer!")
greet()

Defines and calls a simple function.

  1. Using math library

import math
print(math.sqrt(16))

Prints the square root of 16.


Section 2: Working with Strings (11 – 20)

  1. String length

text = "Python"
print(len(text))

Prints the number of characters in the string.

  1. Convert to uppercase

print("hello".upper())

Prints HELLO.

  1. Convert to lowercase

print("WELCOME".lower())

Prints welcome.

  1. Replace text

msg = "I like Java"
print(msg.replace("Java", "Python"))

Replaces "Java" with "Python".

  1. Check if word exists

print("python" in "I love python")

Returns True if the word exists.

  1. Split a string into words

words = "Python is fun".split()
print(words)

Splits the string into a list of words.

  1. Join list into a string

join_text = "-".join(["Py", "thon"])
print(join_text)

Joins list items into a string (Py-thon).

  1. Reverse a string

print("abc"[::-1])

Prints cba.

  1. Trim spaces

print(" Hi ".strip())

Removes extra spaces at the start and end.

  1. Count occurrences

print("banana".count("a"))

Prints how many times "a" appears (3).


Section 3: Lists (21 – 30)

  1. Create a list

fruits = ["apple", "banana", "cherry"]
print(fruits)

Creates a list of fruits.

  1. Add an item

fruits.append("orange")
print(fruits)

Adds "orange" to the list.

  1. Remove an item

fruits.remove("banana")
print(fruits)

Removes "banana" from the list.

  1. Access a specific item

print(fruits[0])

Prints the first item.

  1. Access the last item

print(fruits[-1])

Prints the last item.

  1. List length

print(len(fruits))

Prints the number of items in the list.

  1. Sort a list

numbers = [3, 1, 2]
numbers.sort()
print(numbers)

Sorts numbers in ascending order.

  1. Reverse a list

numbers.reverse()
print(numbers)

Reverses the list order.

  1. Check if item exists

print("apple" in fruits)

Returns True if "apple" exists in the list.

  1. Merge two lists

a = [1, 2]
b = [3, 4]
print(a + b)

Combines both lists.


Section 4: Dictionaries (31 – 40)

  1. Create a dictionary

person = {"name": "Ali", "age": 20}
print(person)

Creates a dictionary with key-value pairs.

  1. Access a value

print(person["name"])

Prints the value of "name".

  1. Update a value

person["age"] = 21
print(person)

Updates the "age" key.

  1. Add a new key-value pair

person["city"] = "Cairo"
print(person)

Adds a new key-value pair.

  1. Delete a key

del person["city"]
print(person)

Deletes the "city" key.

  1. Loop through a dictionary

for key, value in person.items():
print(key, value)

Prints all keys and values.

  1. Get all keys

print(person.keys())

Prints all keys.

  1. Get all values

print(person.values())

Prints all values.

  1. Check if key exists

print("name" in person)

Returns True if the key exists.

  1. Clear the dictionary

person.clear()
print(person)

Removes all items from the dictionary.


Section 5: Fun & Practical (41 – 50)

  1. Random choice

import random
print(random.choice(["red", "green", "blue"]))

Chooses a random item from the list.

  1. Random number

print(random.randint(1, 10))

Generates a random number between 1 and 10.

  1. Current date and time

import datetime
print(datetime.datetime.now())

Prints the current date and time.

  1. Measure execution time

import time
start = time.time()
time.sleep(2)
print("Time elapsed:", time.time() - start)

Measures how long the code takes to run.

  1. Read a file

with open("file.txt", "r") as f:
print(f.read())

Reads and prints a file’s content.

  1. Write to a file

with open("file.txt", "w") as f:
f.write("Hello, file!")

Writes text to a file.

  1. Handle errors

try:
num = int("abc")
except:
print("Conversion error!")

Handles errors without stopping the program.

  1. Draw a circle with turtle

import turtle
turtle.circle(50)

Draws a simple circle.

  1. Convert to JSON

import json
data = {"name": "Omar"}
print(json.dumps(data))

Converts a dictionary to JSON format.

  1. Simple calculator

a = float(input("Enter a number: "))
b = float(input("Enter another number: "))
op = input("Choose operation (+ - * /): ")
if op == "+":
print(a + b)
elif op == "-":
print(a - b)
elif op == "*":
print(a * b)
elif op == "/":
print(a / b)
else:
print("Invalid operation")

Performs basic arithmetic operations (+, -, *, /).


With these 50 simple Python codes, you’ve covered the essential basics to start coding confidently. Practice them, modify them, and try creating your own projects!