While true python ошибка

Here’s my script:

def makeithappen():
    word=""
    while True:
        try:
            word=inputText()
        except:
            print("Something happened inputText")
        else:
            if len(word)>0:
                break
            elif word!=str:
                break 

For some reason however I get an invalid syntax error and I am not sure why.

halfer's user avatar

halfer

19.8k17 gold badges98 silver badges185 bronze badges

asked Nov 25, 2016 at 6:20

Sean Gurdon's user avatar

18

def makeithappen():
   word=""
   while True: 
       try:
           word=input() #is this supposed to be input()?
       except:
           print("Something happened inputText")
       else: 
           if len(word)>0:
               break
           elif isinstance(word, basestring): #I never got the logic behind it 
               break 

I think this is what you wanted to do. It exits if entered text is valid (length is more than 0) and input type is not of str (which is always false in case of python3).

answered Nov 25, 2016 at 6:42

Prajwal's user avatar

PrajwalPrajwal

3,9105 gold badges24 silver badges48 bronze badges

2

#!/usr/bin/python
# -*- coding: utf-8 -*-

def makeithappen():
   word=""
   while True:
        try:
           word=raw_input("Go:")
        except:
           print("Something happened inputText")
        else:
           if len(word)>0:
              print("Hello!!")
           elif word!=str:
              print("Bye!!")
              break
makeithappen()

answered Nov 25, 2016 at 7:22

vcmsxs's user avatar

vcmsxsvcmsxs

1012 bronze badges

Вот код

While True:
		data = await input_group(" Новое сообщение", [
			input(placeholder="Текст сообщения", name = msg)
			actions(name="cmd", button = ["Отправить", {'label':"Выйти из чата", "type":"cancel"}])
		], validate=lambda m: ("msg", "Введите сообщение") if m["cmd"]=="Отправить" and not m["msg"] else None)

		if data is None:
			break 

		msg_box.append(put_markdown(f"`{nickname}`:{data["msg"]}"))
		chat_msgs.append((nickname, data["msg"]))

	refresh_task.close()
	online_users.remove(nickname)
	toast("ББ ты вышел из чатикса")
	chat_msgs.append((""), f"`{nickname}` вышел из чатикса")
	msg_box.append(put_markdown(f"`{nickname}` вышел из чатикса"))

Почему-то While True у меня является ошибкой синтаксиса
Ошибка

While True:
          ^^^^
SyntaxError: invalid syntax

Hello everybody,

I am working on a little NON AI-Chatbot and I wanted to make a «while True:» loop inside a «if name == «main»». But when I’m running the code, it says:

while True: 
^ SyntaxError: invalid syntax

I’ve tried making another script with a while True loop, and that worked, but in the other script it just doesn’t work.

Here’s the nessacery code:

if __name__ == "__main__"

    #forever loop

    while True:

    #here are some if input things


    #this is the last piece of code, in the if__name__ ...

    elif input() in query ["That's not funny at all", "That was not funny", "Not funny."]:
            jokesorry = ["I am sorry.", "Sorry! :-("]
            print(random.choice(jokesorry))

Yes, so when I run the code, I’m getting a syntax error cause of that while True: as I’ve menshiond above. But what am I doing wrong about the while True:. Why am I getting an error. Thanks for your help guys. I am using python 3.7.

Piethon

Posts: 1,904

Threads: 8

Joined: Jun 2018

Reputation:
166

This is definitely syntax error and easy one — every if must end with :

I’m not ‘in’-sane. Indeed, I am so far ‘out’ of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There’s a dead bishop on the landing. I don’t know who keeps bringing them in here. ….but society is to blame.

Posts: 5,147

Threads: 395

Joined: Sep 2016

Reputation:
170

A lot of times you have to look at the line before the traceback

Posts: 72

Threads: 14

Joined: Jul 2019

Reputation:
0

Jul-20-2019, 12:24 PM
(This post was last modified: Jul-20-2019, 12:25 PM by Piethon.)

(Jul-20-2019, 09:49 AM)perfringo Wrote: This is definitely syntax error and easy one — every if must end with :

I did that. Hm…I’m still getting that error.

(Jul-20-2019, 10:50 AM)metulburr Wrote: A lot of times you have to look at the line before the traceback

And where exactly? Do you mean this line: ?

if __name__ == «__main__»

Piethon

Posts: 1,904

Threads: 8

Joined: Jun 2018

Reputation:
166

You posted if __name__ == "__main__". Did you added : to the end?

I’m not ‘in’-sane. Indeed, I am so far ‘out’ of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There’s a dead bishop on the landing. I don’t know who keeps bringing them in here. ….but society is to blame.

Posts: 5,147

Threads: 395

Joined: Sep 2016

Reputation:
170

you posted this

if __name__ == "__main__"

It should be this

if __name__ == "__main__":

Posts: 72

Threads: 14

Joined: Jul 2019

Reputation:
0

Quote:It should be this

if __name__ == "__main__":

I did it, and now, I’m getting a syntax error, cause of it.

if __name__ == «__main__»:
^
SyntaxError: invalid syntax

Piethon

Posts: 7,949

Threads: 150

Joined: Sep 2016

Reputation:
581

no, it’s not because of it
sometimes the error is on the line before the one where the error is shown (note it points at the start of the line).
If you post your full code we may be able to tell you more. in any case — check the line before that one

Posts: 5,147

Threads: 395

Joined: Sep 2016

Reputation:
170

It appears you have a similar issue above that line as well. You need to post the full code.

My code:

def make_response(self):
    recognised = False
    get_cmd = False
    database = {
        "hello": "Nice to meet you. What can I do for you?",
        "hi": "Nice to meet you. What can I do for you?",
        "hey": "Nice to meet you. What can I do for you?",
        "goodbye": "Bye. See you next time!"
    }

    self = self.lower()

    for i in database:
        if i in self:
            recognised = True
            value = database.get(i)
            print(value)


def robot():
    print('Welcome to robot.py')
    print('What can I do for you?')

    while True:
        query = input('>')
        make_response(query)


robot()

When I input «hello», the program gives the intended response but it just exits without completing the loop. Which line broke the loop??
Thank you.

asked Apr 19, 2020 at 9:15

J Muzhen's user avatar

5

In Python 3.x, works fine.

Maybe you’re compiling with python 2.x. In that case, you need to use ‘raw_input’ instead of ‘input’, but I don’t recommend raw_input (it’s deprecated in Python3).

Try Python 3.x.

PS: Also, I’d replace ‘self’ with other variable name. Self is used in classes.

answered Apr 19, 2020 at 9:26

m8factorial's user avatar

2

It doesnt break. Please verify your solution. Here is modified code

database = {
        "hello": "Nice to meet you. What can I do for you?",
        "hi": "Nice to meet you. What can I do for you?",
        "hey": "Nice to meet you. What can I do for you?",
        "goodbye": "Bye. See you next time!"
    }


def make_response(self):
    self = self.lower()
    value = database.get(self, "Sorry I dont understand")
    print(value)


def robot():
    print('Welcome to robot.py')
    print('What can I do for you?')

    while True:
        query = input('>')

        if query == "goodbye":
            value = database.get(query)
            print(value)
            break
        else:
            make_response(query)

robot()

answered Apr 19, 2020 at 9:32

Lovleen Kaur's user avatar

0

I’m totally unable to reproduce that. It keeps prompting for new inputs, just like the code says.

As an aside, though, here’s a slight simplification, using dict.items():

database = {
    "hello": "Nice to meet you. What can I do for you?",
    "hi": "Nice to meet you. What can I do for you?",
    "hey": "Nice to meet you. What can I do for you?",
    "goodbye": "Bye. See you next time!",
}


def make_response(query):
    query = query.lower()
    for keyword, answer in database.items():
        if keyword in query:
            print(answer)
            break


def robot():
    print("Welcome to robot.py")
    print("What can I do for you?")

    while True:
        query = input(">")
        make_response(query)


robot()

answered Apr 19, 2020 at 9:18

AKX's user avatar

AKXAKX

149k15 gold badges108 silver badges165 bronze badges

This Code works perfectly in my machine. But problems with Python 2.7 version. I prefer you to work with Python 3.6 or above.

Here is a simplified code.

Code:

def make_response():
  database = {
        "hello": "Nice to meet you. What can I do for you",
        "hi": "Nice to meet you. What can I do for you?",
        "hey": "Nice to meet you. What can I do for you?",
        "goodbye": "Bye. See you next time!"
      }
  return database

def robot():
    print('Welcome to robot.py')
    print('What can I do for you?')

    while True:
        query = str(input('>'))
        database = make_response()
        if query in list(database.keys()):
            print(database[query])

robot() 

Check it out.
I hope it would be helpful.

answered Apr 19, 2020 at 10:30

Littin Rajan's user avatar

Littin RajanLittin Rajan

8521 gold badge10 silver badges21 bronze badges

Jason Hitching

I’m getting a syntax error on my while True: part of code and i’m not sure why?

make a list to hold onto our items

task_list = []

print out instructions on how to use the app

def show_help():
print(«What do you want to add to your to-do list?»)
print(«»»
Enter ‘DONE’ to stop adding items.
Enter ‘SHOW’ to show the list of tasks.
Enter ‘HELP’ to receive with the program.
«»»)

def show_task():
print(«Here’s your list:»)

for item in task_list:
    print(item)

def add_to_task(new_task):
task_list.append(new_task)
print(«Added {}. List now had {} items.».format(new_task, len(task_list)

while True:
new_task = input(«> «)

# be able to quit the program
if new_task == 'DONE':
    break

elif new_task == 'HELP':
    show_help()
    continue

elif new_task == 'SHOW':
    show_help()
    continue
add_to_task(new_task)

print()
show_task()

1 Answer

Steven Parker

You’re missing some punctuation.

On the print line just before that while True:, there are more open parentheses «(» than there are closing ones «)». It looks like 2 more closing ones need to be added to put them back in balance.

In future questions, be sure to format your code so the spacing shows up (in Python, indentation is everything).
Use the instructions for code formatting in the Markdown Cheatsheet pop-up below the «Add an Answer» area. :arrow_heading_down:

Понравилась статья? Поделить с друзьями:
  • Whatsapp ошибка неправильная дата и время
  • Whatsapp ошибка инициализации
  • Whatsapp ошибка загрузки невозможно загрузить файл
  • Whatsapp ошибка загрузки медиа
  • Whatsapp ошибка даты и времени