Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
evensevenone
May 12, 2001
Glass is a solid.
No.


What is happening with the script? I would imagine it's throwing an exception or something. Is there a traceback?

Adbot
ADBOT LOVES YOU

Sir_Substance
Dec 13, 2013
It's hard to say, I've been directing the output to /dev/null for the moment, I'll redirect it to a file and run it again, I guess. I don't know what would cause it to run a-ok for 30 hours and then suddenly kark it though. It's not like any of the input from the arduino is changing.

Hubis
May 18, 2003

Boy, I wish we had one of those doomsday machines...

Sir_Substance posted:

It's hard to say, I've been directing the output to /dev/null for the moment, I'll redirect it to a file and run it again, I guess. I don't know what would cause it to run a-ok for 30 hours and then suddenly kark it though. It's not like any of the input from the arduino is changing.

out-of-memory / allocation failure?

Dren
Jan 5, 2001

Pillbug

Hubis posted:

out-of-memory / allocation failure?

in application code due to misunderstanding how the serial driver allocates resources, or in the driver itself, or somewhere else entirely.

BeefofAges
Jun 5, 2004

Cry 'Havoc!', and let slip the cows of war.

It could even be a rare timing bug, or issues with a specific unlikely program state, or something like that. It's practically impossible to debug without seeing some code, or logs, or stack traces.

Haystack
Jan 23, 2005





But to answer your basic question: no, python has no problem with long running processes. I've left python web processes running for months without issues.

Sir_Substance
Dec 13, 2013

Hubis posted:

out-of-memory / allocation failure?

Possibly, the code isn't very complex though (yes, I blatantly stole the serial and xmpp init stuff wholesale from stack overflow :v:):

code:
import xmpp
import serial
import datetime

def interface():
    fileName = "SpiLog-"+str(datetime.datetime.now().strftime("%d-%m-%Y_%H-%M-%S"))+".txt"
    ser = serial.Serial('/dev/ttyACM0', 115200,timeout=330)
    #ser = serial.Serial('COM3', 115200,timeout=330)
    #mcguffins to automatically send some init commands to the PI
    print(ser.readline())
    ser.write('N')
    print 'N'
    #mcguffins ends
    while 1:
        message = ser.readline()
        if(message == None or message == ''):
	#if blank or null message within 330 second timeout, arduino has stopped responding 
	#(it regularly sends a heartbeat signal every 300 seconds), send timeout warning over jabber
            message = 'timeout\n'
            dispatchMessage(message)            
        elif('alive' in message):
	#heartbeat message recieved, do nothing because I don't care about heartbeats
            pass
        else:
	#otherwise, echo any message that the arduino sends over jabber
            dispatchMessage(message)
        with open(fileName, "a") as logfile:
	#then log the message
            logfile.write(str(datetime.datetime.now()) + "\n" + str(message))
        #print ser.readline()
        
        
    
    
def dispatchMessage(message):
    username = 'a username'
    passwd = 'a password'
    to='a destination'


    client = xmpp.Client('a server')
    client.connect(server=('a server',5222))
    client.auth(username, passwd, 'rasPI')
    client.sendInitPresence()
    message = xmpp.Message(to, message)
    message.setAttr('type', 'chat')
    client.send(message)

if __name__ == '__main__':
    interface()

I haven't actually taken a long hard look at python memory management, but it's not exactly a verbose consumer of memory.

Dren
Jan 5, 2001

Pillbug
Only thing that looks suspect to me is that xmpp.Client object. There's no cleanup method called for it (like a disconnect or a close) and looking at the API docs it doesn't even look like one exists. Try calling dispatchMessage() over and over in a while loop and watch if the process's memory usage steadily climbs.

Sir_Substance
Dec 13, 2013
If I do that, I'll get flood-banned from the server on the receiving end, it doesn't belong to me :/

salisbury shake
Dec 27, 2011
Start up a whatever Linux instance and install a jabber server to test the script.

diddy kongs feet
Dec 11, 2012

wanna lick the dirt out between ur chimp toes
I've just recently started a first year programming class that teaches using jython and JES so I hope this is the right place to ask.

Mostly it's been a fun class, I played around with programming games and junk in highschool so I only have a really vague leg up on the other students so far. I just went ahead on did the whole first assignment over the weekend, but I'm stressing out because it felt too easy or whatever. More specifically, I got to the last part of the assignment which requires taking several image manipulation effects and letting a user pick which ones to apply and in which order, so I just naturally started using if statements since I remembered using them in highschool and they seemed easy enough in jython. After I wrapped up I went through the tutorial slides and recordings again and realise these haven't so much as been mentioned yet, so I guess we're not meant to know them?
Is there any other simple way to do something like request a selection and then apply the chosen for loop besides if statements? I'm just wondering in case I missed some super fundamental way of doing something like this and got too far ahead or whatever. The way I've got it working right now is I use requestIntegerInRange to ask for 0-9, then go if choicex then apply effect y, with 10 for loops, one for each effect.

suffix
Jul 27, 2013

Wheeee!

diddy kongs feet posted:

I've just recently started a first year programming class that teaches using jython and JES so I hope this is the right place to ask.

Mostly it's been a fun class, I played around with programming games and junk in highschool so I only have a really vague leg up on the other students so far. I just went ahead on did the whole first assignment over the weekend, but I'm stressing out because it felt too easy or whatever. More specifically, I got to the last part of the assignment which requires taking several image manipulation effects and letting a user pick which ones to apply and in which order, so I just naturally started using if statements since I remembered using them in highschool and they seemed easy enough in jython. After I wrapped up I went through the tutorial slides and recordings again and realise these haven't so much as been mentioned yet, so I guess we're not meant to know them?
Is there any other simple way to do something like request a selection and then apply the chosen for loop besides if statements? I'm just wondering in case I missed some super fundamental way of doing something like this and got too far ahead or whatever. The way I've got it working right now is I use requestIntegerInRange to ask for 0-9, then go if choicex then apply effect y, with 10 for loops, one for each effect.

You could use a dict with a mapping from choices to functions, like
Python code:
filter_function_map = {0: apply_filter_foo}
while True:
  choice = ask_user()
  filter_function = filter_function_map[choice]
  img = filter_function(img)
I prefer this to a large chain of elif's, BUT I would be surprised if you learned this technique before you learn about if statements. It's usually considered a bit more intermediate level.

In general I would be suspicious of a solution with 10 for loops. Do these loops have much code in common? Maybe you can extract the differences to variables and reduce it to one or two loops?
Are you writing the effects yourself, or are you using a library?

namaste friends
Sep 18, 2004

by Smythe
I'm having a hard time figuring out what I'm doing wrong here.

I've got two files, 'version.py' and 'version2.py'. 'version.py' was written in pycharm on a windows 7 box and remote deployed (through auto sftp) to a linux box. It runs fine in the linux box as shown in the output below. 'version2.py' is a file I created in vi on the linux box and a straight cut/paste.

Why is the diff output showing that version2.py is completely different to version.py? Pycharm remote reployment shows the encoding as utf-8.

code:
lol@lol:~/test$ python version.py
{"Version": "Ubuntu 12.04.3 LTS \\n \\l\n"}
lol@lol:~/test$ python version2.py
{"Version": "Ubuntu 12.04.3 LTS \\n \\l\n"}
lol@lol:~/test$ diff version.py version2.py
1,10c1,9
< #!/usr/bin/python
<
< import commands
< import json
<
< version = commands.getstatusoutput('cat /etc/issue')
< print json.dumps({
<     "Version" : version[1]
< })
<
---
> #!/usr/bin/python
>
> import commands
> import json
>
> version = commands.getstatusoutput('cat /etc/issue')
> print json.dumps({
>     "Version" : version[1]
> })
lol@lol:~/test$


Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
Line endings.

supercrooky
Sep 12, 2006

Cultural Imperial posted:

I'm having a hard time figuring out what I'm doing wrong here.

I've got two files, 'version.py' and 'version2.py'. 'version.py' was written in pycharm on a windows 7 box and remote deployed (through auto sftp) to a linux box. It runs fine in the linux box as shown in the output below. 'version2.py' is a file I created in vi on the linux box and a straight cut/paste.

Why is the diff output showing that version2.py is completely different to version.py? Pycharm remote reployment shows the encoding as utf-8.


It's probably line endings, CRLF for the windows file, LF for the linux file.

namaste friends
Sep 18, 2004

by Smythe
This makes no sense.

code:
lol@lol:~/test$ file -bi version.py
text/x-java; charset=us-ascii
lol@lol:~/test$ file -bi version2.py
text/x-java; charset=us-ascii
lol@lol:~/test$

namaste friends
Sep 18, 2004

by Smythe
Ah ok thanks guys.

edit: Ok I can get this all to work now. I had to change the project file encoding from utf-8 to US-ASCII. Weird.

namaste friends fucked around with this message at 19:49 on Mar 23, 2014

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer

Maluco Marinero posted:

I'm setting up CI for a project, first time using Python in that context and I'm wondering what approach is best.

From my brief investigation so far it seems like tox can be fed my requirements.txt so I can spin up a virtualenv and run tests in the QA phase, and after that, deploying should I just use tox on the deployment target? Or should I be using pex or wheels or something like that. In most cases I'll definitely be deploying to another Linux server, but not always sure whether it'll be rpm or Debian.

Any advice from people who've done it before?

For my build process at work (currently our lone python project amongst a sea of ruby/java) it's a bit of a weird mix at the moment as our deployment and build scripts themselves are Go (not the language) CI and its Ruby Rakefile based system. I have the following build process:

Build Server:
- Pulls latest copy of code from mercurial
- Grab get-pip.py and run with the flag to install to ~/.local
- Grab python appropriate source tgz for headers, install to ~/.local/python-2.x
- local-pip installs virtualenv locally
- local-pip populates virtualenv with requirements.txt
- run unit tests
- package server + virtualenv into rpm, upload to repo

Deploy Server:
- Pulls rpm from build server repo
- installs, post-install scripts handle root level stuff like /etc
- unit tests

If I had my choice I would move building the packages themselves into their own pipeline as pip wheels. We maintain a clean environment between builds and it can take 5-10 minute for something like lxml to build depending on server load.

sofokles
Feb 7, 2004

Fuck this

vikingstrike posted:

Write a function in whatever language you want to do the "speak" part and then use os.system to call it. With this approach you would use python to generate the arguments to pass to your other function.

Did just that. 4 lines of console application code in C# with a reference to System.Speech.dll and it worked well. Microsoft Anna speaks like a true civil aviator.

Now I wonder if I could wrap that System.Speech.dll with ctypes and make Python speak like Anna.


First tried using pywin32 and that bluescreened and messed my file system up right after installation. Guess that's what System Restore is for.

Anyway : Where can I get Darth Vader's voice? Or Borat? Or that bad guy from Police Academy ?

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
With virtualenvwrapper, how do you handle persisting the Per-User Customization. I am hesitant to use it because I know I'll forget about it when I do a rmvirtualenv or something. I suppose I could symlink it to files that are stored elsewhere in source control, seems kinda messy though. Any suggestions?

Dominoes
Sep 20, 2007

Hey dudes. Is there a way to automatically make matplotlib scale y values based on a set x limit. For example, the code I set below does it somewhat manually.

Python code:
plt.xlim(start_date.date(), end_date.date())
displayed_data = self.data[symbol][attribute][start_date.date(): end_date.date()]
highest, lowest = max(displayed_data) * 1.05, min(displayed_data) * .95
plt.ylim(lowest, highest)
Is there something like this?:
plt.xlim(start_date.date(), end_date.date(), yscale=auto)

ahmeni
May 1, 2005

It's one continuous form where hardware and software function in perfect unison, creating a new generation of iPhone that's better by any measure.
Grimey Drawer

fletcher posted:

With virtualenvwrapper, how do you handle persisting the Per-User Customization. I am hesitant to use it because I know I'll forget about it when I do a rmvirtualenv or something. I suppose I could symlink it to files that are stored elsewhere in source control, seems kinda messy though. Any suggestions?

It looks like $VIRTUALENVWRAPPER_HOOK_DIR itself doesn't have to be inside the virtualenv itself, so you could just point the environment variable to another directory in the source tree.

salisbury shake
Dec 27, 2011
Beginning to clean up the SomethingAwful Forums module I've posted about, which is under the vanilla GPLv3 now. The components conform to an interface, redundant and extraneous attributes have been consolidated or removed amd broken imports have been quarantined from the stable importable code.
I'm adding comments and rewriting portions that were thrown together from the REPL, so hopefully it won't be too convoluted and will end up being something worth using.

Unsurprisingly, search is broken.

Python code:

In [1]: from AwfulPy import AwfulPy

In [2]: ap = AwfulPy('salisbury shake')
Loading from backup: .salisbury_shake3.bak
Finished loading from backup.

In [3]: from pprint import pprint

In [4]: pprint(ap.index.forums)
{155: SA's Front Page Discussion,
 214: E/N Bullshit,
 1: GBS ,
 154: FYAD V,
 26: FYAD,
 48: Main,
 145: The MMO HMO,
 93: Private Game Servers,
 103: The Game Room,
 234: Traditional Games,
 191: Let's Play!,
 44: Games,
 192: Inspect Your Gadgets,
 162: Education & Academics,
 211: Tourism & Travel,
 200: Business, Finance, and Careers,
 158: Ask / Tell,
 46: Debate & Discussion,
 170: Haus of Tech Support,
 202: The Cavern of COBOL,
 219: YOSPOS,
...

In [5]: coc = ap.index.forums[202]

In [6]: coc.read()

In [7]: coc.
coc.base_url   coc.name       coc.page       coc.parent     coc.session    coc.threads    coc.url        
coc.id         coc.navi       coc.pages      coc.read       coc.subforums  coc.unread     

In [8]: pprint(coc.threads)
{2779598: Ask General Programming Questions Not Worth Their Own Thread,
 2836504: Cavern of Cobol FAQ (Read this first and check out project.log!),
 2773485: C/C++ Programming Questions Not Worth Their Own Thread,
 3607482: Oldie Programming: Career Advice, Questions, Change of Directions,
 3571035: Modern front-end development: skinny jeans and handlebar mustaches ITT,
 3376083: Newbie Programming Interviews/Get a Job Megathread: How do I linked list?,
 2841382: Post screenshots of stuff you're working on!,
 3491072: My Code is Fragmented - Android Development Megathread,
 3554791: The Web Design & Development Megathread,
 2692947: Game Development Megathread,
 2262300: .Net Questions Megathread Part 2,
 2585949: Ruby on Rails Love-In,
...


In [10]: python_thread = next(thread for thread in coc.threads.values() if 'Python' in thread.title)

In [11]: python_thread.read()
In [12]: python_thread.
python_thread.base_url   python_thread.last_read  python_thread.navi       python_thread.parent     python_thread.session    python_thread.url
python_thread.icon       python_thread.lastpost   python_thread.page       python_thread.posts      python_thread.title      python_thread.user_id
python_thread.id         python_thread.name       python_thread.pages      python_thread.read       python_thread.unread     

In [13]: post_body = 'WAIT WUT'

In [14]: ap.session.reply(python_thread.id, post_body)

SurgicalOntologist
Jun 17, 2004

Holy poo poo packaging is so confusing. I'm using setuptools and it just fills my directory with junk that seems to cause problems. For example, when running python setup.py install for the second+ time from the same directory, I was getting a cryptic error, so I added this to setup.py that fixed the problem:
Python code:
if os.path.exists('dist') and sys.path[0] == 'experimentator':
    shutil.rmtree('dist')
There's probably a better way to handle that, if anyone knows what's going on there let me know.

However, I'm actually posting because of another problem. I've been experimenting with sphinx-apidoc and was so confused about what I was seeing, until I realized that it was looking in the .egg-info directory despite the fact that the actual source directory is specified in the command-line arguments. So is the fix here to just add another rmtree to setup.py? Or am I required to run python setup.py install before the sphinx command? This all seems so hacky. The setuptools documentation is profoundly unhelpful.

Edit: Actually sphinx is looking in site-packages. That can't be right, why have a (required) command-line argument called <module-path> but look somewhere else?

Edit2: Also not sure about napoleon vs. numpydoc. Napoleon is packaged with Sphinx, so that's a plus. Everything I could find suggested they did the same thing, but it looks like following the numpydoc guide with napoleon didn't quite work. It doesn't understand a Yield section for example, and it doesn't automatically search for classes/attributes/whatever when you use backticks but instead seems to require you to use :class: or whatever. So I'm trying numpydoc. But maybe I'm missing something...

SurgicalOntologist fucked around with this message at 03:44 on Apr 2, 2014

BigRedDot
Mar 6, 2008

SurgicalOntologist posted:

Edit2: Also not sure about napoleon vs. numpydoc. Napoleon is packaged with Sphinx, so that's a plus. Everything I could find suggested they did the same thing, but it looks like following the numpydoc guide with napoleon didn't quite work. It doesn't understand a Yield section for example, and it doesn't automatically search for classes/attributes/whatever when you use backticks but instead seems to require you to use :class: or whatever. So I'm trying numpydoc. But maybe I'm missing something...
I switched to Napoleon and have not looked back. I like the Google docstring format better, and even when everything is working perfectly numpydoc often spits out hundreds/thousands of spurious warnings just because.

Regarding setuptools, I strive never to use it. We ripped it out of all our setup.py's, for "develop" mode we just write a .pth file by hand.

SurgicalOntologist
Jun 17, 2004

I actually got rid of all the warnings with this in conf.py:
code:
numpydoc_class_members_toctree = False
And it turned out that both those features I was complaining out not being in Napoleon were not actually in the numpydoc reference. I could have sworn I read somewhere that there's a way to just use backticks and skip the :class: or whatever, and it will search your package for the reference. But maybe I'm making that up.

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb
This code:

Python code:
from datetime import datetime
from pytz import timezone
from pprint import pprint

kiri_tz = timezone('Pacific/Kiritimati')
kiri_time = datetime.now().replace(tzinfo=kiri_tz)
pprint(kiri_time)
print(kiri_time)
Prints out:

code:
datetime.datetime(2014, 4, 2, 16, 21, 32, 987836, tzinfo=<DstTzInfo 'Pacific/Kiritimati' LINT-1 day, 13:20:00 STD>)
2014-04-02 16:21:32.987836-10:40
Why the 13:20 vs. -10:40 discrepancy with the offset? Also, Wikipedia has Pacific/Kiritimati @ +14:00?

edit: oh I think I answered my own question:

Python code:
kiri_time2 = datetime.now(tz=utc).astimezone(kiri_tz)
pprint(kiri_time2)
print(kiri_time2)
code:
datetime.datetime(2014, 4, 3, 13, 26, 12, 266531, tzinfo=<DstTzInfo 'Pacific/Kiritimati' LINT+14:00:00 STD>)
2014-04-03 13:26:12.266531+14:00

fletcher fucked around with this message at 00:27 on Apr 3, 2014

Dominoes
Sep 20, 2007

It looks like replace() swaps out the timezone while leaving the date/time the same, while astimezone() actually converts it.

Dominoes fucked around with this message at 00:32 on Apr 3, 2014

SurgicalOntologist
Jun 17, 2004

I'm trying to read the stdout from a process and stop blocking once I get a sentinel value (the process sometimes takes 1 min to initialize, sometimes 10 seconds, so I got tired of always waiting 1 minute).
Python code:
        logger.info('Starting server process...')
        self.process = subprocess.Popen(server_args,
                                        stdout=subprocess.PIPE if self.sentinel else None,
                                        stderr=subprocess.STDOUT if self.sentinel else None,
                                        universal_newlines=True)
        logger.warning('Server PID: {}'.format(self.process.pid))

        if self.sentinel:
            logger.info('Waiting for string "{}"...'.format(self.sentinel))
            start_time = time.time()
            std_out = ''
            while self.sentinel not in std_out:
                if time.time() - start_time >= self.wait:
                    logger.warning('Waited {} s, giving up.'.format(self.wait))
                    break

                try:
                    std_out, _ = self.process.communicate(timeout=0.5)
                    print(std_out, end='')
                except subprocess.TimeoutExpired:
                    pass

            print('\n')

        else:
            logger.info('Waiting {} seconds...'.format(self.wait))
            time.sleep(self.wait)
But communicate doesn't seem to be working as I expect it to. Nothing gets printed to the console (and I know it should because the process initialized alright). This whole thing is a bit tricky, do I have the right overall idea? And if so, can anyone see where I went wrong?

QuarkJets
Sep 8, 2008
Probation
Can't post for 2 hours!
Instead of using communicate like that, try:

code:
for line in self.process.stdout:
    std_out = line
    print line

Lurchington
Jan 2, 2003

Forums Dragoon
a relevant stack overflow post:
http://stackoverflow.com/a/17698359/171094

builds on the answer that QuarkJets suggests

lufty
Jan 26, 2014
code:
#Dice Roller
import random #imports the random feature, allows randomisation of given values

def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    if UserInput == "Yes" or "yes":

return:
    exit(0)

def RollFunc():
    DiceRoll = input("Which sided dice would you like to roll, a 4, 6 or 12 sided dice?\n") #asks the user for their choice of dice

if DiceRoll == "4" or "four" or "Four":
    FourVar = random.randint (1, 4)
    print("You have rolled a four sided die, resulting in", FourVar".")

elif DiceRoll == "6" or "six" or "Six":
    SixVar = random.randint (1, 6)
    print("You have rolled a six sided die, resulting in", SixVar".")

elif DiceRoll == "12" or "twelve" or "Twelve":
    TwelveVar = random.randint (1, 12)
    print("You have rolled a twelve sided die, resulting in", TwelveVar".")

else:
    print("Not a valid input.")
    RollFunc()

while True:
    RollFunc()
    RollRepeat()
i'm getting an "expected an indented block" error on line "return:", any solutions?
i've set my indentation width to 4 spaces and manually typed it all out as the previous copy had other indentation errors.

sorry for my shite code btw

SurgicalOntologist
Jun 17, 2004

return is not a keyword that defines a new indentation section. So there shouldn't be a colon after it, with code after. You probably meant this:
Python code:
def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    if UserInput == "Yes" or "yes":
        return
Also, when you have a line like this:
Python code:
if DiceRoll == "4" or "four" or "Four":
The phrases if DiceRoll == "4" and "Four" and "four" are all evaluated for truthiness independently. Non-empty strings are always true, so that if block will always fire. You probably want:
Python code:
if DiceRoll in ("4", "Four", "four"):
Which is an easier way of writing
Python code:
if DiceRoll == "4" or DiceRoll == "Four" or DiceRoll == "four":
Finally, it looks like everything starting with if DiceRoll == "4" until while True: needs to be indented one more level so it will fall under the RollFunc function.

lufty
Jan 26, 2014

SurgicalOntologist posted:

return is not a keyword that defines a new indentation section. So there shouldn't be a colon after it, with code after. You probably meant this:
Python code:
def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    if UserInput == "Yes" or "yes":
        return
Also, when you have a line like this:
Python code:
if DiceRoll == "4" or "four" or "Four":
The phrases if DiceRoll == "4" and "Four" and "four" are all evaluated for truthiness independently. Non-empty strings are always true, so that if block will always fire. You probably want:
Python code:
if DiceRoll in ("4", "Four", "four"):
Which is an easier way of writing
Python code:
if DiceRoll == "4" or DiceRoll == "Four" or DiceRoll == "four":
Finally, it looks like everything starting with if DiceRoll == "4" until while True: needs to be indented one more level so it will fall under the RollFunc function.

I'm still getting an "expected indentation block" error
Python code:
#Dice Roller
import random #imports the random feature, allows randomisation of given values

def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    if UserInput == "Yes" or "yes":
        return

def RollFunc():
    DiceRoll = input("Which sided dice would you like to roll, a 4, 6 or 12 sided dice?\n") #asks the user for their choice of dice

    if DiceRoll in ("4", "four", "Four"):
    FourVar = random.randint (1, 4)
    print("You have rolled a four sided die, resulting in", FourVar".")

    elif DiceRoll in ("6", "six", "Six"):
    SixVar = random.randint (1, 6)
    print("You have rolled a six sided die, resulting in", SixVar".")

    elif DiceRoll in ("12", "twelve", "Twelve"):
    TwelveVar = random.randint (1, 12)
    print("You have rolled a twelve sided die, resulting in", TwelveVar".")

    else:
    print("Not a valid input.")
    RollFunc()

while True:
    RollFunc()
    RollRepeat()

SurgicalOntologist
Jun 17, 2004

You always need to indent after a colon. In this code, you need to indent after every if or elif (indent the code that you want to run conditionally).

E: and you still have a bare string in an 'or' clause in that first function.

E2: you also have bad syntax in your print functions. You want something like this:
Python code:
print("You have rolled a twelve sided die, resulting in {}.".format(TwelveVar))

SurgicalOntologist fucked around with this message at 14:17 on Apr 7, 2014

vikingstrike
Sep 23, 2007

whats happening, captain

lufty posted:

I'm still getting an "expected indentation block" error
Python code:
#Dice Roller
import random #imports the random feature, allows randomisation of given values

def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    if UserInput == "Yes" or "yes":
        return

def RollFunc():
    DiceRoll = input("Which sided dice would you like to roll, a 4, 6 or 12 sided dice?\n") #asks the user for their choice of dice

    if DiceRoll in ("4", "four", "Four"):
    FourVar = random.randint (1, 4)
    print("You have rolled a four sided die, resulting in", FourVar".")

    elif DiceRoll in ("6", "six", "Six"):
    SixVar = random.randint (1, 6)
    print("You have rolled a six sided die, resulting in", SixVar".")

    elif DiceRoll in ("12", "twelve", "Twelve"):
    TwelveVar = random.randint (1, 12)
    print("You have rolled a twelve sided die, resulting in", TwelveVar".")

    else:
    print("Not a valid input.")
    RollFunc()

while True:
    RollFunc()
    RollRepeat()

You need to fix that inner function, at the very least:

code:
def RollFunc():
    DiceRoll = input("Which sided dice would you like to roll, a 4, 6 or 12 sided dice?\n") #asks the user for their choice of dice

    if DiceRoll in ("4", "four", "Four"):
    	FourVar = random.randint (1, 4)
    	print("You have rolled a four sided die, resulting in", FourVar".")

    elif DiceRoll in ("6", "six", "Six"):
    	SixVar = random.randint (1, 6)
   	print("You have rolled a six sided die, resulting in", SixVar".")

    elif DiceRoll in ("12", "twelve", "Twelve"):
    	TwelveVar = random.randint (1, 12)
    	print("You have rolled a twelve sided die, resulting in", TwelveVar".")

    else:
    	print("Not a valid input.")
    	RollFunc()

namaste friends
Sep 18, 2004

by Smythe
Lufty, your if code blocks aren't indented. Try cut pasting into here http://pep8online.com/

I use pycharm and I find its code inspection feature really useful.

lufty
Jan 26, 2014
Python code:
#Dice Roller
import random #imports the random feature, allows randomisation of given values

def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    if UserInput == ("Yes", "yes", "y"):
        return

def RollFunc():
    DiceRoll = input("Which sided dice would you like to roll, a 4, 6 or 12 sided dice?\n") #asks the user for their choice of dice

    if DiceRoll in ("4", "four", "Four"):
        FourVar = random.randint (1, 4)
        print("You have rolled a four sided die, resulting in {}".format(FourVar))

    elif DiceRoll in ("6", "six", "Six"):
        SixVar = random.randint (1, 6)
        print("You have rolled a six sided die, resulting in {}".format(SixVar))

    elif DiceRoll in ("12", "twelve", "Twelve"):
        TwelveVar = random.randint (1, 12)
        print("You have rolled a twelve sided die, resulting in {}".format(TwelveVar))

    else:
        print("Not a valid input.")
        RollFunc()

while True:
    RollFunc()
    RollRepeat()
It's working, but now I need the Roller to end after declining to try again.

Any chance I could cut the code down, and streamline it?

For reference, if it helps:

lufty fucked around with this message at 14:48 on Apr 7, 2014

SurgicalOntologist
Jun 17, 2004

Python code:
def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    return UserInput in ("Yes", "yes", "y")

...

while RollRepeat():
    RollFunc()

Adbot
ADBOT LOVES YOU

lufty
Jan 26, 2014

SurgicalOntologist posted:

Python code:
def RollRepeat():
    UserInput = input("Do you want to try again? Type Yes or No.\n")
    return UserInput in ("Yes", "yes", "y")

...

while RollRepeat():
    RollFunc()


i'm not quite sure how this fits in?

  • Locked thread