I'm writing some code in Python that calculates the area of a triangle or a circle, depending on the user's choice. I want to write "if the user's choice is a C (for circle), continue running", but everything I write doesn't work and it shows an error.
I have:
option = raw_input('Enter C for Circle and T for Triangle: ')
circle = 'C'
tringle = 'T'
if option == circle:
return option
As noted in the comments, you cannot return a value unless it is from a function.
If you want to accomplish a running example you can easily use a while loop like so:
circle = 'C'
tringle = 'T'
value = True
while value:
option = raw_input('Enter C for Circle and T for Triangle: ')
# check lower() so capitalization doesn't matter
if option.lower() == circle:
# do something
print("Do something, 'C' has been selected")
pass
else:
value = False
As an explanation, if you are unclear on what is happening above. The while loop is always True if the selected option is circle, thus the loop never terminates and the iteration continues. If the selected option is not circle, the value of value will not be True, so the loop breaks before the code in the loop is executed again.
You're getting a SyntaxError because you are calling return despite not having any function defined. According to Python syntax, you can only return from inside of a function. I'd recommend reading up on how to create Python functions (this article does a good job of explaining it)
Related
I'm trying to create a "football" game on python and if the user wants to pass the ball, my code is supposed to have a 50% probability of having an incomplete pass or a completion yielding between 3 and 15 yards
I know that to print the yardage, the code would look something like
import random
input("Enter r to run and p to pass")
p = print(random.randint(3,15))
but I'm not sure how to make "Incomplete" show up as a 50% probabilty
You can use the code below. As you have defined a statement to pick a random number between 3-15, you can create another statement to pick 0 or 1 (not %50 guaranteed). Also in your code, you are assigning return value of the print function to a parameter. This is definitely wrong! Print function returns nothing so assigning it to another variable is meaningless.
x = random.randint(0,1)
if x == 1:
random.randint(3,15)
else:
# incomplete pass
You could use something like this.
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([random.randint(3,15),0]))
elif(inp == "r"):
print("ran successfully")
This: random.choice([random.randint(3,15),0]) is the important bit. random.choice takes multiple values (in this case 2) in a list, and picks one randomly (2 values => 50% probability).
I also fixed the input output thing. To get input from the user you assign the value of input to a variable like this: example = input("Your input here: "). If you ran that line of code, and answered with potato for instance, you'd be able to print example and get potato (or whatever the user answered) back.
If you'd like to really flesh your game out, I'd suggest looking into template strings. Those let you do wonderful things like this:
import random
inp = input("Enter r to run and p to pass")
if(inp == "p"):
print(random.choice([f"Successfully passed the ball {random.randint(3,15)} yards","You tripped, the ball wasn't passed."]))
elif(inp == "r"):
print("Ran successfully.")
My goal is to create a little program that converts angle from radiant to degree and vice-versa. I need the program to close with no error message from python if the user enters the information to convert in the wrong format.
After assigning the variable ‘angle’ to both values of the input. The angle variable becomes a list type.
In norther to exit program with no error message I write this:
'if angle is not list():break'.
The problem is when I do that it exits the program for any type of command entered as an input.
here is my code:
import numpy as np
while 1:
angle=input("Please enter the angle you want to convert,\n\n"\
"If you wish to convert degrees in radiant or vise-versa,\n"\
"follow this format: 'angle/D or R'").split('/')
if angle is not list():break
angle[0]=float(angle[0])
radiant= (angle[0]*(np.pi))/180
degre=((angle[0]*180)/np.pi)
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D' :
print(radiant,'radiants')
elif angle[1] is 'R':
print(degre,'degrés')
else:break
You can use isinstance(angle, list) to check if it is a list. But it won't help you achieve what you really want to do.
The following code will help you with that.
question = """Please enter the angle you want to convert.
If you wish to convert degree in radiant or vice-versa.
Follow this format: 'angle/D or R'
"""
while 1:
angle=input(question).split('/')
if not isinstance(angle, list): break # This will never happen
# It will never happen because string.split() always returns a list
# Instead you should use something like this:
if len(angle) != 2 or angle[1] not in ['D', 'R']:
break
try:
angle[0]=float(angle[0])
except ValueError:
break
if (angle[0]>=0 or angle[0]<=360) and angle[1] is 'D':
# You could also improve this by taking modulo 360 of the angle.
print((angle[0]*np.pi)/180, 'radiants')
else:
# Just an else is enough because we already checked that angle[1] is either D or R
print((angle[0]*180)/np.pi, 'degrees')
What you want:
if not isinstance(angle, list): break
What you've done: if angle is not list():break will always evaluate to True as no object will ever have the same identity as the list list(); since is is a check for identity.
Even this:
>>> list() is not list()
True
break statements are used to get out of for and while loops. Try using a while loop after the input statement to evaluate the input. Use a possible set as a conditional. You do not need to break from an if statement because it will just be bypassed if the the conditional is not met.
Sometimes you might see an if statement followed by a break statement. The break statement, however, is not breaking from the if statement. It is breaking from a previous for or while loop.
I tried this... but it doesn't work
question = input("do you want the program to start? Type Y/y to start: ")
y = TRUE
Y = TRUE
if(question == TRUE):
run statements
else:
what am i doing wrong? this doesn't work.
To answer your specific question, it is not working because of these issues:
TRUE is not a defined variable in python. True is.
question == TRUE won't work. See 1.
run statements isn't real code.
You need to put something in your else: block.
EDIT:
question can never become True in this code. – #adsmith
NOTE:
Just trying to be comprehensive with my coverage.
The boolean is True in Python, not true or TRUE. In any case, this doesn't do what you expect it to. This is what I'd do.
question = input("...")
if question.lower() == 'y': # or `question in ('y','Y'):` or `question.upper() == "Y":` or `question.casefold() == 'y':` or................
do_things
else:
handle_it
What you had written assigns the variables y and Y to some (undefined) variable TRUE. This will trigger a NameError since there is no such variable TRUE. If you had done:
y = True
Y = True
It still wouldn't have done what you wanted, since your input (fed into the variable question) is a string and those are variables. You could have done that with if globals()[question] but that's really bad practice, and COMPLETELY unnecessary in this situation.
As a side note -- there's never a reason to type == True. if foo will evaluate to True or False, which will fulfill the conditional on its own. It just does a needless compare :)
I think you probably want to use code something along these lines:
answer = raw_input("Do you want the program to start? Type Y/y to start: ")
if answer[0].lower() != "y": # first character not a "Y" or "y"?
exit()
rest of program...
1) You have five (5) spaces indenting your if clause. Should follow Generally Accepted Python Practices (GAPP) ;) (Yes, I just made this up. It may or may not become a thing :p) you should use four (4) spaces.
2) Try adding pass after else:
else:
pass
3) In Python, case matters. As such, boolean testing must be True or False (or 1/0 :p)
4) Don't you mean Y/N? Not Y/y?
Pretty new to python/programming in general, this is my biggest project yet.
I am writing a program that will do SUVAT equations for you. (SUVAT equations are used to find the displacement, start/end velocity, acceleration and time travelled by an object with constant velocity, you may call them something different.)
I made this list:
variables = ["Displacement", "Start Velocity", "End Velocity", "Acceleration", "Time"]
which is used in the following while/for loop:
a = 0
while a==0:
for variable in variables:
# choice1 is what the user is looking to calculate
choice1 = raw_input("Welcome to Mattin's SVUVAT Simulator! Choose the value you are trying to find. You can pick from " + str(variables))
# will execute the following code when the for loop reaches an item that matches the raw_input
if choice1 == variable:
print "You chave chosen", choice1
variables.remove(variable) #Removes the chosen variable from the list, so the new list can be used later on
a = 1 # Ends the for loop by making the while loop false
# This part is so that the error message will not show when the raw_input does not match with the 4 items in the list the user has not chosen
else:
if choice1 == "Displacement":
pass
elif choice1 == "Start Velocity":
pass
elif choice1 == "End Velocity":
pass
elif choice1 == "Acceleration":
pass
# This error message will show if the input did not match any item in the list
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
Hopefully the comments I have written in the code should explain my intentions, if not, feel free to ask anything.
The problem is that when I run the code, and input choice1, the for loop activates the last line of code:
else:
print "Sorry, I didn't understand that, try again. Make sure your spelling is correct (Case Sensitive), and that you did not inlcude the quotation marks."
and then prompts me to enter the input again, and will do this as many times as it needs to get to the item on the list that I am typing.
However, I specifically coded that if what I input does not match the item on the list the for loop is currently checking, but does match one of the other items on the list, then it should pass and loop round to checking the next item.
I am probably doing something stupid, but I don't see it, so please help me figure out what I have to do to get my desired result? I assumed it was the syntax I had wrong so that is why that is the title.
Thanks for any help, I appreciate it.
Besides the problem with the indentation in your pasted code, I would rewrite it as such:
while True:
choice = raw_input('...')
if choice in variables:
print "You chave chosen", choice
# Remove the chosen member from the list
variables = [v for v in variables if v != choice]
# Break out of loop
break
# Print error messages etc.
Also remember that string comparisons are case sensitive. I.e 'Displacement' != 'displacement'.
I'm toying around with writing creating a serial code generator/validator, but I can't seem to get how to do a proper check.
Here's my generator code:
# Serial generator
# Create sequences from which random.choice can choose
Sequence_A = 'ABCDEF'
Sequence_B = 'UVWQYZ'
Sequence_C = 'NOPQRS'
Sequence_D = 'MARTIN'
import random
# Generate a series of random numbers and Letters to later concatenate into a pass code
First = str(random.randint(1,5))
Second = str(random.choice(Sequence_A))
Third = str(random.randint(6,9))
Fourth = str(random.choice(Sequence_B))
Fifth = str(random.randint(0,2))
Sixth = str(random.choice(Sequence_C))
Seventh = str(random.randint(7,8))
Eighth = str(random.choice(Sequence_D))
Ninth = str(random.randint(3,5))
serial = First+Second+Third+Fourth+Fifth+Sixth+Seventh+Eighth+Ninth
print serial
I'd like to make a universal check so that my validation code will accept any key generated by this.
My intuition was to create checks like this:
serial_check = raw_input("Please enter your serial code: ")
# create a control object for while loop
control = True
# Break up user input into list that can be analyzed individually
serial_list = list(serial_check)
while control:
if serial_list[0] == range(1,5):
pass
elif serial_list[0] != range(1,5):
control = False
if serial_list[1] == random.choice('ABCDEF'):
pass
elif serial_list[1] != random.choice('ABCDEF'):
control = False
# and so on until the final, where, if valid, I would print that the key is valid.
if control == False:
print "Invalid Serial Code"
I'm well aware that the second type of check won't work at all, but it's a place holder because I've got no idea how to check that.
But I thought the method for checking numbers would work, but it doesn't either.
The expression `range(1, 5)' creates a list of numbers from 1 to 4. So in your first test, you're asking whether the first character in your serial number is equal to that list:
"1" == [1, 2, 3, 4]
Probably not...
What you probably want to know is whether a digit is in the range (i.e. from 1 to 5, I assume, not 1 to 4).
Your other hurdle is that the first character of the serial is a string, not an integer, so you would want to take the int() of the first character. But that will raise an exception if it's not a digit. So you must first test to make sure it's a digit:
if serial_list[0].isdigit() and int(serial_list[0]) in range(1, 6):
Don't worry, if it's not a digit, Python won't even try to evaluate the part after and. This is called short-circuiting.
However, I would not recommend doing it this way. Instead, simply check to make sure it is at least "1" and no more than "5", like this:
if "1" <= serial_list <= "5":
You can do the same thing with each of your tests, varying only what you're checking.
Also, you don't need to convert the serial number to a list. serial_check is a string and accessing strings by index is perfectly acceptable.
And finally, there's this pattern going on in your code:
if thing == other:
pass
elif thing != other:
(do something)
First, because the conditions you are testing are logical opposites, you don't need elif thing != other -- you can just say else, which means "whatever wasn't matched by any if condition."
if thing == other:
pass
else:
(do something)
But if you're just going to pass when the condition is met, why not just test the opposite condition to begin with? You clearly know how to write it 'cause you were putting it in the elif. Put it right in the if instead!
if thing != other:
(do something)
Yes, each of your if statements can easily be cut in half. In the example I gave you for checking the character range, probably the easiest way to do it is using not:
if not ("1" <= serial_list <= "5"):
Regarding your python, I'm guessing that when your wrote this:
if serial_list[0] == range(1,5):
You probably meant this:
if 1 <= serial_list[0] <= 5:
And when you wrote this:
if serial_list[1] == random.choice('ABCDEF'):
You probably meant this:
if serial_list[1] in 'ABCDEF':
There are various other problems with your code, but I'm sure you'll improve it as you learn python.
At a higher level, you seem to be trying to build something like a software activation code generator/validator. You should know that just generating a string of pseudo-random characters and later checking that each is in range is an extremely weak form of validation. If you want to prevent forgeries, I would suggest learning about HMAC (if you're validating on a secure server) or public key cryptography (if you're validating on a user's computer) and incorporating that into your design. There are libraries available for python that can handle either approach.