Python Forum

Full Version: TypeError: argument of type 'NoneType' is not iterable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Every time i try to run the bellow code it gives me back this Error message
(TypeError: argument of type 'NoneType' is not iterable)
can anyone tell me where exactly the problem

import pyttsx3 
import speech_recognition as sr
import webbrowser
import time
import datetime
import os
import subprocess
import asyncio
from pydub import AudioSegment
from pydub.playback import play

#import pyautogul 

wel = pyttsx3.init()
voices = wel.getProperty('voices')
wel.setProperty('voice', voices[0].id)
def Speak(audio):
    wel.say(audio)
    wel.runAndWait()

def TakeCommands():
    command = sr.Recognizer()
    with sr.Microphone() as mic:
        print ('say commands sir ..')
        command.phrase_threshold = 0.4
        audio = command.listen(mic)
        try :
            print ('Recording ...')
            query = command.recognize_google(audio, language = 'en')
            print (f'you said : {query}')
        except Exception as Error:
            return None
        return query.lower()

music = AudioSegment.from_mp3('sounds/welcom.mp3')
play (music)


while True:
    query = TakeCommands()
    if 'open phootoshop' in query:
        b = AudioSegment.from_mp3('sounds/absher.mp3')
        play(b)
(Nov-28-2024, 04:12 PM)Tajaldeen Wrote: [ -> ]it gives me back this Error message
(TypeError: argument of type 'NoneType' is not iterable)
Please post the entire error message. It is the only way to diagnose the problem.
Most of the time an error like 'Nonetype' is not iterable occurs because a function returned None to a code that was expecting another value.
(Nov-28-2024, 07:33 PM)Gribouillis Wrote: [ -> ]
(Nov-28-2024, 04:12 PM)Tajaldeen Wrote: [ -> ]it gives me back this Error message
(TypeError: argument of type 'NoneType' is not iterable)
Please post the entire error message. It is the only way to diagnose the problem.
Most of the time an error like 'Nonetype' is not iterable occurs because a function returned None to a code that was expecting another value.

This is the whole messages :

Error:
say commands sir .. Recording ... Traceback (most recent call last): File "c:\Users\pc\Desktop\AI\main.py", line 41, in <module> if 'open' in query: ^^^^^^^^^^^^^^^ TypeError: argument of type 'int' is not iterable PS C:\Users\pc\Desktop\AI>
(Nov-29-2024, 03:37 AM)Tajaldeen Wrote: [ -> ]This is the whole messages :
This error message does not correspond to the code that you wrote above. Clearly the error messages occurs because the query variable returned by TakeCommands() is an integer, but the function that you wrote above cannot return an integer, unless you replaced the None value in the Exception handling part by an integer such as 0 for example.

As the message 'You said ...' does not appear in the message, it means that the call to recognize_google() failed and throwed an exception.

The code that calls TakeCommands() must handle the case when this function failed to get a valid command.
(Nov-29-2024, 06:37 AM)Gribouillis Wrote: [ -> ]
(Nov-29-2024, 03:37 AM)Tajaldeen Wrote: [ -> ]This is the whole messages :
unless you replaced the None value in the Exception handling part by an integer such as 0 for example.

same error with 0 value
(Nov-29-2024, 08:00 AM)Tajaldeen Wrote: [ -> ]same error with 0 value
Again I repeat that the code that calls TakeCommands() must take into account the fact that this function may occasionally return None or 0. Your code ignores this fact and this is why you have the error.
The error you're encountering (TypeError: argument of type 'NoneType' is not iterable) is happening because the TakeCommands() function can return None when an exception occurs during the recognition process in the except block. Later in your while True loop, you're trying to check if 'open phootoshop' is in query, but if query is None, this results in the error, as None cannot be iterated over.

### The Cause:
In this line of code:
`python
if 'open phootoshop' in query:
`
You are assuming that query will always be a string. However, if the recognize_google() function fails and an exception is raised, your except block returns None. When None is passed into query, the check 'open phootoshop' in query tries to iterate over None, leading to the TypeError.

### Solution:
You need to check if query is not None before attempting to check if the string 'open phootoshop' is in it. This can be done by adding a simple conditional check.

Here’s how you can modify the code to fix the error:

### Modified Code:


import pyttsx3 
import speech_recognition as sr
import webbrowser
import time
import datetime
import os
import subprocess
import asyncio
from pydub import AudioSegment
from pydub.playback import play

wel = pyttsx3.init()
voices = wel.getProperty('voices')
wel.setProperty('voice', voices[0].id)

def Speak(audio):
    wel.say(audio)
    wel.runAndWait()

def TakeCommands():
    command = sr.Recognizer()
    with sr.Microphone() as mic:
        print('Say commands, sir..')
        command.phrase_threshold = 0.4
        audio = command.listen(mic)
        try:
            print('Recording...')
            query = command.recognize_google(audio, language='en')
            print(f'You said: {query}')
        except Exception as Error:
            return None
        return query.lower()

music = AudioSegment.from_mp3('sounds/welcom.mp3')
play(music)

while True:
    query = TakeCommands()
    if query:  # Check if the query is not None or empty
        if 'open phootoshop' in query:
            b = AudioSegment.from_mp3('sounds/absher.mp3')
            play(b)
### Key Changes:
1. **Check if query is valid**:
Before checking if 'open phootoshop' is in query, we check if query is not None using the condition if query:.
This ensures that the program only tries to process query if it contains a valid string.

### Explanation:
- The condition if query: ensures that query is neither None nor an empty string (""), so it will only attempt to perform the string check ('open phootoshop' in query) if query is a valid string.

This will prevent the TypeError from occurring and make your program more robust when the speech recognition fails to return a valid command.
(Nov-29-2024, 08:47 AM)warmth1 Wrote: [ -> ]### Solution:

You are genius , problem has scattered away .... thank you very much sir Heart Heart Heart