2016-08-15 3 views
0
# -*- coding: utf-8 -*- 
""" 
fill-in-the-blanks1.py 

""" 

# -*- coding: utf-8 -*- 
""" 
p1 

""" 

level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be 
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can also be 
printed by the __1__ command. __4__ is the statement of true or false.''' 

level2 = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by 
adding ___2___ separated by commas between the parentheses. ___1___ by default return ___3___ if you 
don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary, 
tuple, and ___4___ or can be more complicated such as objects and lambda functions.''' 

level3 = '''__1__ , __2__ , __3__ , all belongs to the if statement. __1__ will be used at the beginning of the 
if statement, __2__ will be used in the middle between the __4__ and the __5__ statement. ''' 
variables1 = ["print", "def", "list", "boolean"] 
variables2 = ["function", "parameter", "false", "list"] 
variables3 = ["if", "elif", "else", "first"] 

d = "__1__" 
e = "__2__" 
f = "__3__" 
g = "__4__" 
h = "__5__" 
def replacevar(string, variable, inputa, finish): 
    string.split() 
    while True: 
     if inputa == variable[0]: 
      string = string.replace(d, inputa) 
      finish = "" 
      finish = finish.join(string) 
      return finish 
      break;  

     else: 
      print ("Your Answer is incorrect, pls try again") 
      return True 


level = input("Which level do you want to play? (1, 2 or 3)") 
if level == "1": 
    print (level1) 
    useranswer = input("Please enter the value for variable NO.1: ") 
    replacevar(level1, variables1, useranswer, finish1) 
    print (finish1) 

Python код, как описано выше, это только первая часть программы, которая просит вас заполнить пробел и заменить ..... словом вы ввели, если ваш ответ правильный. Но когда я запускаю программу, после того, как я набрал 1, вопрос показал, как и ожидалось, но после того, как я набрал «print» (без «») для ответа для первой переменной «», он не печатает строка с замещенными словами.код оленья кожа печати ничего

+0

Кажется, что-то отсутствует, переменная 'finish1' не определена нигде. – fjarri

ответ

0

Единственная проблема, которую вы использовали, если уровень == "1": замените ее, если уровень == 1: и это сработало.

""" 
    fill-in-the-blanks1.py 

    """ 

# -*- coding: utf-8 -*- 
""" 
p1 

""" 

level1 = '''The __1__ command can print out any types of a variable. __2__ defines a function that could be 
called out at any place in the document. A __3__ is a group of strings, variables or numbers. __3__ can also be 
printed by the __1__ command. __4__ is the statement of true or false.''' 

level2 = '''A ___1___ is created with the def keyword. You specify the inputs a ___1___ takes by 
adding ___2___ separated by commas between the parentheses. ___1___ by default return ___3___ if you 
don't specify the value to return. ___2___ can be standard data types such as string, number, dictionary, 
tuple, and ___4___ or can be more complicated such as objects and lambda functions.''' 

level3 = '''__1__ , __2__ , __3__ , all belongs to the if statement. __1__ will be used at the beginning of the 
if statement, __2__ will be used in the middle between the __4__ and the __5__ statement. ''' 
variables1 = ["print", "def", "list", "boolean"] 
variables2 = ["function", "parameter", "false", "list"] 
variables3 = ["if", "elif", "else", "first"] 

d = "__1__" 
e = "__2__" 
f = "__3__" 
g = "__4__" 
h = "__5__" 
def replacevar(string, variable, inputa, finish): 
    string.split() 
    while True: 
     if inputa == variable[0]: 
      string = string.replace(d, inputa) 
      finish = "" 
      finish = finish.join(string) 
      return finish 
      break;  

     else: 
      print ("Your Answer is incorrect, pls try again") 
      return True 


level = input("Which level do you want to play? (1, 2 or 3)") 
if level == 1: 
    print (level1) 
    useranswer = input("Please enter the value for variable NO.1: ") 
    replacevar(level1, variables1, useranswer, finish1) 
    print (finish1) 
+0

уровень 1 принимает int как вход, и вы использовали «1», который становится символом, поэтому он выполняет условие, если условие не было выполнено. –

1

Когда вы получите через плетень сделать 1-го уровня работы, я считаю, что структура вашей программы делает ее трудно получить другие уровни, чтобы работать, а не много избыточного кода. Я переработал его немного ниже, чтобы включить другие уровни - увидеть, если это дает вам какие-либо идеи в отношении продвижения вперед к вашей программе:

statements = { 
    "1": '''The __1__ command can print out any type of a variable. __2__ defines a function that 
could be called out at any place in the document. A __3__ is a group of strings, variables or numbers. 
__3__ can also be printed by the __1__ command. __4__ is a statement of true or false.''', 

    "2": '''A __1__ is created with the def keyword. You specify the inputs a __1__ takes by 
adding __2__ separated by commas between the parentheses. __1__ by default return __3__ if you 
don't specify the value to return. __2__ can be standard data types such as string, number, 
dictionary, tuple, and __4__ or can be more complicated such as objects and lambda functions.''', 

    "3": '''__1__ , __2__ , __3__ , all belong to the if statement. __1__ will be used at the beginning 
of the if statement, __2__ will be used in the middle between the __4__ and the __5__ statement.''', 
} 

answers = { 
    "1": [("__1__", "print"), ("__2__", "def"), ("__3__", "list"), ("__4__", "boolean")], 
    "2": [("__1__", "function"), ("__2__", "parameters"), ("__3__", "false"), ("__4__", "list")], 
    "3": [("__1__", "if"), ("__2__", "elif"), ("__3__", "else"), ("__4__", "first")], 
} 

def replacevar(string, answer, response, blank): 

    if response == answer: 
     return string.replace(blank, response) 

    return None 

level = input("Which level do you want to play? (1, 2 or 3) ") 

statement = statements[level] 

blanks = answers[level] 

print(statement) 

for (blank, answer) in blanks: 
    while True: 
     user_answer = input("Please enter the value for blank " + blank + " ") 

     finish = replacevar(statement, answer, user_answer, blank) 

     if finish is None: 
      print("Your Answer is incorrect, please try again") 
     else: 
      statement = finish 
      print(statement) 
      break 

print("Level completed!") 

Некоторые конкретные вопросы с вашим кодом: replacevar() имеет break, который никогда не будет достигнуто после return; replacevar() иногда возвращает логическую, а иногда и строку - она ​​должна возвращать строку или None, или она должна возвращать True или False, но не смешивать типы при возврате; ваша основная программа игнорирует результат replacevar(), который он не должен, поскольку он устанавливает вас для следующего пустого; вы split() строки, но не сохраняете результаты вызова, поэтому он не работает; вы вызываете join() на строку, когда она предназначена для вызова в массиве.

+0

Большое спасибо за ваш ответ, но я также хочу знать, что ни один из кода python не нуждается в ";" в конце? И имеет ли значение интервал, прежде чем вводить утверждения? –

+0

@AlanLin, конец точки с запятой оператора редко используется в Python и редко используется хорошо, даже если это так. Избегай это. Python несколько уникален тем, что интервал/отступ перед каждой строкой семантически значителен. Речь идет не столько о том, сколько интервалов/отступов, сколько о согласованности. – cdlane

Смежные вопросы