Outputs of a program

I am new to programming and I would like to know how to solve questions like this. I was told to expect questions like this on the exam. Can someone please tell me how I would go about solving something like this? Thanks.

x = 0
for num in range(5):
    if num % 2 == 0:
        x = x + 2
    else:
        x = x + 1
        print(x)

Answers


You need to work on a skill which is to "be the compiler", in the sense that you should be able to run code in your head. Step through line by line and make sure you know what is happening. In you code example, you have for num in range(5) means you will be iterating with num being 0,1,2,3 and 4. Inside the for loop, the if statement num % 2 == 0 is true when num/2 does not have a remainder (how % mods work). So if the number is divisible by 2, x = x+2 will execute. The only numbers divisible by 2 from the for loop are 0,2 and 4. so x=x+2 will execute twice. The else statement x = x +1 runs for all other numbers (1,3) which will execute 2 times.

Stepping through the for loop:

num = 0 //x=x+2, x is now 2
num = 1 //x=x+1, x is now 3, print(x) prints 3 
num = 2 //x=x+2, x is now 5
num = 3 //x=x+1, x is now 6, print(x) prints 6
num = 4 //x+x+2, x is now 8

Therefore the answer is that 3 and 6 will be printed


In my opinion,

  1. Whatever language you are using, you need to learn some common elements of the modern programming languages, such as flow-control (if...else in your case), loop(for, in your case)

  2. Some common used functions, in your case, you need to what does range do in Python, docs.python.org is a good place for you.

As you are new to programming, you can go with the flow in you mind or draw it on the paper.

  1. Using x to store our final result
  2. loop through every item in [0, 1, 2, 3, 4] <- range(5)

    a. if the number is divisible by 2 then increase x by adding 2 to it.

    b. else increase x by adding 1 and print it out

So the result would be :

3

6


Need Your Help

PHP file_exists sometimes returns false for a file on CIFS share

php linux share mount cifs

I have a CIFS share from Windows Server 2012 R2 mounted on Ubuntu 14.04.2 LTS (kernel 3.13.0-61-generic) like this

JQuery not a function error

javascript jquery firebug

While developing with Firebug I keep getting this error.