我正在做一个Python程序。这基本上是一份问卷,我只是想知道是否有一种更短的方法来做这件事,因为现在我正在用不同的功能写出所有的问题。我想知道是否有一种替代的方法,在几乎一个函数中,这个函数只是重复,但问题和正确的答案每次都会发生变化。如果我不能做到这一点,有没有一种替代的方法来做到这一点,而不必为每个问题做单独的功能?是否有更快/更有效的方法来完成这一任务?
所有的建议将是非常感谢的,我已经贴上了前4个问题和下面代码的其余部分。我会有更多的问题,但我只是做了4个,这样它就不会占用太多的空间:)
import time
questionNumber = 0
right = 0
wrong = 0
name = str(input("Please Enter your name"))
print()
def questions():
def questionOne():
global right, wrong, questionNumber
print("What is the population of New Zealand?")
print("Is it A:6.7m B:3.2m C:5.1m or D:4.5m")
ans = str(input())
if ans == "D" or ans == "d" or ans == '4.5' or ans == '4':
print("You got it right!")
right = right + 1
else:
print("You got it wrong!")
wrong = wrong+1
questionNumber = questionNumber + 1
questionOne()
time.sleep(2)
print()
print("So far",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
print()
time.sleep(4)
def questionTwo():
global right, wrong, questionNumber
print("What year did the first european set foot on New Zealand (Abel Tasman)")
print("Is it A:1830 B:1543 C:1642 or D:1765")
ans = str(input())
if ans == "C" or ans == "c" or ans == '1642'or ans == '3':
print("You got it right!")
right = right + 1
else:
print("You got it wrong!")
wrong = wrong+1
questionNumber = questionNumber + 1
questionTwo()
time.sleep(2)
print()
print("So far ",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
print()
time.sleep(4)
def questionThree():
global right, wrong, questionNumber
print("How many Kiwi are there left in New Zealand (Approx)")
print("Is it A:2000 B:600 C:70,000 or D:100000")
ans = str(input())
if ans == "D" or ans == "d" or ans == '100000'or ans == '4':
print("You got it right!")
right = right + 1
else:
print("You got it wrong!")
wrong = wrong+1
questionNumber = questionNumber + 1
questionThree()
time.sleep(2)
print()
print("So far ",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
print()
time.sleep(4)
def questionFour():
global right, wrong, questionNumber
print("How many new babys where born in New Zealand in 2015")
print("Is it A:61,000 B:208,000 C:98,000 or D:18,000")
ans = str(input())
if ans == "D" or ans == "d" or ans == '100000'or ans == '4':S
print("You got it right!")
right = right + 1
else:
print("You got it wrong!")
wrong = wrong+1
questionNumber = questionNumber + 1
questionFour()
questions()发布于 2016-07-05 11:10:55
一些PEP8(这是Python的样式指南)对您的编码风格和格式进行了评论:
在方法之间,您应该有两个空行。
def questionOne():
....
def questionTwo():
....在PEP8中,建议:
使用函数命名规则:小写,必要时用下划线分隔单词,以提高可读性。
话虽如此,questionNumber将成为question_number
我见过很多人也使用camelCase作为变量,所以这是首选的问题。
同样的规则适用于您的方法:
questionOne() -> question_one()
在每个逗号(,)后面放一个空格。当你通过你的代码时,它真的很有帮助。
所以这个:
print("\nSo far ",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions\n")可改写为:
print("\nSo far ", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
questionNumber, "Questions\n")而不是right = right + 1,您可以使用增广赋值:right += 1。
更多,而不是这样做:
print()
print("So far",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions")
print()你可以:
print("\nSo far",name,"You have got",right,"Answers right,",wrong,"Answers wrong and you have completed",questionNumber,"Questions\n")我不喜欢您如何格式化上面的print(),但我稍后会再讨论它。
让我们看看到目前为止我提到的修改得到了什么:
import time
wrong = 0
right = 0
question_number = 0
name = str(input("Please Enter your name: "))
def questions():
def question_one():
global right, wrong, question_number
print("What is the population of New Zealand?")
print("Is it A:6.7m B:3.2m C:5.1m or D:4.5m")
ans = str(input())
if ans == "D" or ans == "d" or ans == '4.5' or ans == '4':
print("You got it right!")
right += 1
else:
print("You got it wrong!")
wrong += 1
question_number += 1
question_one()
time.sleep(2)
print("\nSo far", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
question_number, "Questions\n")
time.sleep(4)
def question_two():
global right, wrong, question_number
print("What year did the first european set foot on New Zealand (Abel Tasman)")
print("Is it A:1830 B:1543 C:1642 or D:1765")
ans = str(input())
if ans == "C" or ans == "c" or ans == '1642' or ans == '3':
print("You got it right!")
right += 1
else:
print("You got it wrong!")
wrong += 1
question_number += 1
question_two()
time.sleep(2)
print("\nSo far ", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
question_number, "Questions\n")
time.sleep(4)
def question_three():
global right, wrong, question_number
print("How many Kiwi are there left in New Zealand (Approx)")
print("Is it A:2000 B:600 C:70,000 or D:100000")
ans = str(input())
if ans == "D" or ans == "d" or ans == '100000' or ans == '4':
print("You got it right!")
right += 1
else:
print("You got it wrong!")
wrong += 1
question_number += 1
question_three()
time.sleep(2)
print("\nSo far ", name, "You have got", right, "Answers right,", wrong, "Answers wrong and you have completed",
question_number, "Questions\n")
time.sleep(4)
def question_four():
global right, wrong, question_number
print("How many new babys where born in New Zealand in 2015")
print("Is it A:61,000 B:208,000 C:98,000 or D:18,000")
ans = str(input())
if ans == "D" or ans == "d" or ans == '100000' or ans == '4':
print("You got it right!")
right += 1
else:
print("You got it wrong!")
wrong += 1
question_number += 1
question_four()
questions()尽量避免使用全局词。应该避免全局变量,因为它们会抑制代码重用。它们不好的原因是它们允许函数隐藏(如“不明显的”和“未声明的”),因此很难理解副作用。而且,这可能导致意大利面码。
正如您所看到的,您的函数几乎是相同的,所以您可以使用它并尝试创建一个方法。更重要的是,我们可以摆脱这种丑陋的内部方法的使用。只是在这种情况下没有必要。
我要做的是:
让我们看看我们有什么:
list_of_questions = ['What is the population of New Zealand ?',
'What year did the first european set foot on New Zealand (Abel Tasman) ?',
'How many Kiwi are there left in New Zealand (Approx) ?',
'How many new babys where born in New Zealand in 2015 ?']
lists_of_answers = [['A:1830', 'B:1543', 'C:1642', 'D:1765'],
['A:1830', 'B:1543', 'C:1642', 'D:1765'],
['A:2000', 'B:600', 'C:70,000', 'D:100000'],
['A:61,000', 'B:208,000', 'C:98,000', 'D:18,000']]
list_of_correct_answers = [['D', 'd', '4.5', '4'],
['C', 'c', '1642', '3'],
['D', 'd', '100000', '4'],
['D', 'd', '100000', '4']]
def questions():
wrong = 0
right = 0
for each_question, each_answer, each_correct_answer in zip(list_of_questions, lists_of_answers, list_of_correct_answers):
print(each_question + '\n' + ' '.join(each_answer))
get_answer = raw_input()
if get_answer in each_correct_answer:
print('Your answer is correct!\n')
right += 1
else:
print('That is not the answer I had in mind!\n')
wrong += 1
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Good luck!'.format(right, wrong))
if __name__ == '__main__':
questions()您可以看到,我还添加了if __name__ == '__main__':。我这么做的原因是,您还可以将代码作为模块导入到另一个脚本中,然后在程序决定时运行主函数。
下一步:
发布于 2016-07-05 12:09:15
我将在德克斯特的好答案上发表我的评论,因为他涵盖了我想要的大部分观点,但是我会尝试以一种稍微不同的方式来做一些细节。其中,正如Caridorc所指出的,我宁愿避免使用并行列表,使用更直接的方法。
question_list = [ # tuple of the form (question, answer list, correct answer list)
('What is the population of New Zealand ?',
['A:1830', 'B:1543', 'C:1642', 'D:1765'],
['D', 'd', '4.5', '4']),
('What year did the first european set foot on New Zealand (Abel Tasman) ?',
['A:1830', 'B:1543', 'C:1642', 'D:1765'],
['C', 'c', '1642', '3']),
('How many Kiwi are there left in New Zealand (Approx) ?',
['A:2000', 'B:600', 'C:70,000', 'D:100000'],
['D', 'd', '100000', '4']),
('How many new babys where born in New Zealand in 2015 ?',
['A:61,000', 'B:208,000', 'C:98,000', 'D:18,000'],
['D', 'd', '100000', '4']),
]
def questions():
wrong = 0
right = 0
for each_question, each_answer, each_correct_answer in question_list:
print(each_question + '\n' + ' '.join(each_answer))
get_answer = raw_input()
if get_answer in each_correct_answer:
print('Your answer is correct!\n')
right += 1
else:
print('That is not the answer I had in mind!\n')
wrong += 1
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Good luck!'.format(right, wrong))
if __name__ == '__main__':
questions()现在,通过拥有一个单一信息来源,事情可以得到改善。目前,一些信息(如正确的答案)在多个地方重复。它很容易弄错,而且你确实错了,因为最后一个正确的答案是:['D', 'd', '100000', '4']。另外,在实际数据和用于用户输入/输出接口的把问题分开之间,这也是一个很好的主意。
例如,根据以下代码:
from random import shuffle
question_list = [ # tuple of the form (question, dict of answers)
('What is the population of New Zealand ?',
{'6.7': False, '3.2': False, '5.1': False, '4.5': True}),
('What year did the first european set foot on New Zealand Abel Tasman ?',
{'1830': False, '1543': False, '1765': False, '1642': True}),
('How many Kiwi are there left in New Zealand Approx ?',
{'2000': False, '600': False, '70,000': False, '100000': False, '100000': True}),
('How many new babys where born in New Zealand in 2015 ?',
{'61,000': False, '208,000': False, '98,000': False, '18,000': True}),
]
def get_input_in_list(lst):
while True:
print("Please enter value from : " + " ".join(lst))
user_input = raw_input()
if user_input in lst:
return user_input
def questions():
wrong = 0
right = 0
for each_question, answer_dict in question_list:
answers = list(answer_dict)
shuffle(answers)
print(each_question)
user_answer = get_input_in_list(answers)
if answer_dict[user_answer]:
print('Your answer is correct!\n')
right += 1
else:
print('That is not the answer I had in mind!\n')
wrong += 1
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Good luck!'.format(right, wrong))
if __name__ == '__main__':
questions()通过更新get_input_in_list,您可以轻松地添加特性,通过字母/索引来选择答案,而不会干扰与您的问题/答案相对应的数据。
https://codereview.stackexchange.com/questions/133906
复制相似问题