简体   繁体   中英

how can I reduce my code? A lot of it is repetitive

The code creates a random addition problem and spits out "Congratulations" if correct and "sorry...." if the inputted value is wrong. The while loop repeats this process until the user inserts "N" for the question "continue (Y/N):, at the same time it keeps track of how many questions have been answered, and which ones are correct. The code works fine, my problem is it has repetitive code. I was wondering if there is a way to shrink it.

**I appreciate everyone one's help and advice. I"ma noob that's just learning python **

import random

correct=0
count=1
num1=random.randint(0,100)
num2=random.randint(0,100)
print(format(num1,'4d'))
print('+',num2)
answer=int(input('='))
sum=num1+num2

if answer==sum:
    print('Congraulations!')
    correct+=1
else:
    print('Sorry the correct answer is',sum)
c=input('Continue (Y/N):')

while c == "Y":

    count+=1
    num1=random.randint(0,100)
    num2=random.randint(0,100)
    print(format(num1,'4d'))
    print('+',num2)
    answer=int(input('='))
    sum=num1+num2
    if answer==sum:
        print('Congraulations!')
        correct+=1
    else:
        print('Sorry the correct answer is',sum)
    c=input('Continue (Y/N):')

else:
    print('Your final score is',correct,'/',count)

By initializing the variable c as "Y", the condition is met and the loop can be executed:

import random
correct=0
count=1
c = "Y"
while c == "Y":
    count+=1
    num1=random.randint(0,100)
    num2=random.randint(0,100)
    print(format(num1,'4d'))
    print('+',num2)
    answer=int(input('='))
    sum=num1+num2
    if answer==sum:
        print('Congraulations!')
        correct+=1
    else:
        print('Sorry the correct answer is',sum)
    c=input('Continue (Y/N):')
    c = c.upper()

else:
    print('Your final score is',correct,'/',count)

I also added the method upper() to the Y/N input so the user can also type it in lowercase

Try to move as much of the processing as possible into the loop. The first "paragraph" of your code was basically a duplicate of the main-loop. By creating the continuation variable c so that it drops straight into the loop, most of that first block could be removed.

import random

correct=0
count=0
c = 'Y'

while c == "Y":

    count+=1
    num1=random.randint(0,100)
    num2=random.randint(0,100)
    print(format(num1,'4d'))
    print('+',num2)
    answer=int(input('='))
    sum=num1+num2
    if answer==sum:
        print('Congratulations!')
        correct+=1
    else:
        print('Sorry the correct answer is',sum)
    c=input('Continue (Y/N):')

else:
    print('Your final score is',correct,'/',count)

The two formula printing statements can also be reduced to a single one:

    print(format(num1,'4d'))
    print('+',num2)

could be

    print( format(num1,'4d') + '+', num2 )

The variable sum could be removed, but it does make the code self-documenting, which is a good thing.

A first start, would be eliminating the code before the while , by initializing the count variable (which keeps track of the turns), in zero, and allowing the while loop to run the first turn, we just need to have a variable like want_to_play and by default it's True , so the first time we'll be playing, and at the end of the game If I don't input Y or y it will asume I don't want to play any more and set the variable to false, that way I can have all the turns ran by the while loop.

and you'll be getting something like this.:

from random import sample

correct = 0
count = 0           # STartint in turn zero
want_to_play = True # Control Variable

while want_to_play:
    count += 1 
    # First turn this is zero, and adds one.

    [num1, num2] = sample(range(0, 101), 2)
    # Just another way of getting two random numbers from 1 up to (including) 100.
    # Printing could be done in one line. 
    print(format(num1, '5d') + '\n+' + format(num2, '4d'))
    answer = int(input('= '))
    # The comparison really doesn't really hurt if you do it this way. 
    if answer == num1 + num2:
        print('Congraulations!')
        correct += 1
    else:
        print('Sorry the correct answer is', sum)

    # HERE you ask if you want to play again or not, using a one line if
    # you decide.
    want_to_play = (True if 'y' == input('Continue (Y/N).lower():') 
                         else False)
else:
    print('Your final score is',correct,'/',count)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM