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.")
I am making a music key theory test.
In order to achieve something else that I won't explain right now here (maybe I will later though if this doesn't work), I need to take the root chord out of the list, store it somewhere else, and call back upon it for the user input when they are asked what key the chords come from.
I don't know how to do this, but I am pretty sure it is possible. I would love it if someone could help me. After I have this problem sorted out I will be much further.
Before, I was trying to find someway to have the actual variable represent the variable, while representing what the variable contains. So then after printing the randomized chords from the variable, the user can input the key from which the chords come from, which I have as the variable. But I don't think that will work.
import random
print('Key Theory Werkout')
Dmajor = {'D','E-','F⌗-','G','A','B-','C⌗dim'}
Gmajor = {'G','A-','B-','C','D','E-','F⌗dim'}
Cmajor = {'C','D-','E-','F','G','A-','Bdim'}
Fmajor = {'F','G-','A-','Bb','C','D-','Edim'}
Bbmajor = {'Bb','C-','D-','Eb','F','G-','Adim'}
Ebmajor = {'Eb','F-','G-','Ab','Bb','C-','Ddim'}
Abmajor = {'Ab','Bb-','C-','Db','Eb','F-','Gdim'}
Dbmajor = {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'}
Cxmajor = {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'}
Gbmajor = {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'}
Fxmajor = {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'}
Bmajor = {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'}
Cbmajor = {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'}
Emajor = {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'}
Amajor = {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'}
questions = [Dmajor, Gmajor, Cmajor, Fmajor, Bbmajor, Ebmajor,
Abmajor, Dbmajor, Cxmajor, Gbmajor, Fxmajor, Bmajor, Cbmajor,
Emajor, Amajor]
print('Difficulty:Easy, Hard')
begin = input("Choose Difficulty:")
if begin == 'easy':
while begin == "easy":
q = random.choice(questions)
qq = random.sample(list(q), 7)
print(qq)
answer = input('Please Provide the key:')
if answer == q
'''HERE IS THE PROBLEM. Lets say the code outputs F, A-, Bb, C, D-
for Dmajor. How can I have the user type in Dmajor and have it
print correct, or incorrect? I am thinking I will have to put .
entire blocks for each question, and then have the easy choose
random out of all of those questions and that will be how I have to
do it. But maybe there is an easier way.
'''
print("correct")
I would like it to tell the user if they are correct or wrong, while keeping the randomness of questions, and chords it spits out exactly the way it is.
What do I need to do?
Maybe you can try using a dictionary to represent your questions, like this:
questions = {
'Dmajor': {'D','E-','F⌗-','G','A','B-','C⌗dim'},
'Gmajor': {'G','A-','B-','C','D','E-','F⌗dim'},
'Cmajor': {'C','D-','E-','F','G','A-','Bdim'},
'Fmajor': {'F','G-','A-','Bb','C','D-','Edim'},
'Bbmajor': {'Bb','C-','D-','Eb','F','G-','Adim'},
'Ebmajor': {'Eb','F-','G-','Ab','Bb','C-','Ddim'},
'Abmajor': {'Ab','Bb-','C-','Db','Eb','F-','Gdim'},
'Dbmajor': {'Db','Eb-','F-','Gb','Ab','Bb-','Cdim'},
'Cxmajor': {'C⌗','D⌗-','E⌗-','F⌗','G⌗','A⌗-','B⌗dim'},
'Gbmajor': {'Gb','Ab-','Bb-','Cb','Db','Eb-','Fdim'},
'Fxmajor': {'F⌗','G⌗-','A⌗-','B','C⌗','D⌗-','E⌗dim'},
'Bmajor': {'B','C⌗-','D⌗','E','F⌗','G⌗','A⌗dim'},
'Cbmajor': {'Cb','Db-','Eb-','Fb','Gb','Ab-','B-dim'},
'Emajor': {'E','F⌗-','G⌗-','A','B','C⌗-','D⌗dim'},
'Amajor': {'A','B-','C⌗-','D','E','F⌗-','G⌗dim'},
}
Then, you select a random question like this:
key = random.choice(list(questions))
set = questions[key]
sample = random.sample(set, 7)
Now, you only have to check if answer is equal to key.
I am translating a kids choose your own adventure book into a python program eg, 'If you choose x go to page y or if you choose a go to page b'
While this program works, by the end of the book there will be over 100 if statements is there any way to create a table that that compares a user input to a list of pages. An example I saw while researching displayed a similar table to this:
#this would hold the potential user inputs
[0,0,0,0,0,0]
[0,0,0,0,0,0]
[0,0,0,0,0,0]
However i am unsure how to implement it
#imports the pages of the book from another python file
from Content import *
clrscrn = (chr(27) + "[2J")
def page0():
print "\n %s" % page1
page0()
#User input loop
while True:
inp = raw_input(">>> ").lower()
#clears the screen then prints the variable (page)
if inp == '3':
print clrscrn
print '%s' % page3
if inp == '10':
print clrscrn
print '%s' % page10
if inp == '5':
print clrscrn
print '%s' % page5
if inp == '14':
print clrscrn
print '%s' % page14
#quits python
elif inp == 'quit':
raise SystemExit
The only difference in each if statement is which page variable you access. Since you want to get at page14 if the user enters "14" you can use the dictionary returned by globals() to access the page variables in a dynamic way.
So, instead of hundreds of if statement, you really don't need any at all. You can use the following lines instead.
print clrscrn
print globals()['page' + inp]
Define in your head what the inputs and outputs will be.
To me, it seems likely that you will have multiple questions, on different pages. So one input would be the "current page number." That would identify the question.
The other input, of course, would be the user's response. In a binary (yes/no) system, there would always be exactly two possible responses from the user (yes, or no). In a non-binary system, there might be more possible responses.
I'd suggest that you assume non-binary, and further, even if only one question is possibly non-binary, go with that. It helps keep things consistent.
Let's assume, then, that you've got a non-binary system with 100 questions. Each question appears at the end of a "page." (Maybe it's at the end of a "chapter" or "paragraph" or something. Feel free to replace words.) When the user answers, they are directed to go to a different "page."
So your mapping is going to be "current page + user input -> new page".
The easiest way to implement this in python is with a list of dictionaries. The list index can be the current page. That will identify the question, and the possible responses. The responses (keys in the dictionary) can be text strings. The results (values from the dictionary) will be integers, indicating the new page number. Thus:
Pages = [ # List of questions, one per page. Use {} for page with no Q
{}, # 0
{}, # 1
{
"yes": 12,
"no": 16,
}, # 2
]
If you want to be a little more efficient, you can store the questions in the same list, using a key like " q " which cannot be input by the user (because you will run .strip() on the user input, naturally)!
{
" q ": "Do you like pizza?",
"yes": 12,
"no": 16,
}
If you're feeling really energetic, you can make the dictionaries into a class, with attributes, store the various pages as JSON, etc.
I am new to learning python, and I only have limited programing experience, so I am sorry for asking such a basic question. I am doing an online python tutorial and wanted to take the program a bit further than the lesson requested to test out how far I could take it. The problem is that I have been hitting a roadblock. After reading a bunch of posts on here I have moved things around, changed variable names, used more functions, less functions, if else statements, and toyed around/ troubleshot, but have received all sorts of errors. I am going to paste where I currently am at below and would really appreciate if someone out there could help me finish up the program.
Here is what I would like for the program to do:
I would like the user to be prompted to enter a number.
I would like to make sure that the user entered a number, and if they don't I would like the program to give them an error and restart.
I would like that once the number is received the program squares that number and then prints the answer.
(again thanks much for all the help)
HERE IS WHERE I AM AT:
n1 = raw_input('Please enter your desired number:')
def n2():
n2 = n1.isnumeric()
return n2
def square(n2):
squared = n2**2
print "%d squared is %d." % (n2, squared)
return squared
square(n2)
n2 = raw_input("number pls\n")
while not n2.isdigit():
print("why did you do this\n")
n2 = raw_input("number pls\n")
print int(n2)**2
Problems from your code:
You need a control structure which repeatedly tries to do something until the right thing happens. This should make you think "while loop."
isnumeric isn't a method. but you had the right idea.
Naming all of your variables and functions n2 is not a good way to easily see what's going on..
If you want to add a construct for floats, you should write a function which takes a string in and returns true or false based on if it looks like a float! This is a good example for using functions to decompose the problem you're working with- you know you need to do something like
while not (n2.isdigit or isFloat(n2)):
There are some good suggestions here and elsewhere about how to do that :)
You could check if you could convert into float if so print the square else print the error .To repeat this process while you get a number you could use while loop
def number_validator( numb ):
try:
float( numb )
return True
except Exception:
print "GIven input is not a valid number"
return False
def square( n2 ):
n2=float( n2 )
squared = n2**2
print "%s squared is %s." % ( n2 , squared )
return squared
n2 = raw_input( 'Please enter your desired number:' )
while not number_validator( n2 ):
n2 = raw_input( 'Please enter your desired number:' )
square( n2 )
Output:
Please enter your desired number:wq
GIven input is not a valid number
Please enter your desired number:we
GIven input is not a valid number
Please enter your desired number:21.0
21.0 squared is 441.0.
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.