Both of the previous 2 answers have at least O(n) time complexity and the string conversion has O(n) space complexity too. Here's a solution for constant time and space:
num // 10 ** (int(math.log(num, 10)) - 1)
import math
def first_n_digits(num, n):
return num // 10 ** (int(math.log(num, 10)) - n + 1)
>>> first_n_digits(123456, 1)
1
>>> first_n_digits(123456, 2)
12
>>> first_n_digits(123456, 3)
123
>>> first_n_digits(123456, 4)
1234
>>> first_n_digits(123456, 5)
12345
>>> first_n_digits(123456, 6)
123456
You will need to add some checks if it's possible that your input number has less digits than you want.