UNIHIVE

Study Hub UNIPORT CSC 183

CSC 183 · Introduction to Problem Solving

First programs: variables, input and output

Turning an algorithm into a Python program with variables, data types, assignment, arithmetic and input and output.

Our notes

2 min read

Why Python

Python is free, reads almost like pseudocode, and runs on phones (with apps such as Pydroid) as well as laptops. CCMAS allows C, Python or similar; the ideas carry over.

Variables and assignment

A variable is a named place that holds a value. The = sign means "store the value on the right in the name on the left" (assignment), not "is equal to".

score = 65
name = "Ada"
score = score + 5

After the third line, score holds 70.

Data types

TypeExampleMeaning
int42whole number
float3.75number with a decimal point
str"UNIPORT"text (a string)
boolTrue, Falseyes/no value

Arithmetic

+ add, − subtract (typed as -), * multiply, / divide (always gives a float), // whole-number division, % remainder.
17 // 5 gives 3 and 17 % 5 gives 2.

Input and output

input() reads text typed by the user; convert it with int() or float() before doing sums. print() shows results.

Worked example: area of a rectangle

length = float(input("Length in m: "))
width = float(input("Width in m: "))
area = length * width
print("Area =", area, "square metres")

With 4.5 and 3 the program prints: Area = 13.5 square metres.

Worked example: naira change

A program that breaks an amount into ₦1,000 and ₦500 notes and the rest:
amount = int(input("Amount: "))
thousands = amount // 1000
rest = amount % 1000
fives = rest // 500
left = rest % 500
print(thousands, "x 1000,", fives, "x 500, and", left, "left")

For 3,700 it prints: 3 x 1000, 1 x 500, and 200 left. Check: 3,000 + 500 + 200 = 3,700 ✓.

Comments and names

A line starting with # is a comment, ignored by Python; use comments to explain why. Choose clear names (total_units, not tu). Names are case-sensitive: Score and score are different.

Errors you will meet

  • Syntax error: the code breaks Python's rules (a missing bracket or colon). Python will not run it.
  • Runtime error: it crashes while running (dividing by zero; int("abc")).
  • Logic error: it runs but gives the wrong answer (using + where * was meant). Only testing finds these.

Exams usually ask

  • Write a short program that reads inputs, computes and prints a result.
  • State the output of a given fragment.

Common mistake

Forgetting that input() gives text: "2" + "3" is "23", not 5.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All CSC 183 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.