Running python functions from terminal

12,124

Solution 1

import hw1 Then use hw1.fizzbuzz(15)

You can also use:

from  hw1 import fizzbuzz

so you will have imported fizzbuzz into your current namespace and can then call it using fizzbuzz(15).

python modules

import hw1 just imports the module name not all the functions defined in it so either use my_module.my_function or the from my_module import my_function syntax.

Solution 2

Although this question is about executing a function from a python file (as a Module) inside the Python Interpreter in Interactive Mode, it's also possible to run a function or module with a one-liner (i.e. not use the interactive interpreter), as documented in Command line and environment. Amongst others:

When called with -c command, it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. Leading whitespace is significant in Python statements!

While quotation marks for strings etc. need escaping (depending on your environment), I could get the desired output on Windows 10 with Python 3.8 using:

python -c "import hw1; print(hw1.fizzbuzz(15))"
FizzBuzz

I could not simply insert a newline on Windows CMD, so this may be limited to Simple statements:

A simple statement is comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons.

Share:
12,124
prisonbreakx
Author by

prisonbreakx

Updated on June 04, 2022

Comments

  • prisonbreakx
    prisonbreakx almost 2 years

    I'm trying to figure out how to run my functions from my homework file. I opened up terminal, changed the directory to desktop (where my hw1.py file is), started up python, then typed "import hw1". Then I type in fizzbuzz(15) and it returns this statement:

    Traceback (most recent call last): File "<stdin>", line 1, in <module>
    

    My only function I'm trying to run is:

    def fizzbuzz(n):
        if (n % 3) == 0 and (n % 5) == 0:
           return "FizzBuzz"
        elif (n % 3) == 0:
           return "Fizz"
        elif (n % 5) == 0:
           return "Buzz"
    
  • Padraic Cunningham
    Padraic Cunningham over 9 years
    No worries, have a peek at the doc examples I linked to, there are nice easily understandable examples.