首页 > 解决方案 > While 循环在 Python 中无法正常工作

问题描述

所以我是 Python 的菜鸟,我正在为我的学校做一个项目,所以我遇到了 While 循环的问题,语音 API(espeak)一次又一次地重复第 12 个选项,它一直在重复,直到我强行退出。所以这是我添加espeak的部分

import pyttsx3
import speech_recognition as sr

engine = pyttsx3.init('espeak')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[2].id)

def speak(audio):
    engine.say(audio)
    engine.runAndWait()

&这是while循环部分

while choice != 17:
    if choice == 1:
        print("""
        If you want to make a website, you can see this site
        https://websitesetup.org/
        If you want to make a website you might learn HTML (Hyper Text Markup Language). It is the core of the website. You also need to learn CSS (Cascading Style Sheets) for making website responsive & beautiful & JS (JavaScript) to make website functional properly. CSS & JS are not required but recommended.
        """)
        speak("""
        If you want to make a website, you can see this site
        https://websitesetup.org/
        If you want to make awhile website you might learn HTML (Hyper Text Markup Language). It is the core of the website. You also need to learn CSS (Cascading Style Sheets) for making website responsive & beautiful & JS (JavaScript) to make website functional properly. CSS & JS are not required but recommended.
        """)

    if choice == 2:
        print("""
        If you want to make an application, you need to know that we can make application either for Android or iOS. For Android apps there are many platforms like Plezmo, MIT App Inventor, MIT Scratch etc. They use the block coding... If you want to make text coding then you can use Java. If you want to make iOS apps then you need to have a mac device & you can program in Swift language.
        You can also see: https://www.biznessapps.com/blog/how-to-build-a-mobile-app-in-12-easy-steps/
        """)
        speak("""
        If you want to make an application, you need to know that we can make application either for Android or iOS. For Android apps there are many platforms like Plezmo, MIT App Inventor, MIT Scratch etc. They use the block coding... If you want to make text coding then you can use Java. If you want to make iOS apps then you need to have a mac device & you can program in Swift language.
        You can also see: https://www.biznessapps.com/blog/how-to-build-a-mobile-app-in-12-easy-steps/
        """)
        
    if choice == 3:
        print("""
        If you want to learn Machine Learning, then you can learn Python. There are many concepts of Machine Learning, & the learning curve is very huge so it is not very possible to learn all the concepts of Machine Learning. There are many modules to learn for Machine Learning like Scikit-learn, Theano, Tensorflow etc. They all have different jobs. If you want to have a simple idea of Machine Learning then you can try out Teachable Machine (https://teachablemachine.withgoogle.com/) for having a simple idea of Machine Learning. 
        You can also see: https://www.geeksforgeeks.org/how-to-start-learning-machine-learning/
        """)
        speak("""
        If you want to learn Machine Learning, then you can learn Python. There are many concepts of Machine Learning, & the learning curve is very huge so it is not very possible to learn all the concepts of Machine Learning. There are many modules to learn for Machine Learning like Scikit-learn, Theano, Tensorflow etc. They all have different jobs. If you want to have a simple idea of Machine Learning then you can try out Teachable Machine (https://teachablemachine.withgoogle.com/) for having a simple idea of Machine Learning. 
        You can also see: https://www.geeksforgeeks.org/how-to-start-learning-machine-learning/
        """)
    if choice == 4:
        print("""
        If you want to learn Hacking, you need to learn about Linux (Command Line), Networking, Python, some modules of Python like Scapy, Requests, Cryptography etc. Also you have three types of Hackers available.
        1. Black Hat Hackers, those who do hacking for malicious intenet & have a intent to harm the computer. They do things for illegal things.
        2. White Hat Hackers, also known as Ethical Hackers are those who use the same technology as Black Hat Hackers, but for a good intent, for the security of a Computer, & to get track of Black Hat Hacker
        3. Grey Hat Hackers, are a mix of both, they do things to check the security of the system but without the user awareness, but do not have an intent to harm the computer. 
        """)
        speak("""
        If you want to learn Hacking, you need to learn about Linux (Command Line), Networking, Python, some modules of Python like Scapy, Requests, Cryptography etc. Also you have three types of Hackers available.
        1. Black Hat Hackers, those who do hacking for malicious intenet & have a intent to harm the computer. They do things for illegal things.
        2. White Hat Hackers, also known as Ethical Hackers are those who use the same technology as Black Hat Hackers, but for a good intent, for the security of a Computer, & to get track of Black Hat Hacker
        3. Grey Hat Hackers, are a mix of both, they do things to check the security of the system but without the user awareness, but do not have an intent to harm the computer.
        See this site for more info: https://www.wikihow.com/Start-Learning-to-Hack
        """)
    if choice == 5:
        print("""
        If you want to learn Python, then you can refer to some tutorials which are made for Python. Python is a programming language which has an easy to understand syntax & can be used in many fields like Machine Learning, Game Development, GUI Development, Website Development, etc. It is one of the most wanted languages in demand (According to Stack Overflow). Many companies use this language like Netflix, Google, Instagram etc,
        Refer to this site for learning Python: https://www.w3schools.com/python/
        """)
        speak("""
        If you want to learn Python, then you can refer to some tutorials which are made for Python. Python is a programming language which has an easy to understand syntax & can be used in many fields like Machine Learning, Game Development, GUI Development, Website Development, etc. It is one of the most wanted languages in demand (According to Stack Overflow). Many companies use this language like Netflix, Google, Instagram etc,
        Refer to this site for learning Python: https://www.w3schools.com/python/
        """)
    if choice == 6:
        print("This is the site for ATL Innovation Mission: https://aim.gov.in/")
        speak("This is the site for ATL Innovation Mission: https://aim.gov.in/")
    if choice == 7:
        print("Website is slow due to a technical issue at their site only, so kindly have patience & it will load soon!")
        speak("Website is slow due to a technical issue at their site only, so kindly have patience & it will load soon!")
    if choice == 8:
        print("This is a technical issue from their site itself. Due to a lot of traffic sometimes the site doesn't open. So you can wait for sometimes or try at one of the times like early morning or late night, so there might be less chances for having the site unusable. Sometimes the site is made for some browser online like Google Chrome or Mozilla Firefox, so if it doesn't open try from any other browser.")
        speak("This is a technical issue from their site itself. Due to a lot of traffic sometimes the site doesn't open. So you can wait for sometimes or try at one of the times like early morning or late night, so there might be less chances for having the site unusable. Sometimes the site is made for some browser online like Google Chrome or Mozilla Firefox, so if it doesn't open try from any other browser.")
    if choice == 9:
        print("The website has issues with the login also. It also turns short password into long due to security issues. Login issues are sometimes because of the browser. For example, Brave browser is not compatible & it will show invalid password even though it is correct. 2 browsers working are Google Chrome & Mozilla Firefox")
        speak("The website has issues with the login also. It also turns short password into long due to security issues. Login issues are sometimes because of the browser. For example, Brave browser is not compatible & it will show invalid password even though it is correct. 2 browsers working are Google Chrome & Mozilla Firefox")
    if choice == 10:
        print("To try to repair or improve something without having the proper skill or knowledge")
        speak("To try to repair or improve something without having the proper skill or knowledge")
        if choice == 11:
            print("""
Corruption
Illiteracy
Education System
Basic Sanitation
Healthcare System
Poverty
Pollution
Women’s Safety
Infrastructure
Unemployment
Agricultural Distress
The rise in Global Protectionism
            """)
        speak("""
Corruption
Illiteracy
Education System
Basic Sanitation
Healthcare System
Poverty
Pollution
Women’s Safety
Infrastructure
Unemployment
Agricultural Distress
The rise in Global Protectionism
        """)

    if choice == 12:
        print("""
Step 1: Identify & Meet with Stakeholders. A stakeholder is anyone who is affected by the results of your project plan. ...
Step 2: Set & Prioritize Goals. ...
Step 3: Define Deliverables. ...
Step 4: Create the Project Schedule. ...
Step 5: Identify Issues and Complete a Risk Assessment. ...
Step 6: Present the Project Plan to Stakeholders.
        """)
    speak("""
Step 1: Identify & Meet with Stakeholders. A stakeholder is anyone who is affected by the results of your project plan. ...
Step 2: Set & Prioritize Goals. ...
Step 3: Define Deliverables. ...
Step 4: Create the Project Schedule. ...
Step 5: Identify Issues and Complete a Risk Assessment. ...
Step 6: Present the Project Plan to Stakeholders.
    """)

    if choice == 13:
        print("""
Come up with a simple project.
Get the software you'll need.
Join communities about how to start coding.
Read a few books.
How to start coding with YouTube.
Listen to a podcast.
Run through a tutorial.
Try some games on how to start coding.
Take a Coding Bootcamp
You can also learn coding from these Coding Classes and Programs
Codecademy. ...
Udemy. ...
Skillcrush's FREE Coding Camp. ...
freeCodeCamp. ...
Khan Academy. ...
Web Fundamentals. ...
w3schools. ...
Code.org.etc
        """)
        speak("""
Come up with a simple project.
Get the software you'll need.
Join communities about how to start coding.
Read a few books.
How to start coding with YouTube.
Listen to a podcast.
Run through a tutorial.
Try some games on how to start coding.
Take a Coding Bootcamp
You can also learn coding from these Coding Classes and Programs
Codecademy. ...
Udemy. ...
Skillcrush's FREE Coding Camp. ...
freeCodeCamp. ...
Khan Academy. ...
Web Fundamentals. ...
w3schools. ...
Code.org.etc
        """)

    if choice == 14:
        print("""
    No, coding is not hard to learn. However, like anything new, it's not easy to start, and how difficult a time one has with learning to code will vary across a number of factors. The point is, learning to code isn't impossible; or, it's not as impossible as it might seem when it comes to getting your kids involved.
        """)
        speak("""
    No, coding is not hard to learn. However, like anything new, it's not easy to start, and how difficult a time one has with learning to code will vary across a number of factors. The point is, learning to code isn't impossible; or, it's not as impossible as it might seem when it comes to getting your kids involved.
        """)
    
    if choice == 15:
        print("""
    The job can be stressful at times, but computer programmers are compensated well for any anxiety they might experience. Many jobs in this profession are being outsourced to other countries where pay is lower, saving companies money.
        """)
        speak("""
    The job can be stressful at times, but computer programmers are compensated well for any anxiety they might experience. Many jobs in this profession are being outsourced to other countries where pay is lower, saving companies money.
        """)

    if choice == 16:
        print("""
    Computer programmers get paid well, with an average salary of $63,903 per year in 2020. Beginner programmers earn about $50k and experienced coders earn around $85k.
        """)
        speak("""
    Computer programmers get paid well, with an average salary of $63,903 per year in 2020. Beginner programmers earn about $50k and experienced coders earn around $85k.
        """)

if choice == 17:
    print("Ok Exiting...")
    speak("Ok exiting...")

&这是第12个选项

    if choice == 12:
        print("""
        Step 1: Identify & Meet with Stakeholders. A stakeholder is anyone who is affected by the results of your project plan. ...
        Step 2: Set & Prioritize Goals. ...
        Step 3: Define Deliverables. ...
        Step 4: Create the Project Schedule. ...
        Step 5: Identify Issues and Complete a Risk Assessment. ...
        Step 6: Present the Project Plan to Stakeholders.
        """)
        
    speak("""
        Step 1: Identify & Meet with Stakeholders. A stakeholder is anyone who is affected by the results of your project plan. ...
        Step 2: Set & Prioritize Goals. ...
        Step 3: Define Deliverables. ...
        Step 4: Create the Project Schedule. ...
        Step 5: Identify Issues and Complete a Risk Assessment. ...
        Step 6: Present the Project Plan to Stakeholders.
        """)

标签: pythonwhile-loop

解决方案


guess我建议在 while 循环的开头插入你的变量,这样在任何不是的输入之后17,它将循环回到 while 循环的开头,这将为您提供另一个选择另一个选项的机会。

while True:
  guess = int(input('input message'))
  if guess == 1:
    # Do something...
  elif guess == 2:
    # Do something else...
  elif guess == 3:
    # Do something else again...
  elif guess == 4:
    # Quit the program for example...

另一种方法是break按照 Code2D 的建议退出循环,但前提是您只想在选择 1 个选项后结束循环。


推荐阅读