Python and C Basics: Data Types, Operators, Loops and Output Tracing

Python and C are the two languages most often used in computer papers for lecturer, programmer and IT posts, and in the ICS computer syllabus. Questions test basic syntax, data types, the difference between Python’s and C’s division and remainder, loops, functions and short pieces of code whose output must be traced by hand. In this lesson, code that would normally be on several lines is written on one line, with semicolons between statements; anything after a colon in a Python loop is the loop body.

Asked in: PPSC, FPSC, NTS, ETEA, KPPSC, SSC, IBPS and ICS/ECAT computer

Two languages, two styles

Python is a high-level, interpreted language with dynamic typing: a variable gets its type from the value stored in it, and no declaration is needed. Blocks of code are marked by indentation, comments start with #, and statements do not need semicolons. Functions are defined with the keyword def, and output uses print().

C is a compiled, statically typed language developed by Dennis Ritchie at Bell Labs in the early 1970s. Every variable must be declared with a type before use, every statement ends with a semicolon, blocks are enclosed in curly braces, and execution starts at the main() function. Single-line comments start with two slashes; multi-line comments sit between a slash-star pair and a star-slash pair. Output uses printf() with format specifiers.

Data types

Python’s basic types are int (whole numbers, of unlimited size), float (decimals), str (text in single or double quotes), bool (True or False, with a capital first letter), and the collections list (changeable, in square brackets), tuple (unchangeable, in round brackets) and dict (key-value pairs, in curly braces). The function type() reports a value’s type.

C’s basic types are int (whole numbers), float and double (decimals; double has more precision), and char (a single character written between single quotes, such as the letter A, stored as its numeric code and taking 1 byte). C has no built-in string type; text is stored as an array of characters ending in a null character.

printf() format specifiers: %d for an int, %f for a float or double, %c for a char and %s for a string.

Division and remainder: Python vs C

In Python 3, the single slash always gives a float: 7 / 2 = 3.5 and even 8 / 2 = 4.0. The double slash is floor division, which rounds down towards minus infinity: 7 // 2 = 3 but −7 // 2 = −4. The % operator gives a remainder with the same sign as the divisor, so −7 % 2 = 1, and a == (a // b) × b + a % b always holds.

In C, dividing one int by another gives an int, and since C99 the result is truncated towards zero: 7 / 2 = 3 and −7 / 2 = −3. The % operator gives a remainder with the same sign as the dividend, so −7 % 2 = −1. If either operand is a float or double, as in 7 / 2.0, the result is 3.5.

Python’s exponent operator is written as two star symbols, and the multiplication operator in both languages is a single star; this lesson writes multiplication in words or as × in explanations.

Other operators

Assignment uses =, while comparison for equality uses == and inequality uses !=. Python’s logical operators are the words and, or and not; C uses && for AND, || for OR and ! for NOT. In both languages True or a non-zero value counts as true, and in Python True + True = 2 because True behaves as 1.

C has increment and decrement operators that Python lacks. In post-increment, x++, the old value is used first and then x increases by 1; in pre-increment, ++x, x increases first and the new value is used. So with x = 5, y = x++ gives y = 5 and x = 6, while y = ++x gives y = 6 and x = 6. Python writes x += 1 or x = x + 1 instead.

Loops

Python’s for loop runs over a sequence, most often range(). range(stop) gives 0 up to stop − 1; range(start, stop) gives start up to stop − 1; range(start, stop, step) moves in steps. So range(1, 5) gives 1, 2, 3, 4 and range(0, 10, 3) gives 0, 3, 6, 9. The stop value itself is never included.

A while loop repeats as long as its condition is true and may not run at all. C has for (initialisation; condition; update), while and do-while; a do-while loop checks its condition at the end, so its body always runs at least once. Python has no do-while loop.

break leaves the loop at once and continue skips to the next repetition. If the condition never becomes false, as when a counter jumps over the value being tested with !=, the loop runs forever: an infinite loop.

Functions and strings

A Python function is defined with def name(parameters): and sends back a value with return; a function with no return statement returns None. Parameters can have default values, as in def greet(name, msg="Hello"), used when the caller leaves that argument out.

A C function states its return type, name and parameter types, as in int add(int a, int b) { return a + b; }; a function that returns nothing has return type void.

Python strings are indexed from 0, and negative indexes count from the end, so s[-1] is the last character. Slicing s[a:b] gives the characters from index a up to but not including b. len(s) gives the number of characters, and + joins two strings.

Solved examples

  1. Evaluate in Python: 17 // 5, 17 % 5 and 17 / 5.
    1. 17 = 5 × 3 + 2, so floor division gives 3 and the remainder is 2.
    2. The single slash always gives a float: 17 / 5 = 3.4.
    Answer: 3, 2 and 3.4
  2. Find −17 // 5 and −17 % 5 in Python, and −17 / 5 and −17 % 5 in C with int operands.
    1. Python rounds down: −17 ÷ 5 = −3.4, rounded down to −4; the remainder is −17 − (−4 × 5) = 3.
    2. C truncates towards zero: −3.4 becomes −3; the remainder is −17 − (−3 × 5) = −2.
    Answer: Python: −4 and 3. C: −3 and −2
  3. What does this Python code print? total = 0; for i in range(1, 6): total = total + i; then, after the loop, print(total)
    1. range(1, 6) gives 1, 2, 3, 4, 5; 6 is not included.
    2. total becomes 1, 3, 6, 10 and finally 15.
    Answer: 15
  4. What does this C code print? int a = 5; int b = a++; int c = ++a; printf("%d %d %d", a, b, c);
    1. b = a++ stores the old value 5 in b, then a becomes 6.
    2. c = ++a first makes a 7, then stores 7 in c.
    3. The output is a, b, c = 7 5 7.
    Answer: 7 5 7
  5. What does this Python code print? def perimeter(l, w): return l + l + w + w; then print(perimeter(7, 3))
    1. l = 7 and w = 3 inside the function.
    2. Return value = 7 + 7 + 3 + 3 = 20.
    Answer: 20
  6. Given s = "Islamabad", what does print(s[0:5], s[-3:], len(s)) display?
    1. Indexes 0 to 4 give I, s, l, a, m: "Islam".
    2. s[-3:] takes the last three characters: "bad".
    3. The word has 9 characters, so len(s) = 9; print separates the values with spaces.
    Answer: Islam bad 9

Exam shortcuts

Common mistakes

Practice MCQs

  1. Which symbol begins a single-line comment in Python?
    A) //
    B) --
    C) #
    D) %
    Answer: C) # — Python ignores everything after # on a line. Two slashes begin a comment in C, C++ and Java, two hyphens do so in SQL, and % is the remainder operator in Python.
  2. In C, what must normally end every simple statement?
    A) A colon
    B) A full stop
    C) A comma
    D) A semicolon
    Answer: D) A semicolon — C uses the semicolon as its statement terminator, and leaving it out is a common syntax error. A colon is used in labels and switch cases, a full stop accesses structure members, and a comma separates items in a list.
  3. Which keyword is used to define a function in Python?
    A) def
    B) function
    C) func
    D) define
    Answer: A) def — Python functions are written as def name(parameters):. The word function is used in JavaScript, func in Go and Swift, and define is not a Python keyword.
  4. In Python 3, what is the data type of the result of 7 / 2?
    A) int
    B) float
    C) str
    D) bool
    Answer: B) float — The single slash in Python 3 always does true division and returns a float, here 3.5. An int would come from 7 // 2, and the result is neither text (str) nor True or False (bool).
  5. Which format specifier prints a single character with printf() in C?
    A) %d
    B) %c
    C) %s
    D) %f
    Answer: B) %c — %c prints one char value. %d prints a decimal integer, %s prints a whole string, and %f prints a floating-point number.
  6. What does the Python statement print(23 // 4, 23 % 4) display?
    A) 5 3
    B) 5.75 3
    C) 6 3
    D) 5 4
    Answer: A) 5 3 — 23 = 4 × 5 + 3, so floor division gives 5 and the remainder is 3. 5.75 is the result of the single slash, 6 rounds the wrong way, and 4 is not the remainder.
  7. What does this C code print? int x = 9 / 2; printf("%d", x);
    A) 4.5
    B) 5
    C) 4.0
    D) 4
    Answer: D) 4 — Both operands are int, so C does integer division and discards the fraction: 9 / 2 = 4. 4.5 would need a floating-point operand, C does not round up to 5, and %d prints an integer with no decimal point.
  8. What does print(-9 // 2) display in Python?
    A) -4
    B) -4.5
    C) -5
    D) 4
    Answer: C) -5 — −9 ÷ 2 = −4.5, and Python’s floor division rounds down towards minus infinity, giving −5. −4 is what C’s truncation would give, −4.5 is the single-slash result, and the sign cannot be positive.
  9. In C (C99 or later), what does printf("%d", -9 % 4); print?
    A) -1
    B) 3
    C) 1
    D) -3
    Answer: A) -1 — C truncates −9 / 4 to −2, so the remainder is −9 − (−2 × 4) = −1; it takes the sign of the dividend. 3 is Python’s answer for -9 % 4, while 1 and −3 come from mixing up the signs.
  10. What does this Python code print? for i in range(2, 11, 3): print(i, end=" ")
    A) 2 5 8 11
    B) 3 6 9
    C) 2 5 8
    D) 2 4 6 8 10
    Answer: C) 2 5 8 — range(2, 11, 3) starts at 2 and adds 3 each time, giving 2, 5 and 8; the next value, 11, is not less than the stop value 11, so it is left out. Starting at 3 or stepping by 2 are misreadings of the arguments.
  11. Given s = "Karachi", what does print(s[1:4]) display?
    A) Kar
    B) arac
    C) ar
    D) ara
    Answer: D) ara — Indexing starts at 0, so index 1 is a, index 2 is r and index 3 is a; the slice stops before index 4. Kar starts at index 0, arac wrongly includes index 4, and ar stops one character early.
  12. What does this C code print? int a = 4; int b = a++ + 2; printf("%d %d", a, b);
    A) 4 6
    B) 5 6
    C) 5 7
    D) 4 7
    Answer: B) 5 6 — Post-increment uses the old value of a, so b = 4 + 2 = 6, and then a becomes 5. The output is a then b: 5 6. Using the new value 5 would give b = 7, and a cannot still be 4 after the increment.
  13. What does this Python code print? n = 1234; s = 0; while n != 0: s = s + n % 10; n = n // 10; then, after the loop, print(s)
    A) 4
    B) 10
    C) 24
    D) 4321
    Answer: B) 10 — Each pass adds the last digit (n % 10) to s and removes it (n // 10): s becomes 4, 7, 9 and 10, and then n is 0. The code finds the sum of the digits. 4 is only the first digit added, 24 is the product of the digits, and 4321 would be the reversed number.
  14. What does this Python code print? def f(a, b=3): return a - b; then print(f(10) + f(4, 1))
    A) 7
    B) 3
    C) 12
    D) 10
    Answer: D) 10 — f(10) uses the default b = 3 and returns 7; f(4, 1) uses b = 1 and returns 3; their sum is 10. 7 and 3 are only the two separate results, and 12 does not follow from the code.
  15. What happens when this Python code runs? i = 1; s = 0; while i != 10: s = s + i; i = i + 2; then, after the loop, print(s)
    A) The loop never stops, as i is never equal to 10
    B) It prints 25
    C) It prints 16
    D) It prints 0 without entering the loop
    Answer: A) The loop never stops, as i is never equal to 10 — i takes the odd values 1, 3, 5, 7, 9, 11 and so on, jumping over 10, so the condition i != 10 is always true and nothing is printed. 25 would be the sum 1 + 3 + 5 + 7 + 9 if the loop stopped after 9, 16 stops one value earlier, and the loop is entered because 1 is not 10.

Questions

Should I learn Python or C first?

Python is easier to start with because of its simple syntax and lack of declarations. C teaches how memory and data types work at a lower level. For exams, know the key differences between the two.

Why do Python and C give different answers for negative division?

Python’s // rounds down towards minus infinity, while C’s integer division truncates towards zero. The remainders then differ too, because each language keeps the rule that the quotient times the divisor plus the remainder equals the original number.

Does Python have ++ and -- operators?

No. Python uses x += 1 or x = x + 1. Writing ++x in Python is legal but just applies the plus sign twice and leaves x unchanged.

Is Python compiled or interpreted?

Python is usually described as interpreted: the standard interpreter first turns source code into bytecode and then executes it. C is compiled into machine code before it runs.