Python, Loops, Multiples - python

I cannot figure out what I am doing wrong; I keep getting a traceback error.
Can someone tell me what I am doing wrong or point me in the right direction, please?
Multiples = str(input('Multiples of 13 from 200 to 100'))
for counter in range(max):
for i in reversed(list(range(100,201))):
if i%13==0:
print(i,'total','*= 13')
list1 = {}
for j in list(range(2,i+1)):
if i%j == 00:
list1 = []
print(list1)
I am trying to get the output to look like the following:
Multiples of 13 from 200 to 100
195 = 13 times 15
182 = 13 times 14
169 = 13 times 13
156 = 13 times 12
143 = 13 times 11
130 = 13 times 10
117 = 13 times 9
104 = 13 times 8
Also, could someone tell me how to enter code in this block, because each time I click on the code or CTRL-K my format is off?

I feel like you're overcomplicating things..
output = []
x = 0
while True:
if 13 * x > 200:
break
output.append('{0} = 13 times {1}'.format(13*x, x))
x += 1
for x in reversed(output):
print(x)
Output
195 = 13 times 15
182 = 13 times 14
169 = 13 times 13
156 = 13 times 12
143 = 13 times 11
130 = 13 times 10
117 = 13 times 9
104 = 13 times 8
91 = 13 times 7
78 = 13 times 6
65 = 13 times 5
52 = 13 times 4
39 = 13 times 3
26 = 13 times 2
13 = 13 times 1
0 = 13 times 0

There are actually quite a few things that are preventing the output from looking like you want it to:
In Multiples = str(input('Multiples of 13 from 200 to 100')), asking for input prompts the user to input a number, and will then assign that input to Multiples.
You're not actually printing Multiples of 13 from 200 to 100.
max is not a number, so you can't call range on it. I've assumed you haven't defined max elsewhere, of course, so if you have, kindly update your code to include it.
print(i,'total','*= 13') will print <number> total *=13. This does not remotely resemble the output you want.
You never actually insert anything into list1 before printing it. Even if you did, it would appear inside a list so it would look like [<element>].
Since the code as provided is not a minimal complete and verifiable example that would let us pinpoint your exact error, I suspect you will need to rewrite your code from scratch - as written, none of it conforms to the output you want to get. This is far more complicated than it has to be in any case.
All you have to do is
Go through the numbers 201, 200, ... 100
Check if each number is divisible by 13
Use the handy division operator / to get the value of the number divided by 13 as a float (a decimal number) and convert it to integer by using int().
Here's a minimal example of the right way to do this:
print('Multiples of 13 from 200 to 100') # prints this string
for i in range(201,100,-1): # iterate through 201, 200, 199 ... 100
if i % 13 == 0: # checks if number is divisible by 13 ...
# prints out the result of number divided by 13 in the format you want
print(i, '= 13 times', int(i/13))

Related

Creating a grid of numbers in python using a list

I am trying to write a program that accepts a number , n. The program will print out the numbers n to n+41 as 6 rows of 7 numbers. The first row will contain the values n to n+6, the second , the values n+7 to n+7+6 and so on.
Sample I/O:
Enter the start number: -2
-2 -1 0 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 32
33 34 35 36 37 38 39
The sample I/O looks a little weird on here but I'm sure you can see it.
I understand how to use nested loops to make a triangle but I cannot understand how to print it in a square with the next line have the previous line's value + 1.
Any help would be much appreciated
The first for loop is the key to your problem. It starts at the number entered and goes to that number plus 40 in steps of 6.
starter = int (input ('Enter a number : '))
for x in range (starter, starter + 40, 6) :
for y in range (6) :
print (x + y, end = ' ')
print ()
Before giving you a possible solution, I suggest you carefully read the lots of information about the Python language that there is both on StackOverflow and, in general, on the internet.
You will probably find answers to your questions simply by reading.
This could be one of the methods, if I understand the question correctly, to get the output you want:
# WITHOUT LIST
n = int(input('Enter the start number: '))
printed_values = 0
row_lenght = 7 # values for row
print('\nOUTPUT:\n')
for i in range(n, n+42, 1):
print(i, end='\t')
printed_values += 1
if not printed_values%row_lenght:
#a row is printed, reset printed_values
printed_values = 0
print('\n')
# WITH LIST
n = int(input('Enter the start number: '))
row_lenght = 7 # values for row
values = list(range(n, n+42, 1))
print('\nOUTPUT:\n')
for i in range(0, len(values), row_lenght):
for value in values[i:i+row_lenght]:
print(value, end='\t')
print('\n')

How do I create a horizontal multiplication table in Python?

So far I have tried to create a table of the first 6 multiples of 2 that should give:
2 4 6 8 10 12
My code for this currently looks like:
i = 1
while i <= 6:
print(2*i ,' \t' , )
i = i + 1
But this outputs them vertically, not horizontally so:
2
4
6
8
10
12
There is also a tab after each number.
You can use a simple for-loop as they are more Pythonic for this application than while loops.
So just loop through the numbers between 1 and 6 and print that number multiplied by 2 with a space instead of the new-line character. Finally, you can call one more print at the end to move to the next line after they have all been printed.
for i in range(1, 7):
print(i * 2, end=' ')
print()
which outputs:
2 4 6 8 10 12
If you wanted do this whole thing in one-line, you could use a generator and string.join(). You may not fully understand this, but the following produces the same result:
print(" ".join(str(i*2) for i in range(1, 7)))
which gives:
2 4 6 8 10 12
Note that one last thing is that this method doesn't produce a uniformly spaced table. To show what I mean by "uniformly spaced", here are some examples:
not uniformly spaced:
1234 1 123 12 12312 123
uniformly spaced:
1234 1 123 12 12312 123
To make the output print nicely like above, we can use .ljust:
print("".join(str(i*2).ljust(3) for i in range(1, 7)))
which gives a nicer table:
2 4 6 8 10 12
Finally, if you wanted to make this into a function that is more general purpose, you could do:
def tbl(num, amnt):
print("".join(str(i*num).rjust(len(str(num*amnt))+1) for i in range(1,amnt+1)))
and some examples of this function:
>>> tbl(3, 10)
3 6 9 12 15 18 21 24 27 30
>>> tbl(9, 5)
9 18 27 36 45
>>> tbl(10, 10)
10 20 30 40 50 60 70 80 90 100
Change your print statement to be like this: print(2*i, end=' \t') The end key argument sets what the ending character should be. By default, it's a newline, as you know.

Check a variable is a multiple of 10

I need my program to check an in putted variable (e_gtin) and then calculate the GTIN from it (times the 1,3,5 and 7th number by three then add the 7 numbers up and divide by the nearest 10 times table) So far, it times the numbers and adds them up but I don't know where to go from there in terms of making it a multiple of ten
In Addition i eventually used this code
calculator = int(e_gtin[0])*3+int(e_gtin[1])+\
int(e_gtin[2])*3+int(e_gtin[3])+\
int(e_gtin[4])*3+int(e_gtin[5])+\
int(e_gtin[6])*3
rounding = round(calculator+4)
The plus 4 is so the variable will always round up rather than rounding down (The GTIN calculation specifies this)
e_gtin being an inputted 7 digit GTIN code.
Thanks go to --->
https://stackoverflow.com/users/906693/roadrunner66
You are presumably asking about calculating the check-digit on a GTIN8 number. An explanation is given here http://www.gs1.org/how-calculate-check-digit-manually
e = input("Enter a 7 digit number - ")
# note: an integer number can not be accessed like a string or list,
# make it a string first
e=str(e)
sum= int(e[0])*3+int(e[1])+\
int(e[2])*3+int(e[3])+\
int(e[4])*3+int(e[5])+\
int(e[6])*3
checkdigit = 9 - (sum-1) % 10
print sum,checkdigit
To understand the working of a the modulo operator, just play with it, make yourself a table etc.
import numpy as np
sums=np.array([50,51,52,53,54,55,56,57,58,59,60,61])
print sums
print sums % 10
print 10 - sums % 10 # all results right except for 10s which should be zeros
print 10 - (sums-1) % 10 -1
output:
[50 51 52 53 54 55 56 57 58 59 60 61]
[0 1 2 3 4 5 6 7 8 9 0 1]
[10 9 8 7 6 5 4 3 2 1 10 9]
[0 9 8 7 6 5 4 3 2 1 0 9]

Why can't I find max number in a file like this?

I'm quite new to python, though I have a lot of experience with bash. I have a file that consists of a single column of numbers, and I would like to find the largest number in the list. I tried to do so with the following code:
i = 0
with open('jan14.nSets.txt','r') as data:
for num in data:
if num > i:
i = num
print(i)
where jan14.nSets.txt is the following:
12
80
46
51
0
64
37
9
270
23
132
133
16
6
18
23
32
75
2
9
6
74
44
41
56
17
9
4
8
5
3
27
1
3
42
23
58
118
100
185
85
63
220
38
163
27
198
Rather than 270, I receive 9 as an output, and I do not understand why this is the case. I know that there are builtins for this, but I would like to know why this doesn't work to help me understand the language. I am using python2.7
num is a string, not a number. Turn it into an integer first using int():
num = int(num)
You are comparing text, so it is ordered lexicographically, '9' > '80' because the ASCII character '9' has a higher codepoint than '8':
>>> '9' > '80'
True
After the '9' line, all other lines either have an initial digit that is smaller than '9', or the line is equal.
You could use the max() function instead, provided you first use map() to turn all lines into integers:
with open('jan14.nSets.txt','r') as data:
i = max(map(int, data))
or use a generator expression (in Python 2, more memory efficient than map()):
with open('jan14.nSets.txt','r') as data:
i = max(int(num) for num in data)
Both pull in all lines from data, map the lines to integers, and determine the maximum value from those.

Can anyone help me figure out the parsing error in this code?

The output of this code is quite similar but not exactly what it's supposed to be.
The code is:
def printMultiples(n):
i = 1
while (i <= 10):
print(n*i, end = ' ')
i += 1
n = 1
while (i<= 3):
printMultiples(n)
n += 1
The output is:
1 2 3 4 5 6 7 8 9 10 2 4 6 8 10 12 14 16 18 20 3 6 9 12 15 18 21 24 27 30
Whereas it should be like:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
How should this code be modified?
add an empty print at the end of the printMultiples, outside the while (i <= 10): loop.
Your problem is that you are not printing a new line after each list of multiples. You could solve this by putting at the end of your printMultiples function outside of the loop the line
print()
To make the columns line up, you will need to completely change your approach. Currently, printMultiples() cannot know how many spaces to put after each number because it doesn't know how many times it will be called in the outer while loop.
What you might do is:
create a two dimensional array of string representations for each multiple (without printing anything yet) - the str() function will be useful for this
for each column, check the length of the longest number in that column (it will always be the last one) and add one
print each row, adding the appropriate number of spaces after each string to match the number of spaces required for that column
A simpler approach, if you're only interested in columnar output and not the precise spacing, would be to print each number with enough space after it to accommodate the largest number you expect to output. So you might get:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
(Note how there are three spaces after each number in the first three columns even though you don't need all three spaces.)
Changing your existing code to do that would be easier. See Format String Syntax for details.
If you already know you wish to pad numbers to be of width 3, then a suitable (and more pythonic) printMultiples is
def printMultiples(n):
txt = "".join(["{0: <3d}".format(n*i) for i in range(1, 11)])
print(txt)
Better would be to allow the width to change. And you could then pass a width you prefer as, eg, the width of the largest number you expect
def printMultiples(n, width=3):
txt = "".join(["{0: <{1}d}".format(n*i, width) for i in range(1, 11)])
print(txt)
width = len(str(4 * 10)) + 1
for i in range(1, 4):
printMultiples(i, width )

Categories

Resources