Trying to make a dice rolling script in python [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm getting a vague syntax error with the print int(rollval) on line 15.
from random import randint
roll == 0
def diceroll(roll):
def dicenum(userdicenum):
userdicenum = int(raw_input("How many dice would you like to roll?"))
return userdicenum
def dicesides(userdiceside):
userdiceside = int(raw_input("How many sides for each die?"))
return userdiceside
for rollval in range(1,userdicenum):
rollval = randint(1,userdiceside)
print int(rollval)
roll = roll + rollval
return roll
print roll

from random import randint
def diceroll():
def dicenum():
userdicenum = int(input("How many dice would you like to roll?"))
return userdicenum
def dicesides():
userdiceside = int(input("How many sides for each die?"))
return userdiceside
roll = 0
dicesida = dicesides() # so you dont have to re type it =)
for rollval in range(dicenum()):
rollval = randint(1,dicesida)
print(int(rollval))
roll = roll + rollval
return roll
print(diceroll())
is this what you want?

One difference between Python3 and Python2 is that in Python3, the print statement is a function in Python3, but a keyword in Python2. The fact that it is a function means that you have to use it like any other function, which is by putting the arguments within parenthesis.
Use print(int(rollval))
You should also have a look at the second line. roll == 0 should probably be roll = 0. And as mentioned in comments, you should also not use raw_input in Python3. Use input.

Related

How to have a function feed another function's input [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making a hangman game and testing how different letter picking algorithms fare, but to do this, the guessing algorithm function has to feed a letter into the hangman function's input('Select a letter').
How do you make it so that a function detects when another function is waiting for an input ?
Assuming you are doing input() in a loop inside your hangman function, you could switch that to a yield and let an external function drive input as needed. In this example I have a hangman function that uses yield to get data. Now its a generator and driving function can use next and the generator's .send method to pump data into it.
def hangman(chances=5):
for i in range(chances):
letter = yield "prompt"
if letter == "quit":
yield "quit"
return
print("letter", letter)
# do all the things
solved = False
if solved:
yield "solved"
yield "failed"
def command_line_prompt_hangman():
feeder = hangman()
state = next(feeder)
while state == "prompt":
state = feeder.send(input("Next letter: "))
def test():
# after years of testing the best algorithm is
test = ['a', 'b', 'c', 'd', 'e', 'f']
feeder = hangman()
assert next(feeder) == "prompt"
for count, letter in enumerate(test, 1):
state = feeder.send(letter)
if state == "solved":
print("did it in ", count, "tries")
break
if state == "failed":
print("exceeded count")
break
command_line_prompt_hangman()
test()
Instead of using the input function, write a custom function to pull an output from whatever algorithm you are using. That would look something like this:
user_input = algo_obj.get_input(game_state)
In this case, algo_obj would be an object storing the current state of the algorithm/generator (if such a state exists, otherwise you can just call the function normally). game_state would be some representation of the game's current state (available letters, the word-form -- ie. blanks & letters).
You can then feed user_input to your Hangman function.
This should be as simple as:
Define both functions.
Pass one function return value to the other one as argument.
This can be done by using input() as according to this
e.g. Define the functions
def first_function():
input_variable = input("Please enter some data")
return input_variable
def second_function(a):
print(a) # Do some calculations here
And use them:
second_function(first_function())
I wouldn't say that this is necessarily the best way to go about but it solves Your problem. If You would like to receive a more detailed answer please provide code samples.

I keep getting None returned from my python program

The code is as followed
# Cristmas Quiz
import time
from time import *
score = 1
quiz_q = [
'how many turtle doves',
'how many French Hens',
'how many gold rings',
'how many Lords a leaping?'
]
quiz_a = [2,3,5,10]
for n in range(4):
question = input(print(quiz_q[n]))
if quiz_a[n] == question:
score += 1
else:
print("your score was ",score-1)
time.sleep(5)
quit()
which returns this:
how many turtle doves
None
I had a look around, but all the other qustion seemed to be refering about functions and the use of return vs print()
any help would be appreciated
As suggested in the comments, I'm reformatting my comment as an answer. I will attempt to elaborate on my explanation.
You are calling the print function, which outputs the text, then returns None. This may not be intuitive, but None is returned from any function that doesn't return anything else.
The None is then passed to the input function as a parameter, which transforms it into text, outputs that and then waits for input.
The "input()" call should only take a string as an argument, not a print function:
for n in range(4):
question = input(quiz_q[n])
# ...

Why does my while loop not stop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
RANDOM_COR=random.randrange(5,6)
def check_xy_data():
global COUNT
COUNT=0
input_xy=input("input(x,y) : ")
think_xy=list(map(int,input_xy.split(",")))
if(random_array[think_xy[0]][think_xy[1]] == "C"):
screen_array[think_xy[0]][think_xy[1]] = "O"
COUNT=COUNT+1
else:
screen_array[think_xy[0]][think_xy[1]] = "X"
def main():
make_intro()
init_screen_array ()
init_random_array ()
make_random_num(RANDOM_COR)
while(True):
check_xy_data()
draw_outline_start(TOTAL_COL_NUM//2)
draw_out_rowline(TOTAL_COL_NUM//2, "Input : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Correct : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Error : ")
draw_out_rowline(TOTAL_COL_NUM//2, "Total : ")
draw_outline_mid(TOTAL_COL_NUM//2)
if(COUNT==RANDOM_COR-1):
break
The if at the bottom of my code is supposed to get me out of the while loop, but I'm stuck in an infinite loop. Help?
(assignment, 2016) 예고편 The Assignment | 어싸인먼트 감독: 월터 힐 각본: 월터 힐, 데니스 해밀 출연: 김성훈 출연 현빈, 유해진, 김주혁 개봉 2016 한국 상세보기 그간...
Try this change:
RANDOM_COR=random.randrange(5,6)
COUNT = 0
def check_xy_data():
global COUNT
With COUNT inside check_xy_data, you set it back to 0 on every call. It can never reach more than 1. Your check is whether it's in the range 5-6. This is never true, so you can never leave the loop.
Note that trivial debugging skills would have found this: just stick a print statement before you test your loop condition, to see what the values are. Use that next time ... :-)

Newbie query about conditional statements [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm learning Python and can't work out why the following doesn't work.
Can anyone advise? code below
thanks
# Make sure that the_flying_circus() returns True
print "What is your number?"
num = input()
print "What is bla?"
bla = input()
def the_flying_circus():
if num ==4 and bla=="bla": # Start coding here!
return True
print "Well done!"
# Don't forget to indent
# the code inside this block!
elif num == 2 or bla== zog:
print "OK"
# Keep going here.
# You'll want to add the else statement, too!
else:
print "Bad luck!"
the_flying_circus()
The return True is probably not what you want to have on the top of the if block. Try removing it.
The only condition that will return True is num==4 and bla=='bla'. Otherwise, the return value is None. However, 'Well done!' will never be printed since the return statement occurs first.
Couple of things...
1) return True should be moved to the end of the function (as mentioned by others)
2) watch how you collect input... use raw_input for your string, use input for the number.
This works for me:
def the_flying_circus():
if a==4 and b=='bla':
print "Well done!"
elif a==2 or b=="zog":
print "OK"
else:
print "Bad luck!"
return 1
a = input("What is your number? ")
b = raw_input("What is bla? ")
the_flying_circus()

How do Arguments and Parameters Work in Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have looked all over Stackoverflow and I can't find an answer, and all the web tutorials just go right over my head. I have a functioning code that I don't understand
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy nd hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('do you want to play again? (yes or no)')
playAgain = input()
I don't understand the def checkCave(chosenCave): parts, why does the argument say chosenCave?
Can someone explain please?
In the function
def checkCave(chosenCave):
...
chosenCave becomes a local variable that you passed to the function. You can then access the value inside that function to process it, provide whatever side-effects you're looking to provide (like printing to the screen, as you're doing), and then return a value, (which if you don't do explicitly, Python returns None, its null value, by default.)
Algebraic Analogy
In algebra we define functions like this:
f(x) = ...
for example:
f(x) = x*x
In Python we define functions like this:
def f(x):
...
and in keeping with the above simple example:
def f(x):
return x*x
When we want the results of that function applied to a particular x, (e.g., 1), we call it, and it returns the result after processing that particular x.:
particular_x = 1
f(particular_x)
And if it returns a result we want for later usage, we can assign the results of calling that function to a variable:
y = f(particular_x)
The name chosenCave appears to have been chosen to describe what it represents, namely, the cave the player chose. Were you expecting it to be named something else? The name isn't required to match or not match any names located elsewhere in the program.

Categories