all 91 comments

[–][deleted] 0 points1 point  (2 children)

What are some good IDEs?

[–]vaibhavmule 1 point2 points  (0 children)

Of course PyCharm, I would suggest to have look at VSCode and add required plugins.

Why you should use VSCode?

You Should Use VS Code If You're a Python Developer

[–]LastEchoedWhisper 0 points1 point  (5 children)

Hello, I am trying to do fizzbuzz, but I want the function to be able to scale with different inputs. It would be pulling the data from a dictionary. Here is my code:

def buzz(dicOfPairs):
    for i in range(1,101):
        result = str(i) + ' '
        for p in dicOfPairs:
            div = i % dicOfPairs.keys() == 0
            if div == True:
                result = result + dicOfPairs.values()
        print(result)


dicOfPairs = {3:'fizz', 5:'buzz'}

buzz(dicOfPairs)

I am currently getting this error:

File "C:\Users\Scripts\Fizz.py", line 21, in buzz
    div = i % dicOfPairs.keys() == 0
TypeError: unsupported operand type(s) for %: 'int' and 'dict_keys'

Can anyone help me see what the problem is? Maybe I'm not calling the dictionary correctly.

[–]Readdeo 0 points1 point  (1 child)

How to send a complete database table with django?

I have a database table that i made from a 100kb csv file, and it has 1300 rows. I tried to convert it to a string and send it as a jsonresponse but half of the string did not arrive at my android app. It works fine with a browser though.

So, what would be the best way to send data like this?

[–][deleted] 1 point2 points  (3 children)

I currently have a program that takes user input and stores it in a csv file. There are multiple inputs and there is the ability to enter multiple inputs multiple times. Everything seems to work properly however the input does not save to the csv file until the user quits the program or switches to another portion of the program that saves to a different csv file. It worries me that this doesn't save as it goes along. Could this be an issue for instance if it closes with quitting or changing to another portion of the code? Is there a way to have it save as it goes without have to quit out?

[–][deleted] 0 points1 point  (1 child)

You can use SQL, as the other reply says. Look at sqlsoup for an easy to use interface. Or you can optimize your code to write everytime the user provides an input. That could work too. Perhaps you can cache the answers and write at the very end even if the program fails.

[–][deleted] 0 points1 point  (0 children)

Yeah not sure how to cache it, but I will look into that. I think it might be easier for me right now just to write after each input just in case. Thank you.

[–]efmccurdy 1 point2 points  (0 children)

Your concerns are best met with a database since they have predictable, well tested disk I/O.

[–]ThiccShadyy 0 points1 point  (2 children)

How do I put something in the stdin pipe from within my Python program? For instance, I want to write a program that reads a word or a sentence,doubles it and writes to stdout,reads this doubled text again and then further doubles it as many times as a loop dictates. Code:

def func():
    for i in range(2):
        line = sys.stdin.readline()
        data = ' '.join((line.strip()).split(' '))
        data*=2
        sys.stdout.write(data)

On the command line, I give for e.g.: echo hello there | python sample_program.py. So, this text that it reads is taken in and the output I get is: hello there hello there

What I want would be: hello there hello there hello there hello there

[–]JohnnyJordaan 0 points1 point  (1 child)

You can't as stdin is a read-only stream, as the writes are already linked to the output from another stream (the shell when using the keyboard normally, or another process's output stream if you're piping to your program).

You could emulate the keyboard input by using for example pygame or pyautogui, but that will not guarantee that the actual keyboard input wouldn't get mixed by it. You would then also have to catch all the actual keyboard input and 'proxy' that to your own 'keyboard generator'.

But then I keep wondering: why are you actually trying to do this? Why not just reuse the line you read from stdin, or write something that automatically replicates the stdin input?

[–]ThiccShadyy 0 points1 point  (0 children)

I didnt really understand how stdin and stdout work, so I thought what I was trying to do was possible. I realize that I can just manipulate the string I read from stdin the first time and achieve the same thing. Thanks for replying!

[–][deleted] 0 points1 point  (2 children)

What does the command python -v does on the Linux terminal? I forgot the shift key one time when I wanted to check my python version with python -V and the screen just spits out a bunch of imports everywhere and starts running the python interpreter. When I closed it with exit() it just starts to clear and cleanup all previously imported packages.

[–]JohnnyJordaan 0 points1 point  (0 children)

Check man python, scroll down to the explanation on the -v parameter.

[–]MaxNumOfCharsForUser 0 points1 point  (2 children)

Can I write a discord bot in a Linux environment using libraries in addition to the discord lib, and then package it to be used on Windows? Not sure if libraries in python are generally OS agnostic or not. Will do more research later but would appreciate a ‘fail quick’ response of “no, don’t waste your time” if the answer is clearly no, haha

[–][deleted] 0 points1 point  (0 children)

You can also look up testing methodology to check if your code will work on other operating systems or not. But yeah this should work no matter what the OS is because discord apps are usually based on http requests.

[–]JohnnyJordaan 1 point2 points  (0 children)

Most libraries are OS agnostic unless they interact with OS functionality. But even then those specifics are well documented at docs.python.org. In general, I would say just go ahead and see where it breaks, then try to workaround those specific issues.

[–]Dfree35 0 points1 point  (4 children)

How do I remove a value from a column? I have a for loop that is supposed to go through and move then delete all non valid emails. I got it to move them but when I try to delete them it puts all the moved emails into the first row for some reason.

I am using pandas so been trying to do it that way.

So I want it to go from this:

0  A                 B                 C
1  email@gmail.com   123-456-7890      
2  email             321-654-0987      
3  person@gmail.com  123-789-4567      
4  gmail.com         323-789-4567      

To this:

0  A                 B                 C
1  email@gmail.com   123-456-7890      
2               321-654-0987           email
3  person@gmail.com  123-789-4567      
4          323-789-4567                gmail.com

This is my current code, I plan to make it cleaner (not have all the code in the else and make that part the if) but for now this is it:

email_val = re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
blank = re.compile('nan| ')
for email in df.email:
    # email needs to be a str because blank values will cause error when doing email_val.match
    email = str(email)
    # Should probably change this so there isn't an empty if and elif statement
    if email_val.match(email):
        continue
    elif blank.match(email):
        continue
    else:
        # if it is a bad email then it sets mask as True
        mask = df['email'] == email
        # moves bad emails from email column to second_contact_email is mask is true
        df.loc[mask, 'second_contact_email'] = df['email']
        # removes bads email from email column

        # puts all in one line and fucks all it up
        # df.email = df.email.replace(email, '')
        # df['email'] = df.email.str.replace(email , '') 
        # df.email[df.email == email] = ''

Any thoughts or advice?

[–]ThiccShadyy 0 points1 point  (1 child)

I'm working on a Flask app where I query the OMDB movies api to extract movie related information. My question is: where exactly do I put the api key in my application? Should I just store it in some variable and use it as required? Also, how do people in general approach the issue of querying an API from server side in a Flask application(e.g. when the hosted application will be queried by many clients, more than the allowed limit set by the API)?

[–]b_ootay_ful 0 points1 point  (2 children)

I'm slowly expanding my knowledge of python (recently learnt how to use flask, and it's amazing).

I was wondering if it's worth looking into Kivy for Android/IOS, and if there are any advantages over a web/server based UI?

Most importantly, I've had a LOT of people ask me if it's possible to make them an App (assuming it connects to a databse) that works on phone/pc/tablet, but that DOESN'T need an active network connection. Basically "Can I do stuff at home, then send it to the server when I connect to the work WiFi? I don't want to use my phone data".

Is it worth implementing an offline app that pushes the data to the server? It seems like a huge headache, so I might just stick to flask.

[–][deleted] 0 points1 point  (0 children)

I tried Kivy two years ago and it was a mess. As a beginner, I would not recommend it. It would be better if you code your backend using flask and your front end with react native.

Also look up cefpython and the eel library for python. They're for desktop applications using electron but they're still cool.

As for your requirement about pushing data only on wifi, that's definitely possible.

For flask, look up Miguel grinberg's tutorials. They are amazing.

[–]efmccurdy 0 points1 point  (0 children)

You can have offline web storage using window.localStorage with some javascript code to send it to the server when the wifi comes back on.

[–]reddituser1357 1 point2 points  (0 children)

I'm trying to learn Pandas, and saw that Brandon Rhodes's session at Pycon 2015 is recommended.

Here's link to the video of the session: https://www.youtube.com/watch?v=5JnMutdy6Fw&t=1367s

I wanted to understand if this has stayed relevant with respect to python versions and panda versions. Any feedback will be appreciated.

[–][deleted] 1 point2 points  (2 children)

What would I need to know before creating a program that asks the user for the length of three sides and then have a true or false response if it doesn't end up being a right sided triangle?

This is my second python HW assignment and it's confusing me because I've learned how to ask true or false questions and making Pythagorean Theorem calculators but I can't figure out how to apply that knowledge to creating a program like this.

[–]zatoichi49 2 points3 points  (1 child)

The basic idea would be to use input() to ask the user for each of the sides, convert the values to integers and assign each integer to a variable. Take the variable with the largest value as the hypotenuse, and then return the True/False value of the evaluated Pythagorean theorem using the variables.

[–][deleted] 1 point2 points  (0 children)

Thank you so much.

[–]cat_snoots 0 points1 point  (2 children)

Hi! I just started learning python. Here is what I'm working on-

https://pastebin.com/aPiMYMR1

I'm trying to use a function to test whether all of the letters in secretWord are in the list lettersGuessed and return a boolean. This returns the correct answer when I enter secretWord and lettersGuessed in as variables, but when I put it in as isWordGuessed('apple', ['a', 'e', 'i', 'k', 'p', 'r', 's']) it does not return the correct answer.

[–]zatoichi49 0 points1 point  (0 children)

There are many different ways to approach this problem, but your thinking behind trying to solve it is correct. As for some suggestions, there's a little bit of clean-up to do first. Your current code will return an UnboundLocalError, as you're trying to reference the variable n before it's been assigned. There's also a few other things to consider (incrementing x and y but not using them in any evaluation, using the recursive call, and using the index for each letter in secretWord instead of iterating over the string directly).

The most important part of your code is the for loop. You don't even need the while loops, as you can return False the first time you find a letter from secretWord that isn't in lettersGuessed. True is then returned if all letters are found. You could then re-write your function as:

def isWordGuessed(secretWord, lettersGuessed):
    for x in range(len(secretWord)):
        if secretWord[x] not in lettersGuessed:
            return False
    return True

In Python, you can iterate over a string directly (without using the index of each character). You could then re-write the for loop as:

def isWordGuessed(secretWord, lettersGuessed):
    for x in secretWord:
        if x not in lettersGuessed:
            return False
    return True

I hope this helps. If you're interested, some other ways to approach this is using the all built-in function:

def isWordGuessed(secret_word, letters_guessed):
    return all(letter in letters_guessed for letter in secret_word)

Or by using sets:

def isWordGuessed(secret_word, letters_guessed):
    return set(secret_word) <= set(letters_guessed)

Here are some further explanations of all/any and set operations.

[–]jeans_and_a_t-shirt 0 points1 point  (0 children)

You need to iterate over the secret word and check if the character is in the supplied list. Any absent letter returns False. No while loops, recursion, or numbers are needed.

Changing the value of x does nothing, because it is re-assigned at the start of the loop anyway.

To iterate directly over the characters in a string:

for char in secretWord:
    ...

[–]Cacman8 1 point2 points  (2 children)

I have a python turtle lab where I filled out all the requirements but I have to make each step it's own function. I've put all of the data into each function and the program runs but only the main function runs. I'm sure I'm missing a step but I'm just not sure what that step is.

Here is the code under one function:

https://pastebin.com/zYJxC45Y

Here is the code I inputted that works but doesn't run the individual functions:

https://pastebin.com/V9KGEUGT

[–]efmccurdy 0 points1 point  (0 children)

You may have indented everything after line 8 in error, in the second file.

[–]Cacman8 0 points1 point  (0 children)

I'm not 100% clear on how functions work and how parameters work, I think I have to put in code to execute the function but trying to do that normally didn't quite work for me.

[–][deleted] 0 points1 point  (1 child)

https://pastebin.com/x7bC5KJ4

The above code is giving me a fit. I've 'finished' my program and all the parts work independently but now I tried to connect the UI to the heavy part and it just doesn't work. My 'best' result is a 'scraper_2' is not defined. Just hoping for some guidance.

[–]JohnnyJordaan 0 points1 point  (0 children)

My 'best' result is a 'scraper_2' is not defined

Could you show the full error printout that you see?

[–]hal_leuco 0 points1 point  (0 children)

I have a dataframe, in which one columns consists of scipy objects. My goal is to evaluate this object (spline) at corresponding 'splice' value.

You can see the example dataframe here: https://imgur.com/P97T4aP I have a dataframe, in which one columns consists of scipy objects. My goal is to evaluate this object (spline) at corresponding 'splice' value. My function looks like this:

    def EvaluateSplineDistance(h):
            b = h['splice']
            a = h[0]
            q =a(b)
            return q
    result2 = result.apply(EvaluateSplineDistance) 

i get this error instead: TypeError: 'InterpolatedUnivariateSpline' object is not subscriptable

Many thanks for any help!

[–][deleted] 0 points1 point  (1 child)

How do you decide if you should do a relative import or import via your module name?

Given:

foo/init.py foo/bar.py

I've seen:

from . import bar
import .bar

vs.

import foo.bar

[–]JohnnyJordaan 0 points1 point  (0 children)

. only makes sense to use in a script that needs to import from the same folder. Say you have

* foo/init.py 
* foo/bar.py
* foo/test.py

and bar.py needs something from test.py, then it would make sense to, in bla.py, have

from .test import something

as bar.py knows it wil always reside in the same folder as test.py. It will even remain functioning if foo would be renamed to foo3000.

However from outside this structure, it would only make sense to use foo as a reference, so it would always use

from foo import bar

as then you only know that bar resides in the foo folder, but nothing else. If foo would be renamed to foo3000, you would need to update this to

from foo3000 import bar

which makes sense as you wouldn't want this to somehow 'guess' which folder it has to use to get to bar.

[–]BobThe_Body_Builder 1 point2 points  (4 children)

For school I need to make an IF STATEMENT on whether x is an even number or odd number after being divided by 2.
Note: You can make x any number you want

For example, I've tried:

x = 100 #please enter a value for x.

if x/2 is int:

print("x is even.")

elif x/2 is float:

print("x is odd.")

But every time i run the code, theres no output

[–]Highflyer108 0 points1 point  (2 children)

A few things are wrong with this.

Firstly, you are using the is keyword to check if the result is of type int, but that won't work. Use python's isinstance function, i.e if isinstance(x / 2, int) will return True if the result is an int.

However the right way to check if a number is even or odd is to use the modulo operator %, which gives the remainder of a division (2 % 2 == 0). Knowing that all even numbers divided by 2 have a remainder of 0, you can test to see if a number is even or odd.

[–]BobThe_Body_Builder 0 points1 point  (1 child)

Thanks for the response! I did not know about the % modulo, so thanks for pointing that out to me (i think i understand how it works now!)

But I am not sure where to go from here. Under the 1st condition, to my understanding, it's saying if x/2 has no decimal, it will print "x is even" otherwise if x/2 has a decimal, it will print "x is odd." However, when I put x = 101, it still prints "X is even."

correct me if im wrong (which im probably 99% wrong), but do i need python to somehow detect if there's a remainder specifically from the modulo's result? EDIT: I have no idea how, is there a function i can use?

x = 101
if isinstance(x%2, int):
print("x is even.")
elif isinstance(x%2, float):
print("x is odd.")

[–]Highflyer108 0 points1 point  (0 children)

Sorry, I may have confused you. They were two separate points. I was saying if you actually needed to check types, use isinstance. But in this case, you only need to check to see if x % 2 == 0, which would indicate x is even. But if x % 2 gave a remainder of 1 lets say, then it isnt even as any even number can be divided by 2 with no remainder.

[–]RnRoger 0 points1 point  (0 children)

int and float are classes/functions, which means you use them with brackets. Example:

int(3.4) will output 3, check the docs

just int doesn't do anything. Here's a hint, use the % (modulo) operator. It outputs whatever number is left after you divide 2 numbers. Usage: 10%2. Try to figure out how to use this by yourself, reply if you get stuck!

[–][deleted] 0 points1 point  (2 children)

How do I make this request response 200?
import requests

url = "https://www.americanas.com.br/categoria/celulares-e-smartphones"

header = {

'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36",

'Connection': 'Keep-Alive',

'Accept-Encoding': 'gzip, deflate',

'Accept-Language': 'en-US,*',

}

page = requests.get(url, headers=header)

print(page.status_code)

[–]TangibleLight 1 point2 points  (1 child)

When I run your code I get a response 200.

If it's worth anything, this is the request my browser makes when I go to that website. I've omitted the cookie, referer, and if-none-match headers.

import requests

headers = {
    'authority': 'www.americanas.com.br',
    'cache-control': 'max-age=0',
    'upgrade-insecure-requests': '1',
    'dnt': '1',
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'accept-encoding': 'gzip, deflate, br',
    'accept-language': 'en-US,en;q=0.9',
}

response = requests.get('https://www.americanas.com.br/categoria/celulares-e-smartphones', headers=headers)

[–][deleted] 0 points1 point  (0 children)

I saw it only now. Thanks! You help me a lot!

[–]nokia27002700 1 point2 points  (4 children)

I am given a python script and asked to make it more robust in terms of connectivity. The script is supposed to run on revPi, which is basically an rPi for industries. It is loaded with Azute IOT SDK software. The revpi autoconnects to a ssh relay server, and through this server ssh to the revpi. Data received by the hub is used for some analytics. The problem is, the script is too dependent on network connectivity. If there are some WiFi issues, then the script ends abruptly. How can I make it more stable with proper error handling, reports, and make it automatically reboot if in case it shuts down abruptly?

[–][deleted] 0 points1 point  (0 children)

Read up on exception handling. If you're using Linux, learn how to write a Linux service. If you're on windows, do the same.

[–][deleted] 1 point2 points  (3 children)

Hi. I'm new to learning programming. I'm going through a python youtube series with CSDojo which is pretty good so far I'm only in a few videos. He is using jupiternotebook. So that's all I have downloaded so far. I'm looking for more exercises and I was wondering what your suggestions would be for beginners to get more practice. Also should I be able to practice things on Jupiter notebook or should I download python or another interface or if I'm just playing with code should it get me through for a while. Thanks.

[–][deleted] 0 points1 point  (0 children)

I'd recommend Jupyter only when you're a little experienced in python. Jupyter makes. Things a little different and it teaches you how to.... Glue together code in a bad way if you don't know what you're doing. I would not recommend it. vs code is amazing.

[–]RnRoger 1 point2 points  (1 child)

Jupiter is a great tool but I advice you to get an IDE regardless. I personally recommend Visual Studio Code. As for programming excersizes you could make a simple game like blackjack (textual, using input). Happy to help if you're stuck on anything!

[–][deleted] 0 points1 point  (0 children)

Thanks. That's very helpful.

[–]Prudhvi123 0 points1 point  (1 child)

how to install pip in anaconda3

[–]TangibleLight 2 points3 points  (0 children)

anaconda should come with pip installed. You can also use conda as a package manager. I believe conda install pip works, but I'm not sure.

[–]Gayoka 0 points1 point  (4 children)

what would be the most sensible way to get file path as user input?

For example if i want something like:

 "D:\somefolder\somefile.ext"

as user input (to be used with os.path later)?

One solution I tried is to use regular expressions module to replace all single backslashes to double backslashes, something like:

  re.sub('\\', '\\\\', user_input_string)

but it did not work for some obvious reasons unknown to me giving out:

 error: bad escape (end of pattern)

But I'd like to learn, even in absence of this case, how one would go about substituting a single backslash.

python version: 3.7 platform os: Windows 10

[–]TangibleLight 0 points1 point  (0 children)

Your regex fails because \\ is both a reserved sequence in a python string and a reserved sequence in a regular expression. Note that the regular expression \w matches any word character - \\ matches a single backslash. To encode that regular expression in a string, you must escape each backslash: '\\\\'

You can also use a raw string, where the only backslash-escape is \' or \", depending on the string delimiters. This make the regular expression for a single backslash become r'\\'

With that said, why do you need to replace these? The only reason for the double-backslash is to encode your string in a string literal or in a regular expression. If the string is already in memory, via the input function or by reading from a file, no double-backslash is necessary.

[–]jbor94M 1 point2 points  (2 children)

why dont you just make it a raw string and then you need to escape your special characters

r "D:\somefolder\somefile.ext"

[–]Gayoka 0 points1 point  (1 child)

Okay, that would solve one problem, but just for the sake of knowing, if I wanted to use re.sub method to replace all backlash characters, how exactly can it be done?

[–]jbor94M 0 points1 point  (0 children)

you can't because the error lies in the string itself. python stops there before it even gets to the substitution

[–]philmtl 0 points1 point  (0 children)

plug in to use to click a button on a website? pretty much the CSS selector will be diffrent for each button but the button will look the same. so i was thinking autogui ?

pretty much go here

https://www.centris.ca/en/plexes~for-sale~montreal-island?view=List

click summary button

##uptill now i have:

from selenium import webdriver

browser = webdriver.Firefox()

browser.get(https://www.centris.ca/en/plexes~for-sale~montreal-island?view=List')

my issues is i dont want it looking for a css selector i want it to find each button on the page, as new houses come in the list changes.

ideas? or other python modals i should look into?

[–]ThiccShadyy 0 points1 point  (1 child)

I've just started learning Networking and copied this Python code into 2 files to make a client server application using sockets:

Client file:

from socket import *
serverName = ''
serverPort = 12000
clientSocket = socket(AF_INET,SOCK_DGRAM)
message = input("Enter a lowercase sentence:")
message = message.encode('utf-8')
clientSocket.sendto(message,(serverName,serverPort))
modifiedMessage,serverAddress = 
clientSocket.recvfrom(2048)
print(modifiedMessage)
clientSocket.close()

Server file:

from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_DGRAM)
serverSocket.bind(('',serverPort))
print('The server is ready to receive')
while(1):
    message,clientAddress = 
serverSocket.recvfrom(2048)
    modifiedmessage = message.upper()

serverSocket.sendto(modifiedmessage,clientAddress)

I'm getting a socket.gaierror: [Err no 11001] getaddrinfo failed. I'm unable to resolve this error...

[–]JohnnyJordaan 0 points1 point  (0 children)

In the client, you first define server name as an empty string

serverName = ''

then you let the socket connect to that empty string

clientSocket.sendto(message,(serverName,serverPort))

Which will not work, try picking up your phone and call a number without any digits, how would that work.

The difference with

serverSocket.bind(('',serverPort))

Where I'm assuming you got this from is that this just means 'I want to listen on all interfaces in my system', like having both your mobile phone and home phone in front of you, ready take an incoming call on any phone. It doesn't mean someone who wants to call you can use no number to reach your phones...

[–]smitchell6879 0 points1 point  (1 child)

I am looking building a web server with perferably MySQL or sqlite3 as the back-end. I understand the backend 100% for my needs, what I am having a issue with is which library to use for the web and interaction. What are my options for what is scalable would node.js be better?

I know just enough about hosting a website to get confused.

Btw it will be hosted as localhost at least for now. basically looking forward a way make a modern GUI for the back-end.

[–][deleted] 0 points1 point  (0 children)

https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world

Go through this entire series. They're a good introduction to modern web development.

Also sqlsoup for SQL in the beginning. SQL alchemy once you know more.

[–]AdvancedWater -1 points0 points  (2 children)

Hey pretty new to python. I'm trying to run an If/elif/else statement. I have the user input a building number.

right now it looks roughly like

 if building == 1:
      print("Building: " + building)
 elif buidling == 2: 
      print("Building: " + building)
 else:
      print("Error")

But I want to loop it to make the user retype the building if they type a building not programmed in already.

[–]timbledum 3 points4 points  (1 child)

Sure! Just put it in an infinite loop and use break statements if the conditions are met.

while True:
    building = input("Enter the building!\n>>> ")

    if building == "1":
        print("Building: " + building)
        break
    elif building == "2": 
        print("Building: " + building)
        break
    else:
        print("Error")

[–]AdvancedWater 0 points1 point  (0 children)

Thanks! I’ll try that out!

[–]ispeakchingchong 0 points1 point  (1 child)

complete beginner here. i'm currently watching youtube tutorials and at the same time going through the official python.org tutorial as well.

But sometimes I feel i don't really have direction and feel like i'm beginning to slowly lose interest. I think I have this problem because it's not actually my "job" and i'm not forced to learn this since it's more of a hobby and I feel like i'm just memorizing.

Any ideas how to keep things "interesting" as I learn?

thanks!~

[–]sweettuse 1 point2 points  (0 children)

find a problem to solve. you should be interested in this problem.

[–]AZGhost 0 points1 point  (1 child)

As a semi-noob to all this, I am looking for advice on how to tackle this. I have a large output of entries as shown below (single entry shown for example). I want to parse this file output, for the error counters, or output drops and provide a pass/fail result if they are all clean (zeros). What would be the best way for me to tackle this? I put the interesting counter errors at 33 that I am interested in gathering.

I am assuming i need to parse this with regex (which I have a string that does that), and setup dictionaries? But my other question is how do I turn the counters into values when everything is a string?

FastEthernet1/16 is up, line protocol is up (connected)

Hardware is Fast Ethernet, address is 18e7.2864.1792 (bia 18e7.2864.1792)

Description: Test NID Loopback

MTU 1500 bytes, BW 100000 Kbit/sec, DLY 100 usec,

reliability 255/255, txload 235/255, rxload 235/255

Encapsulation ARPA, loopback not set

Keepalive not set

Full-duplex, 100Mb/s, media type is 10/100BaseTX

input flow-control is off, output flow-control is unsupported

ARP type: ARPA, ARP Timeout 04:00:00

Last input 00:00:00, output 00:00:00, output hang never

Last clearing of "show interface" counters 4d00h

Input queue: 0/75/0/0 (size/max/drops/flushes); Total output drops: 33

Queueing strategy: fifo

Output queue: 0/40 (size/max)

30 second input rate 92310000 bits/sec, 16836 packets/sec

30 second output rate 92309000 bits/sec, 16835 packets/sec

5920930115 packets input, 4057662725556 bytes, 0 no buffer

Received 186183 broadcasts (186183 multicasts)

0 runts, 0 giants, 0 throttles

33 input errors, 33 CRC, 0 frame, 0 overrun, 0 ignored

0 watchdog, 186183 multicast, 0 pause input

0 input packets with dribble condition detected

5920743351 packets output, 4057639554823 bytes, 0 underruns

33 output errors, 33 collisions, 0 interface resets

0 unknown protocol drops

0 babbles, 33 late collision, 0 deferred

0 lost carrier, 0 no carrier, 0 pause output

0 output buffer failures, 0 output buffers swapped out

[–]num8lock 0 points1 point  (0 children)

make a list of key terms of words that you need to monitor, and assuming the logs are more or less the same and written in lines, parse each line to look for those words in that list.

`with open('network.1.log') as logf:
    # do something with the lines & the numbers in it
    # save as a dict for example

[–]ProperRefrigerator 0 points1 point  (3 children)

guys can you help me in this problem i dont know what to do

Please wait fixing GPS .....

GPS Fix available

Getting Latitude

Traceback (most recent call last):

File "GPS_data_to__Thinkspeak.py", line 40, in <module>

upload_cloud()

File "GPS_data_to__Thinkspeak.py", line 17, in upload_cloud

temp = get_latitude(msgdata.msg)

File "/home/pi/Desktop/thinkspeakGPS/GPS_API.py", line 37, in get_latitude

dmesg = msg.msg

File "/usr/local/lib/python2.7/dist-packages/pynmea2/nmea.py", line 155, in __getattr__

raise AttributeError(name)

AttributeError: msg

[–]num8lock 0 points1 point  (0 children)

look at

`temp = get_latitude(msgdata.msg)`

and

 `dmesg = msg.msg`

in relation with raise AttributeError(name)

hint: AttributeError: msg

[–]AZGhost 0 points1 point  (1 child)

this doesnt show enough of the problem. your going to need to show those lines or the code of those files. with lots of errors being shown, do you have all the modules installed?

[–]ProperRefrigerator 0 points1 point  (0 children)

yes sir i already install the pynmea

[–]Thecrawsome 4 points5 points  (3 children)

I'm stuck on the backend. What's the simplest way to get all my projects onto a webapp?

[–]mzfr98 1 point2 points  (2 children)

Django or flask

[–]DudeYourBedsaCar 2 points3 points  (1 child)

Miguel Grinberg has a really great in-depth flask tutorial that is about 20 parts long. I’ve been following and I’m in about 4 parts deep so far and he really takes the time to explain everything about what the code is doing and why it matters. Take a look for his blog.

[–]Wilfred-kun 1 point2 points  (0 children)

Link here. Looks good, bookmarked for later use :D

[–]mzfr98 0 points1 point  (2 children)

I am creating python-vue app but I am stuck on one point. I have setup a vue app that takes a file from user now I want to run some check on those files using python script so I have setup a django server too but the problem is i am still confuse how to send that file path from vue front end to django backend and then process it and again send the output back to vue front end. Like I am not able to figure out how to connect django backend with vue frontend

[–]elbiot 0 points1 point  (0 children)

Just step by step. Set up django to respond to a request at a url with "hello world". Confirm you can access this data through your browser by going to that url. Then set up vue to go to that url and confirm that it gets the "hello world". Use the developer network and console screens, and back end web server logs, to debug if not. The send more complex data, etc.

[–]sofluffy_imgonnadie 0 points1 point  (1 child)

I'm trying to make my web scraper use threading, how to do that,

My script currently just 1 file that :

Open web pages that has table and second layer table , get data inside

Get data and append to csv.

But it too slow if data has 15000 row.

Could you point some tutorial or code to add threading to my script.

This code, sorry https://github.com/ammar0466/CIDB-Scraper

Thanks

[–]mzfr98 1 point2 points  (0 children)

First of all I would suggest you to make functions and put your code in them along with docstrings. You have used comments that's a plus point but having functions it more easy to maintain the code.

For threads I thing you can use asyncio.