Can you write a program that alters another program semantically?
Your idea fails (assuming all P are allowed), and that's not by accident.


You can not find an input for with P halts in finite time.
P may never halt, in which case that line in your program loops;
thus, the program behaves exactly the same as P.
You can skip finding k and do

alter(P, x) =
  P(x) + 1


This is the same idea as you have (note how it alters the semantics on
 all inputs on which P halts) but does not require us to find
 an input on which P halts.

However, it's still fails for the never-halting program -- but, at least,
 only that one!
What if we just output 1 or any other value sometimes?
 That takes care of never-halting P, but for each such
 hack with a static, computable "abort and output c"-criterion
 -- that includes runtime bounds! -- we can build easy counterexamples.
 Idea: if ( criterion ) then c else something.


So that looks bad; we can't compute uncomputable criteria! And we have to "decide"
after finite time for any fixed x (otherwise the never-halting P skrews us).

When prospects are this bleak, it's sometimes wise to try the other direction.
What if the problem can not be solved, that is alter does not exist?
In fact, given sufficient background in computability, it is clear that such
a function can not exist.

Assume any computable, total function $\mathtt{alter} : \mathbb{N} \to \mathbb{N}$.
We understand natural numbers as (the numbers of) programs in some
Turing-complete programming language $\phi$.
More specifically, let $\phi$ be a suitable numbering of all (partially) computable functions; 
we then denote by $\phi_i$ the function computed by program $i$.

Now, by Kleene's recursion theorem
there is some index (program) $i^*$ so that $\varphi_{i^*} = \varphi_{\mathtt{alter}(i^*)}$, 
that is $\mathtt{alter}$ has no effect on $i^*$, semantically. 
Stronger versions show that there are infinitely many such $i^*$ so there's no hope fixing this.

In summary, no such program alter that works on all input programs can exist.

If you allow only P that halt for at least some x, your approach works; the proof is elementary (show that alter is computable, and that alter(P)(k) != P(k) for some k).