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
Related
in the output pane ı cannot see the values that ı entered before when the program finishes (when using debugger). I think, normally ı should see the guess that ı made between the two lines in the output( ı draw an arrow).
You have multiple errors in your code so far, maybe you are about to write the logic for it after you have the desired output, but I am anyway going to mention it.
1.If you want the user to guess multiple times you need to use a loop.
For example:
while True:
if ():
print()
elif():
print()
else:
print("Correct")
break
2.Also, if you want the user to guess again you would need to take input inside the if-elif structure.
3.To print the user input you can do as previous suggestion and put it inside the print-statement inside the if-statement like this:
answer = 5
guess = int(input("Please guess a number between 1 and 10:"))
while True:
if guess < answer:
print("You guessed:", guess)
guess = int(input())
.
.
.
else:
print("You guessed:", guess)
print("Congrats, it was correct!")
break
you can add:
print(guess)
before all the "if" statements if you want to see the input value printed
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
I would like to know why this code does not work; it should exit at the "GAME OVER" point, but it continues to my next defined function.
I have tried other variations on exit() such as: sys.exit(), quit() and SystemExit.
run_attack = input("What do you do: Run/Attack\n")
run = ['run', 'Run', 'RUN']
attack = ['attack', 'Attack', 'ATTACK']
run_attack = 1
while run_attack < 10:
if run_attack == ("run") or ("Run") or ("RUN"):
print ("You turn to run from the wolf but he quickly pounces
you...")
time.sleep(2)
print("You are quickly ripped apart and just about get to see
yourself be eaten.")
print("GAME OVER")
break
exit() #This is where the game should exit, yet after input it
continues to the next function
elif run_attack == ("attack") or ("Attack") or ("ATTACK"):
print("You brace yourself for a bite and have no time to reach"
"for any kind of weapon form your backpack.")
time.sleep("2")
input("You clock the dog hard, twice on the muzzle.")
print("The dog recoils in pain and retreats back to the woods.")
print("You quickly start running as you assume there will be a den in the woods.")
break
else:
input("Type Run or Attack...")
You have several problems in your code; why did you write this much without testing it?
First, you read the user's input, immediately replace is with 1, and then try to test it (incorrectly) as if it were still a string. Your posted code has several syntax errors, so I have some trouble reproducing the problem. However, the immediately obvious problem is here:
break
exit() # This is where ...
You can't get to the exit statement, as you break from the loop just before you can get there.
I strongly recommend that you back up to a few lines and use incremental programming: write a few lines at a time, debug those, and don't continue until they do what you want.
Also look up how to test a variable against various values. Your if statement is incorrect. Instead, try the list inclusion you're trying to set up:
if run_attack in run:
...
elif run_attack in attack:
...
I took the liberty of rewriting your whole program to show you a few things wrong with it and a few tricks. I've done it without the loop, since you never use it anyway... you can add the while loop later once you've mastered it, but you should really go back to basics on some things here:
run_attack = input("What do you do: Run/Attack\n")
if run_attack.lower() == "run":
print("""some
stuff
with
multiple
lines and GAME OVER""")
exit()
elif run_attack in ("attack", "Attack", "ATTACK"):
print("""some
stuff
with
multiple
lines""")
else:
input("Type Run or Attack...")
Some notes:
Using """ for strings enables you to write multiple lines without multiple print statements
Using str.lower() on strings makes everything easy to compare because you only have to compare it to the lowercase version of each string. However for attack you can notice I used a different inclusion test, without multiple conditions. Either way works here.
Like the other answer here (and many comments), you should use only exit() to leave the program entirely, or only break to exit the loop and continue to other code that's beneath the entire loop.
When you rewrite your loop, with a condition like while number_of_turns < 10 don't forget to add 1 to the number of turns on each loop, otherwise that condition is always True and you'll have an infinite loop...
I'm actually quite surprised this code had any resemblance to the behavior you expected from it, my suggestion is to go back over to the basics of python, learn loops, string methods, basic commands. The rest is already said in the other answer here (which is better than mine, frankly) just wanted to add some ideas.
I have been trying to convert some code into a try statement but I can't seem to get anything working.
Here is my code in pseudo code:
start
run function
check for user input ('Would you like to test another variable? (y/n) ')
if: yes ('y') restart from top
elif: no ('n') exit program (loop is at end of program)
else: return an error saying that the input is invalid.
And here is my code (which works) in python 3.4
run = True
while run == True:
spuriousCorrelate(directory)
cont = True
while cont == True:
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
cont = False
elif choice == 'n':
run = False
cont = False
else:
print('This is not a valid answer please try again.')
run = True
cont = True
Now what is the proper way for me to convert this into a try statement or to neaten my code somewhat?
This isn't a copy of the mentioned referenced post as I am trying to manage two nested statements rather than only get the correct answer.
If you want to make your code neater, you should consider having
while run:
instead of
while run == True:
and also remove the last two lines, because setting run and cont to True again isn't necessary (their value didn't change).
Furthermore, I think that a try - except block would be useful in the case of an integer input, for example:
num = input("Please enter an integer: ")
try:
num = int(num)
except ValueError:
print("Error,", num, "is not a number.")
In your case though I think it's better to stick with if - elif - else blocks.
Ok so as a general case I will try to avoid try...except blocks
Don't do this. Use the right tool for the job.
Use raise to signal that your code can't (or shouldn't) deal with the scenario.
Use try-except to process that signal.
Now what is the proper way for me to convert this into a try statement?
Don't convert.
You don't have anything that raises in your code, so there is no point of try-except.
What is the proper way to neaten my code somewhat?
Get rid of your flag variables (run, cont). You have break, use it!
This is prefered way of imlementing do-while, as Python docs says; unfortunately, I cannot find it to link it right now.
If someone finds it, feel free to edit my answer to include it.
def main()
while True: # while user wants to test variables
spuriousCorrelate(directory) # or whatever your program is doing
while True: # while not received valid answer
choice = input('Would you like to test another variable? (y/n) ')
if choice == 'y':
break # let's test next variable
elif choice == 'n':
return # no more testing, exit whole program
else:
print('This is not a valid answer please try again.')
I am very very new to Python and before this I only used extremely simple "programming" languages with labels and gotos. I am trying to make this code work in Sikuli:
http://i.imgur.com/gbtdMZF.png
Basically I want it to loop the if statement until any of the images is found, and if one of them is found, it executes the right function and starts looping again until it detects a new command.
I have been looking for tutorials and documentation, but I'm really lost. I think my mind is too busy trying to go from a goto/label to an organized programming language.
If someone could give me an example, I would appreciate it a lot!
In Python indentation matters, your code should look like this:
def function():
if condition1:
reaction1()
elif condition2:
reaction2()
else:
deafult_reaction()
I recommend reading the chapter about indentation in Dive Into Python as well as PEP 0008.
x = input( "please enter the variable")
print(" the Variable entered is " + x)
myfloat = int(x)
def compare (num):
if num%2 == 0:
print(" entered variable is even")
else:
print("entered variable is odd")
compare(myfloat)