Python变量随机赋值方法及Pygame多选题测验技术问询
Hey there! Let's break down your two Python questions with practical, straightforward solutions:
1. How to assign random values to variables in Python?
The random module is your go-to here—pick the right function based on what type of random value you need:
Random integer: Use
random.randint(min, max)to get an integer betweenminandmax(inclusive). Example:import random lucky_number = random.randint(1, 100) # Assigns a random number from 1 to 100Random float:
random.random()gives a float between 0 and 1, whilerandom.uniform(min, max)lets you set a custom range:import random temperature = random.uniform(18.0, 25.0) # Random temp between 18°C and 25°CRandom choice from a list: Use
random.choice()to pick a random item from a sequence like a list or tuple:import random snacks = ["chips", "fruit", "yogurt"] random_snack = random.choice(snacks) # Randomly picks one snack optionRandom boolean: Quick way is
random.choice([True, False]), orbool(random.getrandbits(1))which generates a 0/1 and converts it to a boolean.
2. Tips for your Pygame multiple-choice quiz
Looking at your code skeleton, you're already off to a good start with random.choice() and tracking used questions with qUsed. Here are some practical improvements to make your quiz smoother:
Avoid repeating questions
Right now you have qUsed, but let's turn that into a robust function to grab unused questions (and reset when all are used):
from random import choice, shuffle import pygame qUsed = [] qEasy = [ { "question": "What year is it", "choices": {"a": "2009", "b": "2016", "c": "2010"}, "answer": "b" }, { "question": "Another Question 1", "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"}, "answer": "a" }, { "question": "Another Question 2", "choices": {"a": "choice 1", "b": "choice 2", "c": "choice 3"}, "answer": "a" } ] def get_new_question(): # Filter out questions already used available_questions = [q for q in qEasy if q not in qUsed] if not available_questions: print("All questions completed! Resetting...") qUsed.clear() available_questions = qEasy.copy() selected_q = choice(available_questions) qUsed.append(selected_q) return selected_q
Shuffle answer choices (for fairness)
Fixed answer positions can give away hints—shuffle them while keeping track of the correct answer:
def shuffle_options(question): # Convert choices to a list and shuffle it option_list = list(question["choices"].items()) shuffle(option_list) # Rebuild the choices dict and find the new correct key shuffled_options = {} correct_key = None for idx, (key, value) in enumerate(option_list): new_key = chr(ord('a') + idx) # Keep using a/b/c labels shuffled_options[new_key] = value # Check if this is the original correct answer if value == question["choices"][question["answer"]]: correct_key = new_key return shuffled_options, correct_key
Handle user input in Pygame
Add code to listen for keyboard presses (a/b/c) and check if the answer is right:
# Initialize Pygame pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("Simple Quiz") font = pygame.font.Font(None, 36) # Start with a random question current_question = get_new_question() shuffled_choices, correct_answer = shuffle_options(current_question) running = True while running: screen.fill((255, 255, 255)) # Draw the question text question_text = font.render(current_question["question"], True, (0, 0, 0)) screen.blit(question_text, (50, 50)) # Draw each shuffled choice y_pos = 150 for key, text in shuffled_choices.items(): choice_text = font.render(f"{key}: {text}", True, (0, 0, 0)) screen.blit(choice_text, (50, y_pos)) y_pos += 50 pygame.display.flip() # Handle events for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: user_input = event.unicode.lower() if user_input in shuffled_choices: # Check if answer is correct if user_input == correct_answer: print("Nice job, that's correct!") else: print(f"Oops, wrong answer. The correct one was {correct_answer}.") # Load next question current_question = get_new_question() shuffled_choices, correct_answer = shuffle_options(current_question) pygame.quit()
If you're hitting specific bugs (like text not showing up, or logic errors) feel free to share your full code and I can help debug further!
内容的提问来源于stack exchange,提问作者Moe

