Programming Basics
Practice problems and improve your skills.
THEORY
All theory for this topic
# Python Programming Basics
In this topic, you will learn the basic Python concepts needed to solve simple programming problems. We will not use loops, lists, dictionaries, or custom functions yet. The main goal is to learn how to read input, store values in variables, perform calculations, check conditions, and print results.
After completing this topic, you should be able to turn a simple problem statement into a working Python program.
## 1. Variables
A variable is a name used to store a value.
```python
age = 16
price = 19.99
name = "Alex"
```
Here, `age` stores an integer, `price` stores a decimal number, and `name` stores text.
A variable can be changed:
```python
score = 10
score = 25
print(score)
```
Output:
```text
25
```
Try to use clear variable names:
```python
width = 10
height = 5
area = width * height
```
This makes your code easier to read and understand.
## 2. Basic Data Types
The first problems mostly use four basic data types.
### int β integers
```python
age = 16
count = 100
temperature = -5
```
### float β decimal numbers
```python
price = 12.5
height = 1.82
```
Python uses a dot for decimal numbers.
### str β strings
Strings store text:
```python
name = "Python"
city = "London"
```
### bool β boolean values
A boolean has only two possible values:
```python
True
False
```
For example:
```python
print(10 > 5)
```
Output:
```text
True
```
## 3. Reading Input with input()
Use `input()` to read data:
```python
name = input()
```
Important: `input()` always returns a string.
To read an integer:
```python
age = int(input())
```
To read a decimal number:
```python
price = float(input())
```
## 4. Reading Multiple Values
If numbers are on separate lines:
```python
a = int(input())
b = int(input())
```
If several numbers are on one line:
```text
10 20
```
use:
```python
a, b = map(int, input().split())
```
`input()` reads the line, `split()` separates it by spaces, and `map(int, ...)` converts each part into an integer.
For three values:
```python
a, b, c = map(int, input().split())
```
## 5. Printing Output
Use `print()` to display a result:
```python
answer = 42
print(answer)
```
You can print several values:
```python
print(a, b)
```
Online judges usually compare your output with the expected output exactly. Do not print extra text unless the problem asks for it.
Correct:
```python
print(answer)
```
Incorrect if the statement does not request it:
```python
print("Answer:", answer)
```
## 6. Arithmetic Operations
Python supports the main arithmetic operators:
- `+` β addition;
- `-` β subtraction;
- `*` β multiplication;
- `/` β normal division;
- `//` β integer division;
- `%` β remainder;
- `**` β exponentiation.
Examples:
```python
print(5 + 3) # 8
print(10 - 4) # 6
print(6 * 7) # 42
print(10 / 4) # 2.5
print(10 // 4) # 2
print(10 % 4) # 2
print(2 ** 5) # 32
```
## 7. Integer Division and Remainder
The operators `//` and `%` are often used together.
For example, convert 135 minutes into hours and minutes:
```python
minutes = 135
hours = minutes // 60
remaining = minutes % 60
print(hours, remaining)
```
Output:
```text
2 15
```
`//` tells you how many complete parts fit into a number, while `%` gives the remainder.
## 8. Order of Operations
Python follows the normal mathematical order of operations.
```python
result = 2 + 3 * 4
```
The result is `14` because multiplication is performed first.
Use parentheses to change the order:
```python
result = (2 + 3) * 4
```
Now the result is `20`.
For complicated formulas, parentheses can also make the code easier to understand.
## 9. Working with Digits
Integer division and remainder can be used to extract digits from a number.
For a two-digit number:
```python
n = 47
first = n // 10
last = n % 10
```
The digits are `4` and `7`.
For a three-digit number:
```python
n = 583
hundreds = n // 100
tens = n // 10 % 10
ones = n % 10
```
The digits are `5`, `8`, and `3`.
## 10. Comparisons
Comparison operators are:
- `==` β equal;
- `!=` β not equal;
- `>` β greater than;
- `<` β less than;
- `>=` β greater than or equal to;
- `<=` β less than or equal to.
Example:
```python
age = 18
print(age >= 18)
```
Output:
```text
True
```
Do not confuse `=` and `==`.
```python
x = 5
```
assigns a value.
```python
x == 5
```
compares values.
## 11. The if Statement
Use `if` when some code should run only when a condition is true.
```python
age = int(input())
if age >= 18:
print("Adult")
```
The code inside the `if` block runs only when the condition is true.
Notice the colon and indentation.
## 12. if / else
Use `else` when there are two possible outcomes:
```python
n = int(input())
if n > 0:
print("positive")
else:
print("not positive")
```
If the condition is true, the first block runs. Otherwise, the `else` block runs.
## 13. if / elif / else
Use `elif` when there are several possible cases:
```python
n = int(input())
if n > 0:
print("positive")
elif n < 0:
print("negative")
else:
print("zero")
```
Python checks conditions from top to bottom and executes the first matching branch.
This means the order of conditions matters.
Example:
```python
score = int(input())
if score >= 90:
print("A")
elif score >= 75:
print("B")
elif score >= 60:
print("C")
else:
print("F")
```
## 14. Boolean Operators
### and
Both conditions must be true:
```python
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Allowed")
```
### or
At least one condition must be true:
```python
day = 6
if day == 6 or day == 7:
print("Weekend")
```
### not
`not` reverses a boolean value:
```python
is_raining = False
if not is_raining:
print("Go outside")
```
## 15. Checking a Range
Python allows you to check whether a value is inside a range:
```python
x = 7
if 1 <= x <= 10:
print("inside")
```
This means that `x` is at least `1` and at most `10`.
## 16. Even and Odd Numbers
Use the remainder operator to check whether a number is even:
```python
n = int(input())
if n % 2 == 0:
print("even")
else:
print("odd")
```
An even number has a remainder of `0` when divided by `2`.
## 17. Minimum and Maximum
You can find the larger of two numbers using a condition:
```python
a, b = map(int, input().split())
if a > b:
print(a)
else:
print(b)
```
Python also provides built-in functions:
```python
print(max(a, b))
print(min(a, b))
```
## 18. Typical Structure of a Simple Program
Most problems in this topic have three main steps.
### 1. Read input
```python
a, b = map(int, input().split())
```
### 2. Calculate the result
```python
result = a + b
```
### 3. Print the result
```python
print(result)
```
Complete program:
```python
a, b = map(int, input().split())
result = a + b
print(result)
```
## 19. Turning a Problem Statement into Code
First determine what data is given and what result is required.
Example:
A rectangle has a given width and height. Find its area.
Input values:
```text
width
height
```
Formula:
```text
area = width * height
```
Code:
```python
width, height = map(int, input().split())
area = width * height
print(area)
```
Do not try to write the whole program immediately. First understand the formula or logic of the solution.
## 20. Edge Cases
After writing your program, test more than just the normal case.
Think about:
- zero;
- negative numbers;
- equal values;
- the minimum allowed value;
- the maximum allowed value;
- values exactly on a condition boundary.
For example, if your condition is:
```python
if age >= 18:
```
check `17`, `18`, and `19`.
## 21. Common Mistakes
### Forgetting to convert input()
```python
a = input()
b = input()
print(a + b)
```
For input `2` and `3`, this prints `23` because strings are joined together.
Correct version:
```python
a = int(input())
b = int(input())
print(a + b)
```
### Confusing / and //
```python
5 / 2
```
returns `2.5`, while:
```python
5 // 2
```
returns `2`.
### Confusing = and ==
`=` assigns a value, while `==` compares values.
### Incorrect condition order
Check more specific or stricter cases first.
Bad:
```python
if score >= 60:
print("passed")
elif score >= 90:
print("excellent")
```
For `95`, the first branch already runs.
Better:
```python
if score >= 90:
print("excellent")
elif score >= 60:
print("passed")
```
### Printing extra text
If the problem asks for only a number, print only the number.
## 22. Problem-Solving Algorithm
Use this process for every problem:
1. Read the whole statement.
2. Identify the input data.
3. Identify what must be printed.
4. Find the required formula or conditions.
5. Read the data using `input()`.
6. Perform the calculations.
7. Use `if / elif / else` if needed.
8. Print only the required result.
9. Test the example from the statement.
10. Test at least one edge case.
## 23. What You Should Know After This Topic
After completing this topic, you should be able to:
- create and change variables;
- work with `int`, `float`, `str`, and `bool`;
- use `input()` and `print()`;
- read several values from one line;
- perform arithmetic operations;
- use `/`, `//`, `%`, and `**`;
- extract digits from numbers;
- compare values;
- use `and`, `or`, and `not`;
- write `if / elif / else` statements;
- check ranges;
- determine whether a number is even or odd;
- find minimum and maximum values;
- turn a simple problem statement into code;
- test solutions on edge cases.
These skills form the foundation for the next topic β loops, where programs learn to repeat actions many times.
YOUR PROGRESS
Topic progress
PRACTICE
Problems
Solve problems from easy to hard and build your skills step by step.
Add Seven
Multiply Two Numbers
Purchase Cost
Kilometres to Metres
Average of Three Numbers
Minutes to Hours and Minutes
Seconds to Time
Last Digit
Sum of Digits of a Two-Digit Number
Circle Area
Circumference
Price After Discount
Percentage of a Number
Celsius to Fahrenheit
Currency Conversion
Rectangle Perimeter
Rectangle Area
Triangle Area
Average Speed
Distance from Speed and Time
Monthly Salary
Salary After Tax
Difference of Numbers
Absolute Difference
Number of Tens
Number of Hundreds
First Digit of a Four-Digit Number
Last Two Digits
Reverse a Two-Digit Number
Reverse a Three-Digit Number
Even or Odd
Divisible by 3
Divisible by 5
Divisible by 3 and 5
Is the Last Digit Even?
Number in Range
Number Outside Range
Same Sign
Different Signs
Positive, Negative, or Zero
Age Check
Adult Check
Can Buy Item
Password Length Check
Temperature Check
Larger of Two
Smaller of Two
Are Numbers Equal?
Maximum of Three
Minimum of Three
Middle Number
Largest Digit
Smallest Digit
Best Competition Result
Who Is Older?
Competition Winner
Student Grade
Age Category
Day of Week
Days in Month
Leap Year
Triangle Existence
Triangle Type
Coordinate Quadrant
Traffic Light
Rock Paper Scissors
Calculator
Store Discount System
Ticket Price
Bank Interest
User Access Level
Login and Password
User Registration
Loan Conditions
Delivery Availability
Free Delivery
Internet Plan Choice
Season
Time of Day
Clothes for Weather
Smart Alarm
Date Validation
Next Day
Previous Day
Time Difference
Minutes Between Events
Lucky Ticket Number
Number Palindrome
Digit Count
Sum of Four Digits
Product of Four Digits
First and Last Digit
ATM
Chessboard Color
Guess the Number
Smart Calculator
Bank Terminal
Ticket Booking System
Student Performance Analysis
Personal Assistant
No matching problems
Try another filter or search query.