Python tricks

Wikipedia Interaction Program

This program allows you to interact with Wikipedia in two ways:

Option A: Summary

Choose option A by typing “A”. Then, input a topic you’re interested in. The program will fetch a summary of that topic from Wikipedia and display it.

Select option B by typing “B”. Input a topic you want to search for. The program will provide you with a list of search results related to that topic on Wikipedia.

import wikipedia

def multiple_choice():
    print("A: summary, B: Search (Only Capital Letters)")
    aorb = input("Enter your choice:")
    if aorb == "A":
        print("What would you like a summary of:")
        topic = input("I would like a summary of:")
        print(wikipedia.summary(topic))
    else:
        print("What would you like a search of:")
        topic1 = input("I would like a search of:")
        print(wikipedia.search(topic1))

multiple_choice()


A: summary, B: Search (Only Capital Letters)
What would you like a summary of:
Ye ( YAY; born Kanye Omari West  KAHN-yay; June 8, 1977) is an American rapper, singer, songwriter, record producer, and fashion designer. Born in Atlanta and raised in Chicago, West gained recognition as a producer for Roc-A-Fella Records in the early 2000s, producing singles for several prominent artists and developing a production style that heavily sampled old-school soul music. With intent on pursuing a solo career as a rapper, he released his debut studio album, The College Dropout (2004), to critical and commercial success. He founded the record label GOOD Music later that year. West explored diverse musical elements like orchestras, synthesizers, and autotune on the albums Late Registration (2005), Graduation (2007), and 808s & Heartbreak (2008). His fifth and sixth albums My Beautiful Dark Twisted Fantasy (2010) and Yeezus (2013) were also met with critical and commercial success. West further diversified his musical styles on The Life of Pablo (2016) and Ye (2018) and explored Christian and gospel music on Jesus Is King (2019). His tenth album Donda (2021) was released to commercial success and mixed critical reception. West's discography also includes the two full-length collaborative albums Watch the Throne (2011) with Jay-Z and Kids See Ghosts (2018) with Kid Cudi.
One of the world's best-selling music artists, with over 160 million records sold, West has won 24 Grammy Awards and 75 nominations, the joint tenth-most of all time, and the joint-most Grammy awards of any rapper along with Jay-Z. Among his other awards are the Billboard Artist Achievement Award, a joint-record three Brit Awards for Best International Male Solo Artist and the Michael Jackson Video Vanguard Award. Six of West's albums were included on Rolling Stone's 2020 500 Greatest Albums of All Time list with the same publication naming him one of the 100 Greatest Songwriters of All Time. He holds the joint record (with Bob Dylan) for most albums (4) topping the annual Pazz & Jop critic poll. Time named him one of the 100 most influential people in the world in 2005 and 2015. As a fashion designer, he has collaborated with Nike, Louis Vuitton, Gap, and A.P.C. on clothing and footwear and led the Yeezy collaboration with Adidas. He is also the founder and head of the creative content company Donda.
West's outspoken views have received significant media coverage; he has been a frequent source of controversy due to his conduct on social media and at awards shows and public settings, as well as his comments on the music and fashion industries, U.S. politics, race, and slavery. His Christian faith, high-profile marriage to Kim Kardashian, and mental health have also been topics of media attention. In 2020, West launched an unsuccessful independent presidential campaign that primarily advocated for a consistent life ethic. In 2022, he was widely condemned and lost many sponsors and partnerships—including his collaborations with Adidas, Gap, and Balenciaga—after making a series of antisemitic statements. West later publicly praised Adolf Hitler, denied the Holocaust, and identified as a Nazi.
from typing import Union

# Define types for mean function, trying to analyze input possibilities
Number = Union[int, float]  # Number can be either int or float type
Numbers = list[Number] # Numbers is a list of Number types
Scores = Union[Number, Numbers] # Scores can be single or multiple 

def mean(scores: Scores, method: int = 1) -> float:
    """
    Calculate the mean of a list of scores.
    
    Average and Average2 are hidden functions performing mean algorithm

    If a single score is provided in scores, it is returned as the mean.
    If a list of scores is provided, the average is calculated and returned.
    """
    
    def average(scores): 
        """Calculate the average of a list of scores using a Python for loop with rounding."""
        sum = 0
        len = 0
        for score in scores:
            sum += score
            len += 1
        return sum / len
    
    def average2(scores):
        """Calculate the average of a list of scores using the built-in sum() function with rounding."""
        return sum(scores) / len(scores)

    # test to see if scores is  a list of numbers
    if isinstance(scores, list):
        if method == 1:  
            # long method
            result = average(scores)
        else:
            # built in method
            result = average2(scores)
        return round(result + 0.005, 2)
    
    return scores # case where scores is a single valu

# define a list of numbers
tests = [90.5, 100, 85.4, 88]

print("Print test data")
print(tests)

print()

print("Average score, long method")
print(mean(tests))

print("Average score, short method")
print(mean(tests, 2))
Print test data
[90.5, 100, 85.4, 88]

Average score, long method
90.98
Average score, short method
90.98