On 18/12/14 21:10, Abdullahi Farah Mohamud wrote:
hello i need help with a program and i dont understand what is wrong
Please always add a meaningful subject line.
when the computers asks the user if he would like to go again
> and the user says yes, it asks for the number of lines
> and then if the user clicks 3 it will only give
me one line.
import random
abz = 0
lines = int(input('How many lines would you like?'))
loop = lines
if lines >7:
You might want to check fpor negative numbers too
or you will loop forever.
print('Too many lines saaxib')
exit()
else:
print()
while lines != 0:
line1 = random.randint (1,7)
line2 = random.randint (8,14)
line3 = random.randint (15,21)
line4 = random.randint (22,28)
line5 = random.randint (29,35)
line6 = random.randint (36,42)
line7 = random.randint (43,49)
> lines = lines - 1
> print(line1, line2, line3, line4, line5, line6,line7)
Down to here basically works. But...
You could have used a list instead of all the
individual variables
line[0] = ...
line[1] = ...
But then you could get clever and use a loop:
while lines != 0:
start = 1
period = 7
for lineNum in range(7):
line[lineNum] = random(start,period)
start += period
period += period
print (*line)
lines -=1
while abz == 0:
again = input('Would you like to go again?')
if again == 'yes':
lines = int(input('How many lines would you like?'))
line1 = random.randint (1,7)
Notice this is outside the if statement so will execute
regardless of the answer.
But unlike the equivalent section above it is NOT in a
while loop so will only execute once per question.
Which is what you were seeing.
line2 = random.randint (8,14)
line3 = random.randint (15,21)
line4 = random.randint (22,28)
line5 = random.randint (29,35)
line6 = random.randint (36,42)
line7 = random.randint (43,49)
lines = lines - 1
print(line1, line2, line3, line4, line5, line6,line7)
Since you are duplicating code you could put it in a function - have you
seen functions yet?
def getLine(start=1, period=7):
line = []
for lineNum in range(7):
line[lineNum] = random(start,period)
start += period
period += period
return line
then the while loop becomes:
while lines != 0:
line = getLine()
print(*line)
lines -= 1
if again == 'no':
print('Okay the program is finished saaxib')
exit()
HTH
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor