I've been working on this simple program in Python just so I can start experimenting with Python and become more knowledgeable of Python and other programming languages in general by designing them in a way in which others can use them in an efficient manner without getting caught on the parts which make this code work. I've been doing this by having a simple program calculate "Angles in a triangle" as it's a simple subject. Recently, I replaced def(): commands with if statements as it cuts down typing to a minimum and making it generally easier for others however, when I try to run this code I get a syntax error message with N becoming highlighted on line 17.
def triangle():
N = int(input("Please enter the number of angles you currently have between 1 and 3: "))
if N == 1:
a = int(input("What's one of the angles?"))
b = int(input("What's the other angle in the triangle?"))
c = a + b
f = 180 - c
print(f)
print("If you'd like to continue, please type in triangle()")
elif N == 2:
a = int(input("What's the value of angle 1?"))
b = 180 - a
c = b /2
print(c)
print("If you'd like to continue, please type in triangle()")
else N == 3:
a = 180
b = 180 / 3
print(b)
print("If you'd like to continue, please type in triangle()")
But I'm getting a syntax error returned on elif N == 3:
Any tips would be great.
else does not have a condition.. remove it to just say
else:
or make it says
elif N == 3:
You have else N == 3:. That is not how the if..elif..else structure works - the else is a catch-all branch that is entered if none of the preceding if or elif conditions are satisfied. If you want to check specifically for N == 3 and no other values, use elif N == 3. If you want a catch-all condition, simply use else:.
elif N == 3:
Either you meant elif (which is Python for else..if), or else
If you meant plain else, it doesn't take a condition.
If you want to annotate that an else implies a certain condition is met, then I use a comment:
else: # N == 3
But that's considered bad style: only do that if you're sure N cannot have any other value than 1,2,3. In your case the user could also input any number 4,5,..,9 (or indeed 10 or larger, or indeed 0 or any negative number), and that will wrongly get handled by the N==3 branch.
Whereas if your last branch if elif N == 3, with no else-clause, invalid numbers will silently fail every branch in your tree.
So for completeness and sanity-checking, you might prefer to do:
...
elif N ==3:
# Handle N == 3 case
else:
print "Invalid number!"
Related
This question already has answers here:
Difference between multiple if's and elif's?
(9 answers)
Closed 5 days ago.
Something that's confusing me is If statements vs Elif statements. If they can both be run and both do the same thing, then what's the difference? For example:
num = int(input("Please enter a number 1-10 "))
if num == 1:
print("I is the roman numeral for 1 ")
elif num == 2:
print("II is the roman numeral for 2 ")
elif num == 3:
print("III is the roman numeral for 3 ")
else:
print("invalid number please try again")
This code can and will run, but what's stopping me from just using an If statement instead of an elif? I read that elifs are faster, but I don't know how true that is if at all.
I've tried going back and removing the if statements and replacing them with elif statements and vice versa, but I just don't see the difference.
The semantics are totally different, and it is very important to understand the difference. Just a bunch of ifs will run only based on the condition. But if you use if ... elif... then the elif will only run if previous if and elifs did not succeed!
In your case, your conditions are mutually exclusive so the behavior is exactly equivalent. But suppose your conditions were not mutually exclusive. Consider the different behaviors between:
x = 1
if x == 1:
print("I am solitary")
elif x < 12:
print("I am less than a dozen")
which simply prints:
I am solitary
versus:
x = 1
if x == 1:
print("I am solitary")
if x < 12:
print("I am less than a dozen")
which prints:
I am solitary
I am less than a dozen
Also note, because of your else on the last if, the behavior isn't exactly equivalent.
I was writing this code and I can't seem to get it to work correctly.
There's no Syntax errors so I'm clear on that.
It just is not giving me the correct output I want.
Here's the code :
This is the out put I get when x = 5 :
Big!
Done!
This is the output I get when x = 1
Small!
Done!
This is what I get when x = anything other than 1 or 5
Done!
What I want it to do is when x = anything between 1-5 to output Small! then Done!
Or if it is between 5-infinity to output Big! then Done! but if the number is not 1 or 5 it just outputs Done!
What changes should I do to my code?
As pointed by a user in the previous answer, what you need to implement is an if-else ladder and use logical operator for the case when your output is specifically either 1 OR 5
x=6 # You can replace this by a user defined input using input()
if x==5 or x==1:
print("Done!")
elif x<5:
print("Small!")
print("Done!")
elif x>5:
print("Big!")
print("Done!")
else:
print("Enter a valid number!")
I checked with various test cases like 1, 5 , numbers between 1 and 5 and numbers greater than 5 and all seem to work fine.
Here's a sample output
x = 5
if x in range(6):
print('Small')
elif x >=6 :
print('Big')
print('Done')
Try this. The range function checks if the number is in between 0 and 6 i.e 0 to 5. Anything lesser than 0 will be ignored
The problem with your code is that you're just checking two conditions if x== 5 and if x == 1. The print statements will be executed only if this condition is satisfied.
Cheers
You can create a if-else ladder to achieve this
def determine_size(inp):
if inp == 1 or inp == 5:
print("Done")
elif 0 <= inp < 5:
print("Small")
print("Done")
elif inp > 6:
print("Big")
print("Done")
else:
print("Negative Input")
>>> determine_size(0)
Small
Done
>>> determine_size(100)
Big
Done
>>> determine_size(60)
Big
Done
>>>
>>> determine_size(3)
Small
Done
>>> determine_size(4)
Small
Done
You can also play around with the if-else statements per your objectives
x = 40
# at first check if x is greater than 1 and less than 5.
# Only then it is between 1 and 5.
if x >=1 and x<=5:
print('Small!')
# Now chek if x is greater than 5
elif x>5:
print('Big!')
print('Done!')
if you meant the above mentioned scenario mentioned in comment
try:
x=int(input("enter a number: "))
if x >=0 or x<=5:
print("Small")
print("Done")
elif x>=6:
print("big")
print("Done")
except ValueError:
print("Done")
here the block of code is written in try block, why i have written in try block if someone enter something which is not number then program will not crash and raise a exception.
if you are not familiar with elif syntax, we can have simple construction like this :-
try:
x=int(input("enter a number: "))
if x >=0 and x<=5:
print("Small")
print("Done")
else:
print("big")
print("Done")
except ValueError:
print("Done")
Here all I have done is to change the logical operator from or to and.
I am trying to create a game where i think of a number in my head. And then the computer guesses the number through me telling it if its guess is too low or high.
This is what I've come up with but i am pretty lost tbh.
maxguess = 100
minguess = 1
count = 0
print("Think of a number between {} and {}".format(minguess,maxguess))
def midpoint(maxguess, minguess) :
z = ((maxguess + minguess)/2)
def guessing(x) :
print("Is you number greater (>) , equal (=) ,or less (<) than" ,z,)
print("please answer <,=, or >! >")
x = input()
if x == (">") :
minpoint = z
count += 1
continue
elif x == ("<") :
maxpoint = z
count += 1
continue
elif x == ("=") :
print ("I have guessed it!")
count += 1
break
print("I needed {} steps!".format(count))
Purposely not a complete solution, but some hints for you:
I'd recommend avoiding the global variables like count, maxguess, and minguess. Instead, make a function that holds all these variables.
Change your midpoint function to return z instead, then call it inside your guessing function.
Your continue and break functions would need to be inside a for or while loop. Since you aren't sure how many iterations you need to guess the number, I think a while loop would make sense here
Your functions are never run. On a style point, bring all your 'main' statements down to the bottom so they're together. After the prompt to think of a number, you need to call the guessing() function. When you call it, you should pass the minguess and maxguess values to it.
I can see what you're trying to do with the if...elif statements, but they need to be in a while True: block. So should the three statements preceding them so the script repeatedly asks for new advice from you.
Either bring the content of the midpoint() function into guessing() or make it return the value of z.
You also offer the user a choice of '>1' but don't handle it - and you don't need it as far as I can tell.
You never use minpoint or maxpoint - and you dont need them. Call the midpoint function instead and pass it the appropriate values, e.g., if '>', z = midpoint(z, maxguess).
Also, you're going to spend forever trying to get it to guess as you are using floats. Make sure everything is an integer.
Finally, you should add some code to manage input that isn't expected, i.e., not '<', '>' or '='.
Good luck!
minguess=1
maxguess=100
z=50
count=0
print("Think of a number between 1 and 100")
condition = True
while condition:
z=((maxguess + minguess)//2)
print("Is your number greater (>) , equal (=) ,or less (<) than" ,z,)
print("Please answer <,=, or >! >")
x = input()
if x == (">"):
minguess=z
count += 1
elif x == ("<") :
maxguess=z
count += 1
elif x == ("=") :
print ("I have guessed it!")
count += 1
condition=False
I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.
I'm making a number guessing game and can someone tell me why it wont work properly?
import random
import time
time.time()
count=0
a = random.randint(0,100)
b = int(input("What number will you guess?"))
while b != a:
if b > a:
print("TOO BIG")
count = count + 1
elif b < a:
print("TOO SMALL")
count = count + 1
else b == a:
print("YOU WIN")
count = count + 1
time=time.time()
print("You took",count,"tries")
print("It took you",time,"second")
The reason this isn't working properly is because you're calling b = input outside of your while loop. As it stands, the user will be asked a single time what their guess is, then the loop will just move infinitely, because b is never being modified.
This loop will accomplish more what you want:
a = random.randint(0,100)
b = -1
while b != a:
b = int(input("What number will you guess?"))
A few notes, though:
Firstly, as Lee Daniel Crocker points out, the user will actually never see "YOU WIN", because you've structured your if-elif-else statement incorrectly. else by definition cannot have a condition - it exists purely in exclusion to all other conditionals in the same block. Additionally, your else statement is the opposite of your while condition. When that else becomes true, the loop exits. You'll need to handle printing "YOU WIN" somewhere else.
Second, you're not validating the user's input in any way - if they enter 'a', the program will crash, because you can't cast 'a' to an int. Either add an exception handler (for ValueError) or using isdigit() on the string, then casting it.
Third, you're not using time.time() correctly - you need to subtract the time at which the user wins from the time at which they started, then represent that value, which is in seconds, in some meaningful way. As it stands you're telling each player that they took the number of seconds since the beginning of the UNIX epoch to complete the game.
Also, for usability reasons, you should probably provide the user some way to break out - a string like "QUIT" - because as it stands, the only way to restart/quit is to either close the application or KeyboardInterrupt.
You need to accept input in the loop. Move the line b = int(input("What number will you guess?")) within the loop.