Practical Python Examples for Beginners to Enhance Coding Skills
Summing Numbers in Python
# Accept user input for two numbers
first_number = input('Enter the first number: ')
second_number = input('Enter the second number: ')
# Compute the sum after converting to floats
total = float(first_number) + float(second_number)
# Output the result
print(f'The sum of {first_number} and {second_number} is: {total}')
Running this code produces:
Enter the first number: 1.5
Enter the second number: 2.5
The sum of 1.5 and 2.5 is: 4.0
Generating Random Entegers in Python
# Import the random module
import random
# Generate a random integer between 0 and 9 inclusive
random_value = random.randint(0, 9)
print(random_value)
Output may vary each execution, such as:
4
The randint(a, b) function returns a random integer N where a ≤ N ≤ b.
Printing Prime Numbers Within a Range
# Get range boundaries from user
start = int(input('Enter the lower bound: '))
end = int(input('Enter the upper bound: '))
# Iterate through the range
for current_num in range(start, end + 1):
# Check if number is greater than 1
if current_num > 1:
# Test for primality
for divisor in range(2, current_num):
if current_num % divisor == 0:
break
else:
print(current_num)
Sample execution:
Enter the lower bound: 1
Enter the upper bound: 100
Determining Days in a Month
import calendar
# Retrieve weekday of first day and total days for September 2016
first_weekday, days_count = calendar.monthrange(2016, 9)
print((first_weekday, days_count))
Output:
(3, 30)
The tuple indicates the first day of September 2016 was Thursday (3, where 0 is Monday) and the month had 30 days.
Clearing a List in Python
sample_list = [6, 0, 4, 1]
print('Before clearing:', sample_list)
sample_list.clear()
print('After clearing:', sample_list)
Result:
Before clearing: [6, 0, 4, 1]
After clearing: []
Additional Example Topics
- Hello World Program
- Calculating Square Roots
- Solving Qudaratic Equations
- Computing Triangle Area
- Calculating Circle Area
- Temperature Conversion (Celsius to Fahrenheit)
- Swapping Variable Values
- Conditional Statements with if
- Loooping Constructs
- String Manipulation Techniques