Looking to condense python code for a math game (Very new to python)

import random

correct_g = 0
incorrect_g = 0

while True:
    user_input = input('Would you like to add, sub, multi? type "end" to end the game : ').lower()

    if user_input == 'add':
        number1: int = random.randrange(1, 100)
        number2: int = random.randrange(1, 100)
        add_answer = number1 + number2
        print(number1, ' + ', number2)
        add_question = input('What is the sum of these two numbers? ')
        if int(add_question) == add_answer:
            print('That is correct!')
            correct_g += 1
            pass

        else:
            print('Incorrect. whomp whomp:(')
            incorrect_g += 1
            pass

    elif user_input == 'sub':
        number3: int = random.randrange(1, 100)
        number4: int = random.randrange(1, 100)
        sub_answer = number3 - number4
        print(number3, ' - ', number4)
        sub_question = input('What is the sum of these two numbers? ')
        if int(sub_question) == sub_answer:
            print('That is correct!')
            correct_g += 1
            pass

        else:
            print('Incorrect. whomp whomp:(')
            incorrect_g += 1
            pass


    elif user_input == 'multi':
        number5: int = random.randrange(1, 100)
        number6: int = random.randrange(1, 100)
        multi_answer = number5 * number6
        print(number5, ' * ', number6)
        multi_question = input('What is the sum of these two numbers? ')
        if int(multi_question) == multi_answer:
            print('That is correct!')
            correct_g += 1
            pass

        else:
            print('Incorrect. whomp whomp:(')
            incorrect_g += 1
            pass

    elif user_input == 'end':
        print('You got ', correct_g, ' questions right!')
        print('You got ', incorrect_g, ' questions wrong.')
        print('Thank you for playing!')
        break

    else:
        print('I do not understand.')
        pass

I’m looking for ways to condense some the if, elif, and number generators. I feel like copy/paste and changing a few words if very inefficient way of creating branches off the first user_input. I’m not to sure how else to do it, and I’m willing to start from scratch if someone recommends a lesson for me to look up and learn from.

New contributor

Jacob Graves is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

You are creating two random numbers between 1,100 regardless of choice. Why not just create them before the choices and always use number1 and number2? You are right copy and pasting code is often a bad sign.

You can create a function that is more flexible and takes the choice as input to create the branches.

import random

def branch(sign):
    if sign=="end":
        return -1
    global correct_g, incorrect_g
    number1 = random.randrange(1, 100)
    number2 = random.randrange(1, 100)
    
    def sub(a, b):
        return a - b

    def add(a, b):
        return a + b

    def multi(a, b):
        return a * b

    # Functions as dict values
    sign2func = {
        "sub": sub,
        "add": add,
        "multi": multi
    }
    
    sign2symbol = {
        "sub": "-",
        "add": "+",
        "multi": "*"
    }
    
    sign2operation = {
        "sub": "difference",
        "add": "sum",
        "multi": "product"
    }

    # Call the appropriate function from the dictionary
    sub_answer = sign2func[sign](number1, number2)

    print(f"{number1} {sign2symbol[sign]} {number2}")
    sub_question = input(f'What is the {sign2operation[sign]} of these two numbers? ')
    
    if int(sub_question) == sub_answer:
        print('That is correct!')
        correct_g += 1
    else:
        print('Incorrect. whomp whomp:(')
        incorrect_g += 1

correct_g = 0
incorrect_g = 0

while True:
    user_input = input('Would you like to add, sub, multi? Type "end" to end the game: ').lower()
    print(user_input)
    if user_input == "end":
        break
    try:
        res=branch(user_input)
        if res==-1:
            break
    except KeyError:
        print('I do not understand.')

instead of using 3 dictionaries, you could join them into one dictionary that has a list as value and then pic the right value out of the list.

Nice work so far, Jacob. The next thing to do is to get familiar with Python’s functions and see if you can break off pieces of your program into functions – it can be kind of like getting Python to do that code copying that you were talking about for you!

You could put each of the branches into its own function, or you could look for common functionality and move that into their own function. For example, to create a pair of random numbers you could write:

def random_pair(max=100) -> (int, int):
  return (random.randint(1, max), random.randint(1, max))

You probably want to use randint() for your game, so you get integers. Good luck, and keep it up!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật