NameError: имя ‘переменной’ не определено Python

#python #variables #append

#python #переменные #добавить

Вопрос:

Итак, я не профессионал в python, и я застрял на ошибке, когда я создаю программу, вот код

 # A game that will tell that the news is fake or not.

# Welcome message
print("Want to know that a news is fake or not?nYou are at a right place. Welcome to FakeNewsDetector.orgnAt here we provide the news which is not fake and you can add more news if you want!!nSo are you excited? Let's get startedn")

# User input   print for input
print("What thing you want do?")
print("1: Ask a news is fake or not?n2: Tell a news it is fake or notn")
number = int(input("We will answer your question just enter the number. Press ctrl c anywhere if you want to exit: "))

# if then else



# Appending part
if number == 2:
    number = int(input("What is the number of news you are adding?: "))
    whatAreYouTelling = input("What news you want to say? Not include that the news is false or true: ")
    with open('news.txt', 'a') as f:
        a = f.write(f"n{number}: {whatAreYouTelling}")
    
    trueOrFalse = input("Is the fact true(T) or false(F)?")
    if trueOrFalse == "t" or trueOrFalse == "T":
        fact = True

    elif trueOrFalse == "f" or trueOrFalse == "F":
        fact = False

    else:
        print("Invalid") 



# Reading part
elif number == 1:
    with open('news.txt', 'r') as f:
        a = f.read()
        print(a)

    news = int(input("What news do you want to ask? Enter number: "))

    if news == 1:
        fact = False
        print(f"The news is {fact}.")

    elif news == 2:
        fact = True
        print(f"The news is {fact}")

    elif news > 2:
        print(f"{trueOrFalse}")
else:
    print("Invalid")

# print("nThanks for using our news service. I hope you like itn Created by Anant Guptan Class 7Dn Homework: ATL")
 

И когда я запускаю свой код и добавляю случайное значение, возникает ошибка, подобная этой

 [anant@anant-hpprobook440g4 atlProject]$ python -u "/home/anant/Desktop/anant/codingPlayground/pythonProject/atlProject/main.py"
Want to know that a news is fake or not?
You are at a right place. Welcome to FakeNewsDetector.org
At here we provide the news which is not fake and you can add more news if you want!!
So are you excited? Let's get started

What thing you want do?
1: Ask a news is fake or not?
2: Tell a news it is fake or not

We will answer your question just enter the number. Press ctrl c anywhere if you want to exit: 2
What is the number of news you are adding?: 3
What news you want to say? Not include that the news is false or true: Hello I am nothing
Is the fact true(T) or false(F)?F
[anant@anant-hpprobook440g4 atlProject]$ python -u "/home/anant/Desktop/anant/codingPlayground/pythonProject/atlProject/main.py"
Want to know that a news is fake or not?
You are at a right place. Welcome to FakeNewsDetector.org
At here we provide the news which is not fake and you can add more news if you want!!
So are you excited? Let's get started

What thing you want do?
1: Ask a news is fake or not?
2: Tell a news it is fake or not

We will answer your question just enter the number. Press ctrl c anywhere if you want to exit: 1
1: Obama tweeted 'ashamed to shake hands with Modi'
2: Kamala Harris hasn't attacked Indian government on farmers
3: Hello I am nothing
What news do you want to ask? Enter number: 3
Traceback (most recent call last):
  File "/home/anant/Desktop/anant/codingPlayground/pythonProject/atlProject/main.py", line 51, in <module>
    print(f"{trueOrFalse}")
NameError: name 'trueOrFalse' is not defined
[anant@anant-hpprobook440g4 atlProject]$ 
 

Я не очень хороший программист, но, пожалуйста, примите мой фрагмент кода. Я работаю в течение 1 часа и не могу устранить ошибку. Если кто-нибудь решит, я буду очень благодарен. Заранее спасибо

Ответ №1:

TrueOrFalse область действия ограничена вашим первым if блоком. Чтобы сделать его доступным в вашем втором блоке, вам нужно объявить его вне ваших if операторов, например, установив для него значение False first .

Комментарии:

1. Спасибо, но как я установлю его значение в true, когда я введу True? Оно может быть доступно только для ложных значений

2. @AnantGupta это структурная проблема с вашим кодом, а не просто синтаксическая ошибка.

3. @stenlal Поэтому, пожалуйста, не могли бы вы предоставить полный код? Я буду очень рад 🙏