Login

Back

Generating numbers

Q1. Enter and run this code:

1.   print("Let's generate some numbers.")
2.   print('It will be fun ...')
3. 
4.   print("\n\nCounting ...")
5.   for i in range(10):
6.   print (i,end=" ")
7. 
8.   print("\n\nCounting in fives ...")
9.   for i in range(0,50,5):
10. print (i,end=" ")
11.
12. print("\n\nCounting backwards ...")
13. for i in range(10,0,-2):
14. print (i,end=" ")

Q2. When you use a print statement, there is a hidden <RETURN> at the end of the line. That's why line 2 prints on the next line. However, you can control what is at the end of a print line using end=" ". You can put all sorts of things inside the quotes. For example, try each one of these one at a time for line 1:

print("Let's generate some numbers.", end=" ")
print("Let's generate some numbers.", end="\t")
print("Let's generate some numbers.", end="\t\t\t\t")
print("Let's generate some numbers.", end="\n")
print("Let's generate some numbers.", end="\n\n\n\n")
print("Let's generate some numbers.", end="FISHFINGERS")

\t and \n are called escape sequences'. They are special codes that make Python do something e.g add a TAB or go to a new line. There are other ones. Search Google for some and try them out.
Q3. Line 5 uses a variable called i and the keyword range to produce a set of numbers. If you just use one number (called a parameter) in range, it will start at 0 and store that in i. Then it will go to line 6, where it prints out i. Then it loops back to line 5 again and gets the next value and puts that in i. Then it goes to line 6 and prints it. This continues until it reaches one less than the number in range. Python always starts at zero (unless you tell it not to) and always goes up to but doesn't include the value in range. 

    1. Produce a set of numbers from 1 up to and including 20.
    2. Produce a set of numbers from 1 up to and including 20 but all separated by a TAB.

Q4. You can start at any number number you like, and can go up in any step you like. How does line 9 work? Can you produce a 12 times table?

1 x 12 = 12
2 * 12 = 24 and so on up to 
12 * 12 = 144

Q5. You can also use a negative step. See line 13. Can you produce a 12 times table that starts:

12 * 12 = 144
11 * 12 = 132 and so on down to
1 * 12 = 12

Q6. Ask the user to enter any number. Produce for them a times table of that number for the first 12 numbers.

Q7. You should have a line similar to this one:

yourNumber = int(input("What number shall I use? >>> "))

What happens if you forget to use the int (   ) function? Explain the result.
Q8. Can you produce a times table for the first 120 numbers? (CNTL + C will stop the program running!). Ask your user what number they want to use in the times table.
Q9. Produce your times table for 120 numbers in reverse order. Ask your user what number they want to use in the times table.
Q10. Produce a times table for a number with a decimal part. Ask your user what number they want to use in the times table.