基本的Python斗争

时间:2017-12-03 13:24:41

标签: python

我正在制作数学技能测试课程,并想知道我是否可以在我的课程中出现随机问题而不必每次都这样做;

import time
start = time.time()
userinput = input("\nWhat is 11+7?")
if userinput=="18":
    print("\nNot bad, lets try something a little harder...")
    print('It took you {0:0.1f} seconds to answer the 
question'.format(time.time() - start))
else:
    print("\nAt least you got one right")
    print('It took you {0:0.1f} seconds to answer the 
question'.format(time.time() - start))
    exit()

另外,我如何在此添加while语句?如果可能的话,我还想添加一个def函数。感谢。

3 个答案:

答案 0 :(得分:0)

选择随机运算符和随机数:

import operator
import random

ops = {'+': operator.add,
       '-': operator.sub}  # add mul and div if you wish

keys_tuple = tuple(ops.keys())
num_a = random.randint(1, 10)  # use larger range if you wish
num_b = random.randint(1, 10)  # use larger range if you wish
op = random.choice(keys_tuple)

print('{}{}{}=?'.format(num_a, op, num_b))
expected_answer = ops[op](num_a, num_b)
user_answer = int(input())
if user_answer == expected_answer:
    print('Correct')
else:
    print('Wrong')

对于while,简单地将整个代码包装在while True循环中,如果用户输入某个值(即'quit'),该循环将会中断,这将导致{{1} }})

答案 1 :(得分:0)

所以你想基本上解决数学问题?以下是您需要做的事情:

制作两个随机的整数 - 第1步 看看答案是否与答案相符 - 第2步

您现在可以尝试自己解决它。如果您需要帮助,可以回来看看:

from random import randint

def get_random_int(): # Function to get random int
    random_num = randint(1, 20) #Gets an int between 1 and 20. Change if needed

    return random_num

def check_answer(first_number, second_number, input_ans): # function to check answer correction
  if (first_number + second_number == input_ans):
      return "Correct answer!"
  else:
      return "Try again!"

number_1 = get_random_int()
number_2 = get_random_int()

user_input = input("What is %s plus %s?" % ( str(number_1), str(number_2) ))
# Wrap in str() to display as string

print( check_answer(number_1, number_2, int(user_input) ) )
# Wrap in int() because it is a number

如果你需要不断循环,请将它包装在while True:无限循环中。一定要给出退出它的方法! (在代码中使用break退出循环)

希望这会有所帮助:)

答案 2 :(得分:0)

这几乎完全是@DeepSpace's代码,但要回答关于如何添加while循环的问题,只需将初始定义之后的所有代码抛出到{{1}的范围内} loop:

while