If, Else not working when checking if function is true - python

I am a beginner in Python programming. Recently I decided to build an Audio assistant(basically a chatbot with audio), but I ran into an issue when trying to produce the Outputs. I wrote the code in a way that if what the user says/asks the bot to do, is something which has not been defined to the bot or it does not have any commands on what to do if that specific argument is given then it should give a specific output. The code for it is as below:
# to take input from the user:
command = input("Whatever you want to say: ")
command = command.lower()
cmd = command.split()
# below are the commands to give output after processing the input
if 'hi' in cmd:
print('hey')
elif (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
elif (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
else:
print('sorry, did not understand what you meant!')
The problem with the above code is that, if the user says: (hi, hru?) the programme only says: hey.
This is because I was using elif statements in the programme. SO I decided to change all of them to if statements:
if 'hi' in cmd:
print('hey')
if (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
if (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
else:
print('sorry, did not understand what you meant!')
what this does is, it prints the output well, but if any other statement's output is supposed to be given, it gives the statement, but also gives the output for else.
Then I tried to define a function for the outputs, and if it is True, i.e. if what the user says has a specified output then it is supposed to give the output, if not, then the programme is supposed to print the exception.
def commands():
if 'hi' in cmd:
print('hey')
if (('how')and('are'))and('you') in cmd:
print('All good! Wbu?')
if (('hi')and('hru')) in cmd:
print('Hey! Everyting is fine! Wbu?')
if commands()==True:
commands()
else:
print('sorry, did not understand what you meant!')
This too as the first, prints the statement as well as the exception. How do I solve this ?

Although it is common in English (and other human languages) to say things like:
if X and Y are in Z...
… that is not quite how boolean logic works.
What you've actually written is parsed more like this:
if X-and-Y is in Z...
And something like ('hi' and 'hru') is going to give you a useless result ('hru', I think).
What you need is:
if X is in Z, and Y is in Z
To accomplish this, rewrite your conditions like this:
if ('hi' in cmd) and ('hru' in cmd):

If a and b in "something"
Won't work
a and b
ends up AND'ing the a and b and then checking if the result is in "something", which likely always gives an output as false, quite the rookie mistake which I couldn't understand at that time

Related

Issue with running input and if/else code in a single code

Please don't hate me if something like this has been asked, I couldn't find a similar problem.
I'm learning python, and I'm trying to get a small piece of code to work in IDLE shell 3.9.7 like this
>>> mark=int(input("enter mark"))
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
with the idea that you enter the mark, then it prints one of the statements without having to run the input code then the if/elif/else statements afterwards (I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately.) However, when I run the code, I enter the mark and nothing happens. I've tried different indentation and putting the input bit at the end, but it just asks for the mark and then nothing happens. I'm not sure what I'm doing wrong, as the app that I'm using to learn has it parsed exactly like this. Appreciate any help.
Try this it should work just had to put it in a for loop
while True:
mark=int(input("enter mark: "))
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
(I want to have all this code, press enter and then get the desired input/output without running the if/else statements separately
Probably you want a function, like this:
def foo(mark: str) -> None:
if mark>=90:
print("excellent")
elif mark<90 and mark>=75:
print("good")
elif mark<75 and mark>=40:
print("average")
else:
print("fail")
that you can call this way in the shell:
>>> foo(int(input("Enter your mark: ")))
10
fail

How to remove previous outputs and execute Python commands through Python's input()?

I have a piece of code that stops the loop when nothing is entered but is there a way to make it look more clean and delete the last line that has nothing? It will give me an output like:
**Line 1: print("Hello World"),
Line 2:**
How can I delete that last line(Line 1: print("hello world")? Note, I tried using the \r\033[F thing but it doesn't seem to work for inputs.
line_number=1
command=None
command2=None
command3=None
command4=None
letter_start=0
letter_end=0
command_end=0
textbox_input=None
print_type=1 #1 = string: 2 = variable
commands=[]
variables={}
def execute_command(textbox):
global print_type
global commands
if textbox.startswith('p'):
if textbox.startswith("pr"):
if textbox.startswith("print("):
command=print #You can change what command is used
if print_type == 1:
letter_start=7 #"letter_start" is the variable that holds the position of the first letter (not including parentheses "" or brackets())
command_end=5
elif print_type == 2:
letter_start=6
command_end=5
else:
print("Only Print")
else:
print("Only Print")
elif "=" in textbox:
equals=textbox.index("=")
variables[textbox(0,equals)]=textbox(equals,-1)
if textbox.startswith('(', command_end):
if textbox.startswith('("', command_end):
if textbox.endswith(')'):
if textbox.endswith('")'):
print_type=1
letter_end=textbox.index(')')-1
textbox_input=textbox[letter_start:letter_end]
else:
print(f"-->{textbox}<--: Missing quotes")
else:
print(f"-->{textbox}<--: Missing parenthesis") ;
elif textbox.endswith(')'):
if textbox.endswith('")'):
print(f"-->{textbox}<--: Missing quotes")
else:
print_type=2
letter_end=textbox.index(')')
else:
print(f"-->{textbox}<--: Missing parenthesis")
else:
print(f"-->{textbox}<--: Missing parenthesis")
#PROGRAM BEGGINING
while True:
textbox1=input(f" Line {line_number}: ")
line_number+=1
if textbox1:
commands.append(textbox1)
else: #if the line is empty finish inputting commands
break
print("--------------")
print(commands)
for cmd in commands:
execute_command(cmd)
Edit:
according to the comments, here's what questioner want to achieve:
Want to remove or edit the previous input.
Execution of Python commands through input function.
Saving the command typed in the input function in a file.
What I understood is you want to create a program which executes Python commands like print('Hello World'), show you the output and also save's it in a document or text file.
for execution of Python command's, you can use sub-process module.
# Code to execute python command
import subprocess
def executor(cmd):
process=subprocess.Popen(['python.exe'],
stdin=subprocess.PIPE, # Input
stdout=subprocess.PIPE,# Output
stderr=subprocess.PIPE,# Error
shell=True)
results=process.communicate(input=bytes(cmd,'utf-8')) # We can only send data to subprocess in bytes.
output=results[0].decode('utf-8') # Decoding or converting output from bytes to string.
error=results[1].decode('utf-8')# Decoding or converting output from bytes to string.
return (output,error)
a=executor('''print('hellow')''')
print(a)
To execute commands from input, you can just change a=executor('''print('hellow')''') to a=executor(input()).
and in order to save the previous command in a text file, you can do the following:
Change return (output,error) to return (output,error,cmd) so you can have an instance of text passed in input.
Write it in a file.
To clear the screen after the execution of previous code, just use os.system('cls') # on windows
Here are the site's I used for references:
Execution from python 1
Execution from python 2
To clear Python Screen
I would suggest you to know about Treading too, i am just guessing that it would be use full for you
You might have to make some change in code for your usage, as here on stack overflow, we just give you hints, we can not help you with creation of full program.

How to enable/disable a line of code without the usage of if statements?

Say that you have 2 print statements:
print ("Hi")
print ("Hello")
And you comment out the second line resulting in:
print ("Hi")
#print ("Hello")
This would only execute the first line on runtime, ignoring the second. My question is, is there a way to enable the second line during runtime without having to manually go to the script and remove it?
I'd like to do through user input, but also without the usage of if statements because my code is getting over saturated with "ifs" and wish to do something different.
I think there is nothing wrong with "over Saturating of if conditions" but however if you want to still find a way here is a one, but it may not guarantee finest result depending upon what you want. and it only works if you already know the output.
taking and trivial example suppose you want to print "hello" if user inputs 1 and "hi" when user inputs 0.
dec = {0: "hello", 1: "hi"}
try:
print(dec[0])
except KeyError:
print("wrong entry!")
i hope it helps!

What is CLI-Loop ? What's the difference with normal loop?

I was doing some research about Python.
And I saw something like this.
# Start CLI-Loop
while True:
try:
text = raw_input()
except:
text = error()
if text == condition_1:
do_Some_Other_Things_1()
break
elif text == condition_2:
do_Some_Other_Things_2()
Is CLI-Loop stands for "Command Line Interface Loop" ?
If not, what does it mean?
What's so special about it?
There is nothing special about the loop; the author simply introduces the code block, stating that it'll interpret commands.
Which is exactly what the loop does; using raw_input(), it asks for user input from the terminal, then executes functions based on the input. In other words, it takes commands, interfacing with the user.
CLI indeed stands for Command Line Interface. There's nothing special about this loop, it's just called "the CLI loop" to indicate it's a loop handling the input taken from the command line.

How to repeat functionality in program

I am working on a simple Python program where the user enters text and it says something back or executes a command.
Everytime I enter a command, I have to close the program. Python doesn't seem to have a goto command, and I cannot enter more than one "elif" without an error.
Here is the part of the code that gives me an error if I add additional elif statements:
cmd = input(":")
if cmd==("hello"):
print("hello " + user)
cmd = input(":")
elif cmd=="spooky":
print("scary skellitons")
Here's a simple way to deal with different responses based on user input:
cmd = ''
output = {'hello': 'hello there', 'spooky': 'scary skellitons'}
while cmd != 'exit':
cmd = input('> ')
response = output.get(cmd)
if response is not None:
print(response)
You can add more to the output dictionary, or make the output dictionary a mapping from strings to functions.
Your program is only coded to execute once from what you've posted. If you want it to accept and parse the user input multiple times, you'll have to explicitly code that functionality it.
What you want is a while loop. Take a look at this page for a tutorial and here for the docs. With while, your program would have the general structure of:
while True:
# accept user input
# parse user input
# respond to user input
while statements are part of the larger flow control.

Categories

Resources