0% found this document useful (0 votes)
3 views11 pages

Python Beginner Examples

Uploaded by

Siam Sadik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Python Beginner Examples

Uploaded by

Siam Sadik
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Beginner Code Examples

10 Complete Programs for Beginner Exam Practice

# Example Title Key Concepts

1 Hello World & Basic Input/Output print(), input(), variables

2 Basic Arithmetic Calculator float(), operators, if/else

3 Even or Odd Checker int(), % modulo, conditionals

4 Counting with a For Loop range(), for loop, f-strings

5 Sum of Numbers Using a While Loop while, break, += operator

6 Working with Lists list, append(), enumerate()

7 Simple Function Definition def, parameters, return

8 Grade Checker with if/elif/else if/elif/else, nested logic

9 Simple Dictionary (Student Record) dict, .items(), key/value

10 Factorial Using Recursion recursion, base case


Exampl Hello World & Basic Input/Output
e1

The most classic beginner program. It prints a message and asks the user for their name.

CODE

# Print a simple message


print("Hello, World!")

# Ask the user for their name


name = input("What is your name? ")

# Greet the user


print("Hello,", name, "! Welcome to Python.")

SAMPLE OUTPUT

Hello, World!
What is your name? Alice
Hello, Alice ! Welcome to Python.

TIP: print() displays output. input() reads what the user types from the keyboard.
Exampl Basic Arithmetic Calculator
e2

Takes two numbers from the user and performs addition, subtraction, multiplication, and division.

CODE

# Get two numbers from the user


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform all basic operations


print("Addition: ", num1 + num2)
print("Subtraction: ", num1 - num2)
print("Multiplication:", num1 * num2)

# Check for division by zero


if num2 != 0:
print("Division: ", num1 / num2)
else:
print("Cannot divide by zero!")

SAMPLE OUTPUT

Enter first number: 10


Enter second number: 4
Addition: 14.0
Subtraction: 6.0
Multiplication: 40.0
Division: 2.5

TIP: Use float() to convert input to a decimal number. Always check for division by zero!
Exampl Even or Odd Checker
e3

Checks whether a number entered by the user is even or odd using the modulo operator (%).

CODE

# Get a number from the user


number = int(input("Enter a number: "))

# Check if it is even or odd


if number % 2 == 0:
print(number, "is an EVEN number.")
else:
print(number, "is an ODD number.")

SAMPLE OUTPUT

Enter a number: 7
7 is an ODD number.

Enter a number: 12
12 is an EVEN number.

TIP: The % operator gives the remainder of a division. If remainder is 0, the number is even.
Exampl Counting with a For Loop
e4

Demonstrates the for loop by counting from 1 to 10 and printing each number with its square.

CODE

# Print numbers 1 to 10 with their squares


print("Number | Square")
print("------------------")

for i in range(1, 11):


print(f" {i} | {i ** 2}")

print("------------------")
print("Loop finished!")

SAMPLE OUTPUT

Number | Square
------------------
1 | 1
2 | 4
3 | 9
4 | 16
5 | 25
6 | 36
7 | 49
8 | 64
9 | 81
10 | 100
------------------
Loop finished!

TIP: range(1, 11) generates numbers 1 to 10. Use ** for exponentiation (power).
Exampl Sum of Numbers Using a While Loop
e5

Keeps asking the user to enter numbers and adds them up until the user types 0 to stop.

CODE

# Initialize total
total = 0
count = 0

print("Enter numbers to add. Type 0 to stop.")

while True:
num = float(input("Enter a number: "))

if num == 0:
break # Exit the loop

total += num # Same as: total = total + num


count += 1

print(f"\nYou entered {count} numbers.")


print(f"Total sum = {total}")

SAMPLE OUTPUT

Enter numbers to add. Type 0 to stop.


Enter a number: 5
Enter a number: 10
Enter a number: 3
Enter a number: 0

You entered 3 numbers.


Total sum = 18.0

TIP: break exits a loop immediately. += is shorthand for adding to a variable.


Exampl Working with Lists
e6

Creates a list of student names, adds/removes items, and loops through to display results.

CODE

# Create a list of student names


students = ["Alice", "Bob", "Charlie", "Diana"]

# Add a new student


[Link]("Eve")

# Remove a student
[Link]("Bob")

# Display all students


print("Student List:")
for i, name in enumerate(students, start=1):
print(f" {i}. {name}")

# Show list info


print(f"\nTotal students: {len(students)}")
print(f"First student: {students[0]}")
print(f"Last student: {students[-1]}")

SAMPLE OUTPUT

Student List:
1. Alice
2. Charlie
3. Diana
4. Eve

Total students: 4
First student: Alice
Last student: Eve

TIP: append() adds to end. remove() deletes by value. enumerate() gives index + value together.
Exampl Simple Function Definition
e7

Defines reusable functions to greet a user and calculate the area of a rectangle.

CODE

# Define a function to greet


def greet(name):
print(f"Hello, {name}! Nice to meet you.")

# Define a function that returns a value


def calculate_area(length, width):
area = length * width
return area

# --- Call the functions ---


greet("Alice")
greet("Bob")

# Calculate and display area


length = 8
width = 5
result = calculate_area(length, width)
print(f"\nRectangle {length} x {width}")
print(f"Area = {result} square units")

SAMPLE OUTPUT

Hello, Alice! Nice to meet you.


Hello, Bob! Nice to meet you.

Rectangle 8 x 5
Area = 40 square units

TIP: def defines a function. return sends a value back to the caller. Functions make code reusable.
Exampl Grade Checker with if/elif/else
e8

Reads a student's score and prints the letter grade using multiple conditions.

CODE

# Get the student score


score = int(input("Enter your score (0-100): "))

# Determine the grade


if score >= 90:
grade = "A"
remark = "Excellent!"
elif score >= 80:
grade = "B"
remark = "Very Good!"
elif score >= 70:
grade = "C"
remark = "Good"
elif score >= 60:
grade = "D"
remark = "Needs Improvement"
else:
grade = "F"
remark = "Failed"

print(f"\nScore : {score}")
print(f"Grade : {grade}")
print(f"Remark: {remark}")

SAMPLE OUTPUT

Enter your score (0-100): 85

Score : 85
Grade : B
Remark: Very Good!

TIP: if/elif/else checks multiple conditions in order. Only the first True block executes.
Exampl Simple Dictionary (Student Record)
e9

Uses a dictionary to store and display a student's information like name, age, and grade.

CODE

# Create a student dictionary


student = {
"name" : "Alice Johnson",
"age" : 18,
"grade" : "A",
"subject": "Mathematics",
"score" : 95
}

# Display student information


print("===== Student Record =====")
for key, value in [Link]():
print(f" {[Link]():10}: {value}")

# Update a value
student["score"] = 98
print(f"\nUpdated Score: {student['score']}")

# Check if a key exists


if "name" in student:
print(f"Student name is: {student['name']}")

SAMPLE OUTPUT

===== Student Record =====


Name : Alice Johnson
Age : 18
Grade : A
Subject : Mathematics
Score : 95

Updated Score: 98
Student name is: Alice Johnson

TIP: Dictionaries store key-value pairs. Use .items() to loop through both keys and values.
Exampl Factorial Using Recursion
e 10

Calculates the factorial of a number using a recursive function — a function that calls itself.

CODE

# Define a recursive function for factorial


def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)

# Test the function


print("Factorial Table")
print("---------------")
for num in range(0, 8):
print(f" {num}! = {factorial(num)}")

# User input
number = int(input("\nEnter a number: "))
print(f"{number}! = {factorial(number)}")

SAMPLE OUTPUT

Factorial Table
---------------
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040

Enter a number: 5
5! = 120

TIP: Recursion means a function calling itself. Every recursive function needs a base case to stop.

You might also like