Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

This is my program. This program basically is a prime number check. It will see if your number that you type in is a prime number or not. If it is then it will say "is a prime number"
The question that i am having is wondering how my main function can be contained in a while loop and at the end ask if i would like to test another number. If i type in y it should run again.



def main():
print("Mirage Jelani's Prime Number Checker")
user_number = int(input("Please enter a number:"))
if is_prime(user_number):
print(user_number, "is prime")
else:
print(user_number, "is NOT prime")

def is_prime( num ):
even_div = 0
if num <= 1:
return False
for currentnum in range (1,num + 1):
if num % currentnum == 0:
even_div = even_div + 1
if even_div > 2:
return False
return True

main()
0
Hire Technology Freelancers with Gigs
LVL 10
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Hi

I'm hoping somebody can help me with the following Python question:

I have been using sympy to generate a function e.g. 5*x**3 - 375*x + 18 called polynomial. The type is: <class 'sympy.core.add.Add'>

>>> polynomial
5*x**3 - 375*x + 18

I want to plot this function using something like:

x_axis = np.arange(-10,10,0.01)

plt.plot(x_axis, polynomial)

However, when I attempt this, I get the following:

Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    plt.plot(x_axis, polynomial)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\pyplot.py", line 3161, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\__init__.py", line 1819, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_axes.py", line 1382, in plot
    for line in self._get_lines(*args, **kwargs):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_base.py", line 381, in _grab_next_args
    for seg in self._plot_args(remaining, kwargs):
  File "C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_base.py", line 359, in _plot_args
    x, y = self._xy_from_xy(x, y)
  File …
0
Hi,

We have Windows 10 laptops each with a local administrator account for our teachers, and one or more local standard user accounts for our students. Now and then these standard user accounts are deleted and new ones are added as students come and go.

Now, I have tried to install Python 3.6.2 for ALL users from within the adminstrator account, hoping that the students then can start all the installed components from within their standard user accounts. But when I log in to these standard accounts I cannot find the applications I installed into my administrator account.

Thus if I log into the adminstrator account, there is a Python 3.6 folder with IDLE, Python application, Python 3.6 module Doc and Python manuals. However if I log into the standard user account, I cannot see those items at all?

How to I install Python 3.6 on a Windows 10 PC so that also other user accounts on that machine can use Python in the same way as they would be able to do if they were logged into the administator account?

Thanks!
0
Hi,
My  7th grader has a probability problem I am trying to write a small script for.

"If you have a spinner with three letters on on (K,V and H) and you spin it three times, list all possible outcomes."
The number of outcomes is 27. I won't list them all here, but it's along the lines of KKK, KVH, VHK, VVK, etc... you get the idea. We have them all listed out already and the HW problem is solved.

I was thinking a small perl script would be fun to write to calculate this. But it's harder then I anticipated. I created an AOA but I can't figure out how to loop through it to get every combo.

I tried a nested for loop but that's not working.

@letters = (
['K','V','H'],
['K','V','H'],
['K','V','H'],
);

for ($i=0; $i<3; $i++){


        for ($j=0; $j<3; $j++){
        print "i=$i, j=$j\n";
        print $letters[$i][$j];
        }
print "\n";
}

I am posting this in Python also as I could do it in python if I can get the logic right.

Thanks!
Nacht
0
can anyone create this type of batch?
I run this Simple-Script.bat:
python my.py -w200
python my.py -w132
python my.py -w900
python my.py -w211

Open in new window

Each line runs well ---> python.exe process opens for each line(do his job) then closes automatically,but it seems that some lines cause problems,python.exe process opens but it never closes and i receive this error message:
failure code 5

Open in new window


Can someone make python.exe automatically when a line receives that error? then continue with the next (line) command?
thxx!

P.S.
or if someone knows the Python scripts can change directly from there.
0
I have never used classmethod in my code, appreciate if I can get some example on how to use and which condition it will be beneficial? Thanks!
0
I would like to access a url say example.company.com but it's protected via okta. I have my user and password which I login via chrome and access. though I would like to access it via python + requests module.

Appreciate if I can get a leads on how should I proceed here. Thanks!
0
Hello Experts,

I have number of HP blade enclosures to pull data from.  I've written a Python script to SSH to the enclosures and retrieve the data.   The script works but takes about 3 hours to complete.   Although the bulk of the code in the script parses the data, the bulk of the time involved is in setting the SSH session to each server.   Thus what I'd like to do is establish a means to run the processes in parallel.    I'm hoping someone can give me pointers in the right direction.

What I've Tried


1. My first stab at this with with the Parallel-SSH module (https://pypi.python.org/pypi/parallel-ssh).   That would have been the cleanest solution.   However, although I was able to connect to my enclosures, I was unable to retrieve output from any of my commands.  
2.  My current work around is to use Python's Multiprocessing module and specifically a pool as that seemed to be the simplest solution.   However, that's not working.   From the output the use of pool.imap results in mangled IP addresses.  Consider the following:

('OA IP is: ', u'1')
Now Processing OA 1.
Cannot connect to OA: 1.
[Errno None] Unable to connect to port 22 on 0.0.0.1

Here are some code snippets
def automatic_mode():
    enclosure_results_lst = []
    try:
        enclosures_lst = get_chassis_data() 
        # Function pulls IP addresses from another systm
        # Function return a Python list.  Example below
        # enclosures_lst = ['10.0.0.1', '10.0.0.1', 

Open in new window

0
Hi: Don't you just hate banks?
We have changed bank and I download all the data  for analysis.  Our new bank offers only csv format. No problem...EXCEPT that for direct debits and standing orders the text field has a comma inserted! It looks to me that the comma is inserted just prior to the word MANDATE.
Dopes anybody know how to write something in python that deletes (or replaces with a semi colon) a comma that appears just before the word MANDATE in a csv file?
Here is a snippet of the text field:
"DIRECT DEBIT PAYMENT TO XXXX PENSION REF 09999999991, MANDATE NO 9999"
See that stupid comma in the middle?
The text before the comma changes every time.

Thanks!
0
[('01', ['name abc', 'age 32', 'address addr123']), ('02', ['name def', 'age 22', 'address addr456'])]

   I want this list to be written in CSV file in below format. Some time list may contain more values.So no hard codings.
    Expected output in csv in table format
   
    id    name   age   address
    01   abc     32     addr123
    02   def     22     addr456
0
On Demand Webinar: Networking for the Cloud Era
LVL 10
On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Are there any instructors like
simon allardice
from lynda.com, plursight.com
who explain computer science concepts without using a scripting language.

Just verbally.

Please add (or subtract) zones
0
I installed Visual Studio Code & I would like to program in python when I go to compile my code I get these error messages

errorI am confused what to add.
When it goes to that point, I do not know what to put in.
Can someone help.

I debug my code, and press run and I get those 2 error messages, but the code successfully runs.
0
I have below python script
response = ''
ascii_map = 'abcdefghijklmnopqrstuvwxyz012345'
for j in range(7):
    response += ascii_map[(int('3996146930') >> (5*j)) & 31]
print response

Open in new window

I give output as below
shxadxd

Open in new window

0
For a school project, I've been tasked with setting up an attendance-taking program. I've done some research and have come to a conclusion: I need some help.

I've got a bit of a plan but I'm not sure if it will work since I've got next to no experience in this type of thing. I want to use a barcode scanner to scan a specific barcode for a student and then input that into some sort of python program and log attendance.

I'm confident I can write the python code but I don't know how to connect a barcode scanner to the IDE, I'm also not sure which IDE to use.  I have considered trying to use Arduino connected to a webcam (or something similar).

Nevertheless, I need some expert advice, so any input will be met with extreme gratitude since I've been stuck at this point for weeks.
Thanks in advance.
0
Hello,

I have a OID as below
30.118.115.58.115.105.110.103.108.101.58.116.101.115.116.45.109.97.99.104.105.110.101.58.104.116.116.112.64.56.48

Open in new window


I would like to know how can I convert it to it's name using python? I do not want to make any network or localhost call.

this OID is mapped to one of the VSERVER's Name in NetScaler.
0
So long story short I think it MAY have something to do with my shebang in my python. I know on our server we have a few different versions of Python and I installed my modules (paramiko and pysftp) in the correct place I believe. Honestly I have researched and am having trouble understanding how exactly the shebang works and knowing what interpreter it is pulling from or why the cron job is failing for that script (is there a log file perhaps to help determine the cause?)

Cron listing:
* * * * * /usr/local/mlb_cdt_download_newv2.py > /dev/null 2>&1
(Yes for testing purposes I am trying to have it run every minute just to see if it runs)

Script:
#!/usr/local/lib/python2.7
import os
import pysftp
import os.path
import paramiko

HOST=""
USER=""
PASSWORD=""
SUFFIX_TO_FETCH__AND_DELETE=".csv"
DESTINATION_PATH="/mnt/sas/ftp_mlb"

srv = pysftp.Connection(host=HOST, username=USER, password=PASSWORD)

def do_nothing(fname):
        return  " "

def fetch_and_remove(fname):
    if not fname.endswith(SUFFIX_TO_FETCH__AND_DELETE):
        return # skip files with wrong suffix
    dst_fname = os.path.join(DESTINATION_PATH, fname)
    dst_dirname = os.path.dirname(dst_fname)
    if os.path.isfile(dst_fname):
        return " "
    else:
        srv.get(fname, dst_fname)
        srv.remove(fname)

srv.walktree('.', fetch_and_remove, do_nothing, do_nothing)

srv.close()

Open in new window


For the record, running this script from the commando line works instantly and perfectly. But when trying to automate it through the cron I have no luck.

Any help trying to understand which interpreter my cron is trying to use and the location of such would be greatly appreciated.
0
Hi all!

I wrote a little python code to continously check if the user is active and, if not, lock the computer screen.

This works well.

I've then decided to use a small systray icon to enable / disable the endless loop that is checking for user activity but it seems like showing the systray icon is an endless loop itself.

Therefore if I run my current code:

# Instructions
#
# Pair your phone to your pc's bluetooth as first step
#
# Then scroll down and customize the locker's parameters before running
# the script. Simply search for "Customize me" to make your life easier :)
#
# 1st parameter is your phone name (in my case 'G4') and 2nd is maximum
# number of seconds that the user is not active before the screen
# is autolocked
#

# Importing classes
from autolocker_class import *
from systray_icon_class import *

# Customize me!
locker = ScreenLock('G4', 10)

# Minimal self test. You'll need a bunch of ICO files in the current working
# directory in order for this to work...
if __name__ == '__main__':
    hover_text = "IPAutolocker"
    bluetooth_icon = 'Checked.ico'
    def autolocker_on(sysTrayIcon):
        locker.is_autolocker_enabled = True
        print "Autolocker enabled"
    def autolocker_off(sysTrayIcon):
        locker.is_autolocker_enabled = False
        print "Autolocker disabled"
    def bluetooth_on(sysTrayIcon):
        is_bluetooth_on = True
        print "Bluetooth enabled"
    def bluetooth_off(sysTrayIcon):
        is_bluetooth_on = 

Open in new window

0
Hi,

I am expected to propose the EDIFACT solution for a company that starts from scratch (regarding EDIFACT).

Communication via OFTP2 ready to be used (on Linux)


The only thing that is already decided and ready to be used is the OFTP2 communication (on Linux machine, OS4X by c-works if it matters, ODETTE ID assigned).

This way, message splitting or even parsing can use UNIX-based tools. Anyway...

MS SQL and procession on Microsoft Server


... the original message (before parsing) will also be saved on Microsoft based server (as a blob in the SQL table).

The database and the Enterprise applications is running on a different computer -- Microsoft Windows Server, MS SQL Server.

First messages to be processed


The Delivery schedule message (DELFOR) and Despatch advice message (DESADV) are the first one to be received. I am aware of versions of the EDIFACT messages (about two releases each year).

I am aware of X12 being the predecessor of EDIFACT, of the other standards like Tradacom, VDA, ... and the consequences of having tools for transformation of the messages. However, the decision was made to use the pure UN/EDIFACT only.

Differences based on a partner decisions


I am partly aware of (future) problems with _the same kind of message from a different …
0
-------my code-----

import xml.dom
import xml.dom.minidom
doc = xml.dom.minidom.parseString('''
<root>
   <person id="01">
      <name> abc</name>
      <age>32</age>
      <address>addr123</address>
      <siblings>
        <name></name>
        <name></name>
      </siblings>
   </person>
   <person id="02">
      <name> def</name>
      <age>44</age>
      <address>addr456</address>
      <siblings>
        <name></name>
        <name></name>
        <name></name>
      </siblings>
   </person>
</root>

''')


def innerHtml(root):
    text = ''
    nodes = [ root ]
    while not nodes==[]:
        node = nodes.pop()
        if node.nodeType==xml.dom.Node.TEXT_NODE:
            text += node.wholeText
        else:
            nodes.extend(node.childNodes)
    return text

for statusNode in doc.getElementsByTagName('person'):
    for childNode in statusNode.childNodes:
        if childNode.nodeType==xml.dom.Node.ELEMENT_NODE:
            print("{}={}".format(childNode.nodeName, innerHtml(childNode)))

-------------output i got is------------------
name= abc
age=32
address=addr123
siblings=
                     
name= def
age=44
address=addr456
siblings=

---------but expected output should be in tableformat-----
i need to get the person id attribute also...pls answer

person id         name         age      address
01                abc          32      addr123
02                def          44       addr456
0
[Webinar] Lessons on Recovering from Petya
LVL 10
[Webinar] Lessons on Recovering from Petya

Skyport is working hard to help customers recover from recent attacks, like the Petya worm. This work has brought to light some important lessons. New malware attacks like this can take down your entire environment. Learn from others mistakes on how to prevent Petya like worms.

Hi,

I am using Jupiter to write a read csv line.

So far,I wrote>>

(1)      import pandas as pd
(2)      pd.read_csv('C:/Users/USER1/Documents/Exports/ItemStatus.csv', sep=',')

but its giving me error. See text file. What I need to change to make this work…
python-read-error.txt
0
Below code works perfectly now I want to provide ObjectType(ObjectIdentity()) as a variable which will be constructed as a list of OID

from pysnmp.hlapi import *

g = getCmd(SnmpEngine(),
           CommunityData('myPa$$word'),
           UdpTransportTarget(('loadbalancer-staging.com', 161)),
           ContextData(),
           ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0')),
		   ObjectType(ObjectIdentity('1.3.6.1.2.1.1.6.0')))

for x in next(g)[3]:
    print x

Open in new window

I have a list of OID as below and somehow I want to put that in getCmd method as a variable
mibs = ['1.3.6.1.2.1.1.1.0', '1.3.6.1.2.1.1.6.0']

Open in new window

so basically I have a dynamic list of OID (minimum 3 and maximum 9 ) and I want to supple them as a variable in above code so that in ONE SNMP call I will get output of all the OIDs. Is there a way I can do it? Thanks!
0
i want to use winpcap lib in python, but prompt :

Traceback (most recent call last):
  File "D:\1_AutoTest\7_Pyhon\1_Code\Winpcap\src\winpcapy.py", line 12, in <module>
    import sysloglib
ImportError: No module named sysloglib
0
I want to be data analyst.
but i don't know, what should i learn first?

what are basic capabilities  should i have ?
0
Hello,
Back when C# came out; I did not know how to pronouns this combination of C and a # (sharp).  Talking to a  developer, he chuckled when I said "C pound."
And now, when "reading" about generic decorators; it is not written as to  how to pronouns these;
*args, **kwargs
Might any one have the phonetics /fəˈnediks/ on these two decorators;
*args, **kwargs

Thanks
0
I'm currently trying to create a script that will search for specific data in an excel document and print out a range of cells.

For example, it would search for "color" in column A. If "color" was found in A4 it would print out the data in A4, B4, C4, D4, etc.

import openpyxl
wb = openpyxl.load_workbook('example.xlsx')
sheet = wb.get_sheet_by_name('Sheet1')

for rowOfCellObjects in sheet['A1':'C3']:
    for cellObj in rowOfCellObjects:
        print(cellObj.coordinate, cellObj.value)

Open in new window


This is the only code I have so far which is an excerpt from Al Sweigart. “Automate the Boring Stuff with Python: Practical Programming for Total Beginners.” iBooks. and the only thing it does is search for specific cell addresses and prints those.

Is this a feasible project? I'm very new to Python so I don't fully grasp its limitations.

Any help would be appreciated!
0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.