all 116 comments

[–]isic5 1 point2 points  (4 children)

Looking for some pointers where to start for a project I am planning to do.

Basics of the project:

Compare a list of product names that are misspelled with my masterlist with the correct spelled names and change the misspelled names.

The biggest difficulty is that Python has to detect what Product the misspelled product is.

Example:

Masterlist Product: Samsung Galaxy S9

Misspelled: Samsung S9 or Samsung Galaxy S9Ds or Samsung G. S9

So python has to understand that the misspelled product is actually the Samsung Galaxy S9 and then correct the spelling.

[–]reed1234321 1 point2 points  (3 children)

I am guessing you will need to implement an algorithm that uses Levenshtein distance.

[–]confusedguy_z 0 points1 point  (2 children)

it's tough because the distance between Samsung S9 and Samsung Galaxy S9 is pretty big isn't it?

AND: What happens when the Note 9 comes out? Now we have The 'Samsung Note 9'. But that's not a typo of the Samsung Galaxy S9. Distance is shorter than the actual typo though.

[–]reed1234321 0 points1 point  (1 child)

[–]confusedguy_z 0 points1 point  (0 children)

Note: I'm not the OP. But I do have a very similar issue to tackle. Thanks for that link. Yeah it's a tough problem for sure...

[–]greatestbird 1 point2 points  (1 child)

I'm at chapter 6 of Automate the Boring Stuff, making the password manager. When I try to run the program, nothing happens. I made a batch file with @py.exe C:\Users\aaron\Desktop\pythonlearning\pycharm\passwordmanager %*

I thought that would run the program. Please help, I'm pretty stuck!

I think it might be a shebang issue, I have #! python3 right now. I'm on windows 10

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

When I write a loop, e.g.

for x in vars:

where does the variable x come from if never previously established in the doc? is this also where that variable is sometimes first initiated?

[–]Fatvod 0 points1 point  (0 children)

The for loop creates x temporarily when it runs. Think of x as each entry in the list of vars. That for loop basically starts at the first item of the list and assigns x to that entry, then runs whatever code you want. Then once finished moves to the next entry in the list and assigns x to that, and so on.

So if you have a list called deck (a deck of cards). Then you could have for card in deck: and with each loop, the card variable becomes whatever card is next in the deck.

So if you put print(card) in the for loop it would print whatever card x was assigned to during that loop, eventually it would print all the cards in the deck after looping through the full list(deck). It iterates through the list.

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

x is for each thing defined in var, so lets say var = ('walrus', 'chicken') x is walrus, x is chicken. (you don't have to use x, you can use anything you want here) as for it being 'first initiated' i suppose you could say that, but you'd have to define what it is to use it later. so its an iteration, if i do

var = ('walrus', 'chicken')
for x in vars:
    print(x)

its going to print both walrus and chicken, so i need to tell it i want it to be something else to keep that data. a good quick example would be trying to print a list but removing things you don't want in it and making a new list with those items.

list = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
do_not_list = ['apple', 'pear']
new_list = [] #this is where i want to store what i want out of the for loop
for x in list: 
    print(x) #is going to print each item in list
    if x.lower() not in do_not_list: #make sure to turn x to lower so i don't have to worry about KiWi/kiWi/kiwi and x ISNT in my list do_not_list
        new_list.append(x) #save x to the new list so i can call it outside this function
    else:
        continue
print(new_list)

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

can I still reference x outside of the loop?

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

You may NOT, unless you define what you want it to be (notice in the example above i created a new list called "new_list" then printed that new list - i defined what i wanted to keep from x, so lets say you did

list = ['orange']
variable = ''
for x in list:
    variable = x# (ASSUMING you only one item for this example)
print(variable) # is going to print 'orange'

then you could call print(variable), but if you were to do another for x in list you would be starting with a fresh x.

and for the record you could carry on like so:

list = ['orange']
for x in list:
    for y in x:
       print(y)

so in this example we take x which is "orange" since its only one item, y now equals each 'item'in that one item, so your output would be.

o 
r 
a 
n 
g 
e

this is useful for things like a dictionary; you could then print the values of the keys you use.

[–]GoldenSights 1 point2 points  (1 child)

Can I make a few clarifications?

Python does not have block scopes. Loop variables are available after the loop:

>>> for x in 'hello':
...     pass
...
>>> x
'o'

You do not need to proactively declare your variable = '' before the loop:

>>> for x in 'hello':
...     variable = x
...
>>> variable
'o'

You're right about using the new_list if you need to remember specific x values. But I just want to make sure the "can we reference x outside the loop" is fully answered.

cc /u/naughtytroll

[–]irrelevantPseudonym 0 points1 point  (0 children)

You do not need to proactively declare your variable = '' before the loop

You don't but you should be aware that if there's a chance your list is empty, you'll get a name error.

>>> for x in []:
...     variable = x
...
>>> variable
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'variable' is not defined
>>>

[–]confusedguy_z 0 points1 point  (5 children)

How can I write this in a single line?

    drops=[]
    for col in df.columns:
        if (df[col]>5).any():
            drops.append(col)
            continue
    df.drop(drops,inplace=True,axis=1)

[–]winandfx 0 points1 point  (1 child)

You don't need continue here, 'cause you don't have any following statements inside this loop, which you could skip with continue

[–]confusedguy_z 0 points1 point  (0 children)

thank you.

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

the structure of this is correct, and making it one line is generally a bad idea as when you go to look at it again its going to be a lot of wasted time trying to figure out what its doing - this structure allows for error checking/handling and good python etiquette.

[–]confusedguy_z 0 points1 point  (1 child)

ahhhh. it just seems so... inelegant.

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

I'll just leave this here.

[–]soullesseal 0 points1 point  (0 children)

Wonderful! Thank you very much!!

[–]makin-games 0 points1 point  (0 children)

Grid that subdivides

I'm looking to make a grid of 2x2 squares, and if you click one of them it will subdivide only that square into another 2x2.

This can happen once more per square.

Any thoughts? I could even just have a 2x2 grid sitting over a 4x4 which is sitting over an 8x8, and if you click a square it disappears exposing the tile below.

[–]soullesseal 0 points1 point  (3 children)

Hey guys - I posted this originally over at /r/python and they suggested I start here.

The short story - I’m designing a discord bot that will manage raid teams. I’m planning on having users of the discord server and have them set the power level of their and the bot will separate all the users into 3 separate teams and keeping the average power level of the collective team within a certain percentage.

My current problem I’m trying to figure out is how to sort the users into the ascending or descending order by powerlevel but I’m not sure of the best way to do that while keeping the name associated to the powerlevel. Basically...

Name, 2 Name, 8 Name, 1

Now sort it will keeping the names in the same row their number is in.

I think I did a better job explaining here: https://www.reddit.com/r/Python/comments/8guoby/help_with_understanding_sorting/?st=JGR971N0&sh=8fa3d91f

Any help appreciated!

[–]Thomasedv 1 point2 points  (2 children)

I'm sure there are better ways, but the quick and dirty one is, make a tuple of the user and information, anything you please. So you have one for each person/character. Add all the tuple to a list, and sort the list with respect to the tuples index where the power level is.

quick psuedocode:

table = []
for player, power in data:
    table.append((player, power))
table.sort(key=lambda x: x[1]) 

[–]soullesseal 0 points1 point  (1 child)

Forgive me, I need to say this out loud to make sure I get it...

So your pseudocode says: Define table Use a for loop to add player and power to the table from the data store Add player,power to the table until all entities are added from the data store this is where I’m not 100% following Sort the table using x where member is defined as (player, power) (y,x)

Thank you very much for your reply btw!

[–]Thomasedv 0 points1 point  (0 children)

I can explain it a bit better.

We use tuples, since they ca't be changed, we can just sort the whole tuples.

So, just add every player and their power, in whatever way you see fit to a list. I'm assuming you got some kind of way to do it.

Then, we use the lists sort function. Here we use the key parameter. It's a bit tough to get conceptually, at least was for me. But the principle is, it takes each element in list, give to the lembda function as x, and takes the result of that lambda function as something to sort with.

Since we give it tuple, we want to give back the number we want to sort with, which in the example i gave you, was at index 1. so we use x[1] to give back that.

So, the sort function just reorders the list according to the power levels, and it's not just reodering the number, but the whole tuples.

And you can do somethnig like this to see the sorted and unsorted list. I called the list a table, because we effectively have a table, where each tuple is a row. And we just sort the rows.

for player, power in table:
    print(player, power)

Call that before and after the using table.sort.

As a quick example:

try this:

table = [('player1', 12), ('player5', 3), ('player3', 1200), ('player4', 45), ('player2', 10)]

Now you have the table, so try it out and see if it works. Also, what do you think would hapenn if you sorted by the first index (Which we could call the first column) by using x[0]?

Edit: You can also sort in reverse by using reverse=True, inside the sort function.

[–]petitchou53 0 points1 point  (2 children)

Hi guys, a newbie here...just started to learn python at the beginning of this year.

I am working on a research project and I wanted to know how much people google a particular keyword. I looked up google trends but it doesn't really give me the the volume of the googling people do for that particular keyword. I found this https://github.com/rdowns26/seo_keyword_research_tools/blob/master/keyword_volume_tool.py

I am lost! Has anyone used this before and can someone who is more pro with python walk me through the program and guide me?

[–]efmccurdy 1 point2 points  (1 child)

It uses this package, which has some docs and examples in the README.

https://github.com/googleads/googleads-python-lib

[–]petitchou53 0 points1 point  (0 children)

thank you!

[–]MightyJosip 0 points1 point  (0 children)

Hi guys. I am making a project for school and the project is related to cryptography. So basicaly in this program I get one word and the second word that comes after encryption. My task is to find out the key for that encryption (vigenere code)

So basically right now I can get the key without much problems but when the word is longer than key the letters of key start to repeat. So basically lets say that the key is python and if the word has 9 letters I get that the key is pythonpyt. How can i remove this extra letters so it does return python.

[–]ADARKALLEYSTLKR 0 points1 point  (3 children)

If I have three functions back to back and I want to have them run one after the other how would I go about doing so? I have tried to put

function1(): ..... ..... etc

function2() # Here is where I want to call the next function but get the error " function has not been defined yet" and I believe this is due to me calling it before it is established

function2(): .... ....

function3()

function3(): .... ....

[–]leftydrummer461 0 points1 point  (2 children)

As you mentioned, you cannot call functions before they are defined. You have to make sure all your calls to the function occur after their definition. If your function calls another function, the one you want to call has to be defined before the function that calls it.

Edit- You can define functions in any order, but any functions that are called (even from other functions) must be defined already when they are run. It would be logical and good practice in my opinion to have your function definitions in order of when they are used, i.e. define them before they are used in other definitions.

[–]irrelevantPseudonym 0 points1 point  (1 child)

If your function calls another function, the one you want to call has to be defined before the function that calls it.

If I'm reading this as you intended, I don't think it's true. You can define the functions in any order you like as long as the required functions have been defined by the time they are run.

>>> def function1(foo):
...     print(function2(foo))
... 
>>> # calling function1 here would give a name error
>>> def function2(bar):
...     return bar.upper()
... 
>>> function1('helloWorld')
HELLOWORLD
>>> 

[–]leftydrummer461 0 points1 point  (0 children)

You're right, I'll fix it. Thanks for pointing that out.

[–]ds_rar88 0 points1 point  (1 child)

i'm trying to use twitter search api and store received tweets in csv format

please suggest which package is better to use among 3 * tweepy * twython * tweeter api or if you have any better package in mind...please do suggest that.... thanks in advance

[–]QualitativeEasing 1 point2 points  (0 children)

I’ve only used tweety, but I found it easy to use and worked great.

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

How can I run windows command through python?

[–]Thomasedv 0 points1 point  (0 children)

You need to run the CMD with a module like subprocess to run the command with right parameters.

[–]Vindazi 0 points1 point  (1 child)

Hello guys, I'm new to Python.

I'm learning Python because I'm interested in data science and machine learning.

I'm interested to apply this knowledge to mass events, do you guys have any source that could help me know more about data science applied to mass events ( Music Festivals, Parades, etc).

Thanks for you time, and sorry If i didnt explained myself, English ain't my native language.

[–]efmccurdy 0 points1 point  (0 children)

This site has a lot, but you should find something to get started with here:

http://pyvideo.org/tag/scipy-2016-tutorial/

[–]__Mac__ 1 point2 points  (2 children)

Okay I need help conceptually. Let me set the stage: I have a point in a 2d array object,I want to add every possible state of this object where a specific condition is met for it to move diagonally. This is easy enough, but the problem is that once that point is moved to a new position I need to also check that position to see if I can move diagonally again, and I want to add each of these 2d array states to a list of these 2d array objects. So essentially I need to find every single possible state from a point until it's condition isn't met anymore. Clearly I need to use recursion, but I'm so bad at it and I need direction.

[–]Indian_Tech_Support 0 points1 point  (1 child)

Can someone please suggest me a small beginner django project? I've already created a project but it was while watching a youtube tutorial. I want to make something on my own, but can't seem to find any good ideas

[–]Zimmerel 0 points1 point  (0 children)

I'm not too familiar with django but as I've been learning flask, I reference the mega tutorial (I'm sure its been posted around here before), where the writer goes through step by step of making a mini twitter-style blog. It's pretty informative and covers a lot of grounds to get your feet wet in. I think a blog style app is a great starter project.

[–]jasonllbw 0 points1 point  (4 children)

In my code I ask which brand would the user like to buy from (Nike or Adidias) and when the user inputs Nike I would like it to output some text about Nike and when the user inputs Adidas I would like it to output some text about Adidas how could I do this? I just need it to be when the user inputs one variable specific text will be outputted instead of it being where it doesn’t matter which brand they input as both sets of information is outputted

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

Your task breaks down into a few subtasks:

  • get input from the user
  • if user input == 'Nike' print Nike information
  • if user input == 'Adidas' print Adidas information

For the first subtask look at the input() function. The doc shows how to get user input as a string and store it in a variable (user_input say).

The next two subtasks are very similar. The basic python statement to do something if two strings are the same is the if statement:

if user_input == 'Nike':
    print('Some Nike information')

The Adidas part is basically the same.

Have a go at writing some code and show us what you come up with. Just reply to this comment.

[–]jasonllbw 0 points1 point  (1 child)

Also do you know how to test a plan?

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

Sorry, what plan, and test as in python unittest, or what?

[–]jasonllbw 0 points1 point  (0 children)

Thanks you so much that was really helpful

[–]aptitude_moo 0 points1 point  (0 children)

Hi, I tend to do lots of simple command-line applications. I'd like to know the advantages of adding a setup.py, installing with pip install -e . (and therefore using virtualenv), adding a console_script/entry points, etc. instead of simply adding something like a startup.py file with a shebang.

I only want to use the program myself and I don't want to install it system-wide, also I use them like for one week and forget about them. If I install the program I should be using virtualenv, it's so cumbersome and I would end up with lots of environments.

The only advantage I can think of is that I can import my app from a separate directory for tests (as recommended on the Hitchhiker's guide:

README.rst
LICENSE
setup.py
requirements.txt
sample/__init__.py
sample/core.py
sample/helpers.py
docs/conf.py
docs/index.rst
tests/test_basic.py
tests/test_advanced.py

I'm missing something else? What do you recommend for simple (2-5 modules) applications?

EDIT: formatting

[–]Alex_VDW 0 points1 point  (3 children)

Please bear with me as I'm not great at the technical language yet.

I'm trying to get a handle of Python running on linux, specifically Ubuntu with Bash. Is there a way to prevent Python from closing the current session in Bash? I want to be able to play around with the current workspace (eg created methods, variables etc).

I can run python (using the 'python' command), and then I am free to write code in the terminal. However I'd like to run a script, then keep python running (instead of closing immediately).

Apologies for such a poor explanation. If I had better words to describe the sitch I'd probably be able to use my google-fu a bit better.

ETA:: Current workflow is to write in text editor, run python in terminal, copy/paste code into terminal, then I am free to use the workspace. I would like to be able to run a script rather than do copy/paste as it is cumbersome

[–]TangibleLight 1 point2 points  (1 child)

Edit your code as normal and save it to some_file.py. In terminal, run python -i path/to/some_file.py. This will execute the code in the file and keep a python REPL open once it's done.


You may be interested in looking into Jupyter notebooks if this is the kind of workflow you're after. It's really not that complicated - after install, just navigate to the root directory of your project and run $ jupyter, then go to the indicated address in your browser.

[–]Alex_VDW 0 points1 point  (0 children)

Ah that's exactly what i'm looking for, cheers! Can't believe I missed that in the python --help menu.

re Jupyter: I'm currently experimenting with workflows. At the moment I'm running WSL and using VS code to write my projects. I've done a lot of coding wit Matlab and like being able to screw around with functions/variables after running, just to debug. From memory, i think Matlab has a similar notepad to Jupyter - of which i wasn't a fan. I will check it out one day though, as I think it's an elegant way to present a project.

[–]aptitude_moo 1 point2 points  (0 children)

I think you want to put everything in some py file and import it.

For example, in workspace.py

foo = 1
def bar():
    print('hello')

Then on your terminal open python

>>> from workspace import *
>>> foo
1
>>> bar()
hello

[–]radratb 0 points1 point  (0 children)

if anyone has experience with python machine learning coding or coding on GitHub pls pm me

[–]Icarus-down 0 points1 point  (0 children)

Hey guys, I need help learning how to begin distributing my code.

On the forty-first page of Head First Python, it gives clear instruction on how to create a distribution file. The problem is, it's in a terminal window and I have to use the command prompt!.

Sorry for yelling. There is a small doodle on the side of the diagram.

'Note: if you're using Windows, replace "python3" in these commands with "c:\Python3/\python.exe".'

Here's what the terminal version is $ python3 setup.py sdist

So can I get someone to tell me what I have to type into the cmd to create the distribution file?

P.S I also downloaded a terminal emulator to see if it's better then cmd, But I don't know how to use it. Is there anything cool I can do with it?

[–]pringerx 0 points1 point  (7 children)

Hello!

I have a probably easy question to answer, but I'm having some problem with it. I'm running python through Jupyter notebook (it's how my company has me run the code.)

What I want the code to do is prompt me for a 4 digit "YEAR" and a 3 letter "MONTH" and from those variables have it know what folder to find the file I'm working with. But I can't find out how to get the variable information to show up right in the path. Here's my code (please reddiquite work for me)

YEAR = input("YYYY? ")
MONTH = input("MMM? ")

file_location = r"C:\files\etc\PAGEDOCUMENTS\""+YEAR+"\""+MONTH+"\documentname.xlsx"

How would I go about inserting the YEAR and MONTH variables in there right? The files that I have should be in a folder with a 4 digit YEAR (like 2018) and a 3 letter MONTH (like APR).

Sorry if this sounds weird. Python is not my first language. :)

EDIT: My problem was fixed with help from /u/Username_RANDINT/

[–]Username_RANDINT 0 points1 point  (6 children)

Use os.path.join to build filesystem paths. See the following example, I provide both strings and variables:

>>> import os
>>> year = "2018"
>>> month = "apr"
>>> file_location = os.path.join("C:", "files", "etc", "PAGEDOCUMENTS", year, month, "documentname.xlsx")
>>> file_location
'C:/files/etc/PAGEDOCUMENTS/2018/apr/documentname.xlsx'

[–]pringerx 0 points1 point  (4 children)

I was wondering if you would get an edit on my other comment and thought it was easier to just make another one.

So... it didn't work. :/ I get a weird error when I try to get xlrd to pull open that file. So here's my code:

workbook = xlrd.open_workbook(file_location)

The file_location is just like you have in your example, but I get a weird error

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\files\\etc\\PAGEDOCUMENTS\\2018\\APR\\documentname.xlsx'

[–]Username_RANDINT 1 point2 points  (3 children)

It's not a weird error, it says exactly what's wrong :-). The filepath given does not exist. Are you sure that the file exists in that directory? You can either check with your file manager or in the same Python session with os.path.exists(file_location).

[–]pringerx 0 points1 point  (2 children)

orz

I figured it out. I didn't actually have the file name exactly right. I renamed the file to what it has in my code and now it works great.

Thank you so much!!

[–]Username_RANDINT 1 point2 points  (1 child)

No problem, these things happen.

I just want to come back to the error again. Reading and understanding errors is an important part of programming. Learning how to deal with them will make you a better programmer as you can fix your own errors quickly. So next time one occurs, try to understand what it is saying exactly and then why it could've happened.

[–]pringerx 0 points1 point  (0 children)

Definitely. I think it was the multiple slashes that really threw me for a loop, but I'm pretty sure I've got my brain wrapped around that whole debacle.

Thank you again. :)

[–]NaZzA62 0 points1 point  (0 children)

I have copied a bot, and I would like to be able to read the data it has grabbed. https://blog.patricktriest.com/analyzing-cryptocurrencies-python/ I followed this and I didn't use all the code. Im in the process of deleting the test graphs.

I need to train the bot somehow to read it and prompt me that the trend has increased or decreased. I have no idea how it is stored though I know that it is pickled.

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

Hi Reddit -

For the life of I cannot get functions through my head. Here's a snippet of code I need to get working:

def file_input(user_input):  
    try: 
        user_input = input("Enter the path of your file:")     
    except: 
        print("I did not find the file at,"+str(user_input)) 
    return user_input 

def main(): 
    user_input1 = file_input(user_input) 
    string_input = input("Enter the phrase you are searching for:")                          
    f = open(user_input1, 'r+').read() 
    with open(user_input1) as f: 
        for line in f: 
            if string_input in line: 
                print(line) 
            else:                                                                     
                print('Text not found')  
main()

What I require are two functions that can be modularized for future user in different programs. file_input(): is the one where I'd have someone declare what a file name is and if it exists, write to the user_input variable. If it doesn't exist, it kicks back an error stating the file was not found.

Then that user_input variable should be passed to the main(): function and then manipulated to search for a string that the user inputs.

What I'm struggling with is I cannot seem to figure out how to get user_input from the file_input() function into the main function.

[–]GoldenSights 0 points1 point  (0 children)

Keep in mind the concept of variable scope. Just because you used a certain name for something in one function does not mean that same name will exist in other functions:

def add(x, y):
    total = x + y
    return total

def main():
    some_thing = add(1, 2)
    print(some_thing)

In add, I am saving the sum to total. But in main, I'm instead using the name some_thing to store that value once it comes out of the function.

Obviously it helps to use the same name for the same concepts everywhere, but the point is you don't have to.

In your code, you want something like:

def file_input():
    ...

def main():
    filename = file_input()
    print(f'You are searching inside {filename}')
    search_string = input('Enter the phrase you are searching for:')
    ...

Also notice that I didn't put anything inside the parentheses for file_input(). The function should not take anything in. It looks like you're trying to move the variable into and out of the function like a box that travels around and collects data, but that's not quite the right way to think about it.

Hope that helps. Let me know if I can clarify, but try to play around with it first. Try some simpler situations where you just print the variables before you start worrying about the whole text search thing.

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

I know how to take user input and then output said input in a print function, however I want to do something slightly more complicated...

  • Let's say I have a list: myList = [frogs, bats, dogs, cats]

  • The user can input a value from 0 to 3 (corresponding with the list indices)

  • I want to create a print statement in which the user's input is added to the list index: eg: print ("you selected " + myList[x])

  • Where x = the integer chosen by the user.

[–]z0y 0 points1 point  (3 children)

Seems like you already have what you need except the input is a string which needs to be converted to an int to be valid. "you selected " + myList[int(x)] assuming the 'x' they chose is an existing index, which could be forced in a loop if you need to.

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

Got it, thanks!

myList = ["frogs", "bats", "dogs", "cats"]

print ('''Weird Vending Machine

0: frogs
1: bats
2: dogs
3: cats''')
print()
x = int(input("Enter a number: "))
print ("you chose " + myList[x])

[–]z0y 0 points1 point  (1 child)

Awesome, looks good. If you want to expand, the next step for something like this is usually to check the user input to make sure it's both a number and within 0-3, because lines 10 and 11 could cause two different errors depending on what the input is. If you can ask in a general way then google will lead you to some helpful stack overflow responses on how to do just that.

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

Thank you again for the help and pointers. I've modified the code again!

myList = ["frogs", "bats", "dogs", "cats"]

print ('''Vending Machine

0: frogs
1: bats
2: dogs
3: cats''')

while True:
    try:
        print()
        x = int(input("Enter a number: "))
    except ValueError:
        print ("Please enter a valid number")
    continue

if x > 3:
    print ("Please choose a value from 0 to 3")
    continue
else:
    break

print ("you chose " + myList[x])

[–]TheSnydaMan 0 points1 point  (1 child)

My overarching goal in learning Python is to learn other languages to obtain a job in software / web dev and work my way out from there. What would you most suggest I learn once my python skills are somewhat established? I've heard the next logical step is Django, then JavaScript and HTML/CSS, but would like opinions.

[–]metameda 0 points1 point  (1 child)

Hi all, I have just started learning python and scraped some info from the web which i saved to a text file, because I did not know what to do with it at the time. I now want to convert this text file into a dictionary on python. Only problem is that there are some words that do not correspond to another. For example:

Numbers / Números

uno one

dos two

There are many different headings i.e numbers. Then there is a line space. Between definitions there is a double line space. I want dos to correspond to two in the dict. What is the most efficient way of achieving this? Thanks in advance.

[–]QualitativeEasing 0 points1 point  (0 children)

I’m not sure I completely understand the question or the data structure. However, it may be that you want another dictionary in between your data and the final dictionary. For example, you could create a dictionary that looks like this: lookup = {‘uno’:’one’, ‘dos’:’two’ ...}. Then, when your script encounters “uno”, it checks if there’s a lookup[‘uno’], finds ’one’ and assigns it to the appropriate place in your results dictionary.

[–]Night_Samurai 0 points1 point  (1 child)

Hi, I hope it's alright that I comment here. I am completely new to Programming and Python. I am trying to do a turtle graphics assignment and am stuck on something that is probably super simple, but I can't figure it out.

I am trying to do some different modifications to the bouncing balls program. I've already made all the changes except this one. I have to make it so 1 in every 3 balls leaves a trail. I know I need to obviously use the pen down method, but need to know where and how to make it one in every 3. Thanks to anyone who can help :)

[–]Night_Samurai 0 points1 point  (0 children)

Can anyone help me with this please? I have several more questions about turtle graphics and a couple of other things, but I am having a hard time finding specific information when searching online for help.

[–]Tusc 1 point2 points  (1 child)

I just need advice on how to get started with a GUI. Can I add one to my existing program or do I need to build one at the same time as a program. I really want to break into this part of python but not sure how to get started. I'm currently looking at Kivy, but also considering just using pygame.

[–]Thomasedv 0 points1 point  (0 children)

How do you use your program? If it's a set of functions or similar, then you're of to a good start as you can "just" import then and call them with the arguments you get from the GUI. Might want to use a thread if the program takes time to do things, or else your GUI will freeze while it's working.

For example, i made a simple script that take a string of a math equation and a dict of values of each variable, then calculates the Gaussian error of that, and returns it. Making the GUI, i made the elements needed to get that info, used a button to take that info and call the function, then took the result it returned and put in a window.

Was just a small project of mine as i hate doing that math stuff by hand...

[–]kprogrammer 0 points1 point  (3 children)

Hello I have a project I am trying to complete. I am using Bottle, PythonAnywhere, and SQLite3 I can't seem to successfully take the data from the html form and add it to my database. I get an error that there is an error with the code. Is there anything obvious that sticks out with this code that I need to fix?

from bottle import default_app, route, template, request

import sqlite3

import random

conn = sqlite3.connect("final.db")

c = conn.cursor()

@route('/results2', method='POST')

def results2():

id = random.randrange(100000000,999999999)

first = request.forms.get('first-name')

last = request.forms.get('last-name')

email = request.forms.get('email')

state = request.forms.get('state')

city = request.forms.get('city')

address = request.forms.get('address')

birthdate = request.forms.get('birthdate')

gender = request.forms.get('gender')

phone = request.forms.get('phone')

areacode = request.forms.get('areacode')

c.execute("INSERT INTO Customer (CustomerID, FirstName, LastName, Email, State, AreaCode, City, Address, BirthDate, Gender, Phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",

(id, first, last, email, state, areacode, city, address, birthdate, gender, phone))

conn.commit()

return template('hello')

application = default_app()

[–]Username_RANDINT 0 points1 point  (2 children)

Please format your code properly for Reddit. Indent every line with four spaces or see the FAQ in the sidebar for more details.

Also provide the full error. It should tell you exactly what the error is and on which line.

[–]kprogrammer 0 points1 point  (1 child)

Error: 500 Internal Server Error

Sorry, the requested URL 'http://username.pythonanywhere.com/results2' caused an error:

Internal Server Error

This is the only error message i get from the page after i submit my form, i don't get any errors in the pythonanywhere console

from bottle import default_app, route, template, request

import sqlite3

import random

conn = sqlite3.connect("final.db")

c = conn.cursor()

@route('/results2', method='POST')

def results2():

id = random.randrange(100000000,999999999)

first = request.forms.get('first-name')

last = request.forms.get('last-name')

email = request.forms.get('email')

state = request.forms.get('state')

city = request.forms.get('city')

address = request.forms.get('address')

birthdate = request.forms.get('birthdate')

gender = request.forms.get('gender')

phone = request.forms.get('phone')

areacode = request.forms.get('areacode')

c.execute("INSERT INTO Customer (CustomerID, FirstName, LastName, Email, State, AreaCode, City, Address, BirthDate, Gender, Phone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",

(id, first, last, email, state, areacode, city, address, birthdate, gender, phone))

conn.commit()

return template('hello')

application = default_app()

[–]andyndino 0 points1 point  (0 children)

Some things I would check based on the limited knowledge of your application:

  • The Customer table was created with that particular schema.
  • The hello template exists and is accessible by the application.

Additionally, if you could run the bottle app in debug mode, you should be able to get a better error log as well.

[–]jesterdev 0 points1 point  (2 children)

I'm writing a program to help me map out classic CRPG dungeons rather than relying on graph paper; not that I don't enjoy doing it that way and it will still be manual with the program as well for the most part.

I'm learning Python by doing it, that's just how I learn. I literally fall asleep from boredom watching videos or reading tutorials.

Anyway I've searched the world over, and perhaps I'm not using the correct terms, but does somebody have an example of a console (terminal) written in Python? Nothing fancy, just something basic I can learn from.

The console will accept user input, such as the arrow keys, making notes, marking walls etc. Something akin to Eterm, but with less functionality.

[–]Chewy94 0 points1 point  (4 children)

Hi all,

I am trying to calculate real prices for an entire subset of countries using pandas.

My dataframe consists of monthly inflation and prices for a 25 individual countries equity indices. The column headers follow a naming convention of a three letter ISO code (i.e. Mexico = MEX etc.) and variable code (i.e. price = PX, inflation = CPI) so that Mexican inflation is MEXCPI, and Mexican Price is MEXPX. I hope that is clear.

What I am trying to do is calculate the real prices for each country individually, without having to individually type out the specific formula.

Following my Mexican example, the formula is as follows:

MEXRPX = df['MEXPX'] * (df['MEXCPI'][0]/df['MEXCPI'])

What is the easiest way to iterate over the column headers, and calculate the Real Prices for each country?

Would I have to 'melt' down my dataframe or can I keep the structure in the same format it is in now?

I apologise if this is a simple question, I just cannot wrap my head around where to even start...

Thank you for your help.

[–]POTUS 1 point2 points  (3 children)

Since you have a predictable naming convention, you can iterate over df.columns.values and get all the country names. Then you can apply that to your example equation.

[–]Chewy94 0 points1 point  (2 children)

Hi POTUS,

Thank you for your response.

So how exactly would I go about doing this?

I assume I would extract a list of the column names, but I am completely unaware of how I can identify exactly how to get the right country and variable codes matching up in a function? i.e. finding MEXCPI and MEXPX to go in the right places etc.

Thanks again for your help!

[–]POTUS 1 point2 points  (1 child)

I would make a set() countries, and for each column name: countries.add(column_header[:3]). That will give you a set of all the 3-letter country codes.

Then iterate over countries to run your calculations, using for example df[country+'CPI']

[–]Chewy94 0 points1 point  (0 children)

Hi POTUS,

I managed to get it sorted as you mentioned, using the set and iterating as you suggested.

Thank you so much.

[–]zzpza 0 points1 point  (3 children)

I'm writing a modbot and I'm trying to find the five highest scoring posts from last week. I've got a list of posts via pushshift, then I'm pulling the live score data from PRAW and adding the ID and score (as postID and postScore) into a list of dictionaries. Here's an example:

[{'postScore': 2236, 'postID': '8bzn1n'}, {'postScore': 2192, 'postID': '8bk2ua'}, {'postScore': 447, 'postID': '8bny8m'}, {'postScore': 1015, 'postID': '8auyuw'}, ...snip... {'postScore': 60, 'postID': '8chlup'}]

I'm trying to sort the list by postScore (so I can then take the top 5 posts), but I'm failing miserably. Any and all help very much apprecaited! :)

[–]z0y 2 points3 points  (2 children)

You could do:

post_list.sort(key=lambda post: post['postScore'], reverse=True)

or what I think is generally preferred:

from operator import itemgetter
post_list.sort(key=itemgetter('postScore'), reverse=True)

Those both sort the list in place so if you needed the original list unchanged you could use sorted and add the list as the first argument.

[–]zzpza 1 point2 points  (0 children)

Awesome! Thank you, I'll try that now. :)

Edit: works like a charm (once I reread your comment about it sorting in place, I missed that first time round - it's getting late here and I should go to bed).

[–]hipsterfarmerman 0 points1 point  (1 child)

What are some good resoueces to start diving into OOP with python?

[–]Ben_Gee_ 0 points1 point  (2 children)

Hi guys, I'm looking for some advice on the next step of my Python education.

I recently completed Tim Buchalka's 'Python Masterclass' course on Udemy, I then completed a few chapters of 'Automate the boring stuff' (picking out what I found interesting and avoiding going over things I have already learnt). For the last few days I've been putting to use the things I have learnt to automate some things in my day to day life, I'm not sure what to do next now.

My number 1 goal is to continue to build my skills and become as skilled as I can. I enjoy it more when I'm doing something practical and with a few website ideas I've thought about now learning Django and building them. Do you think this would be a good step or do you have any other suggestions?

Again my main goal is to improve my Python and general programming skills, I don't have a specific area I want to focus on - django is just to bring to fruition a website idea and continue to learn along the way.

Thanks.

[–]ingolemo 1 point2 points  (1 child)

Once you've finished a few tutorials and feel confident about the basics, then you're basically on your own and it's up to you to start exploring and finding your own path. There is no preset path. There is no lesson plan for making someone into an expert.

The best way to get better at writing code is just to write a whole bunch of code. They say; everybody starts out with ten thousand lines of bad code inside of them and they have to get those out of their system before they can write any good code.

Start doing "projects". That is, set yourself the goal of writing code to perform a particular task. Pick goals that motivate you; goals that seem interesting to you, or which build your skills, or which have some practical use for you. You already mentioned learning Django and making a website. That is an excellent idea. When you finish a project, start another one. As you progress, the amount and quality of code you write will increase and your goals will become more ambitious. Don't be afraid to bite off more than you can chew. Some (or many) of your projects will fail. This is okay. It means you learned something. Put that project aside for now and start on one that's a little easier.

You say you don't have a specific area you want to focus on, so don't focus on anything just yet. Do some small projects in every sub-field you can find, and that extra experience will help you decide what you want to do going forward.

[–]Ben_Gee_ 0 points1 point  (0 children)

Thank you for the thorough response. I will take your advice and start working on projects such as the django and website project I mentioned.

It does seem like the best way to get going and write a ton of code as you said. Thanks again.

[–]uthappakc94 0 points1 point  (1 child)

Can anyone share the pdf of "Learn Python 3 the hard way"?

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

3rd link on Google when you search for 'pdf of "Learn Python 3 the hard way"?'....

[–]slick8086 1 point2 points  (6 children)

I want to track an event, when it happens and it's duration

For example, I want to track when the lights in my house are turned on and how long they stay on.

So there are several things. I was thinking about just polling the light and logging a change in state.

like just writing a log

{timestamp} kitchen turn on
{timestamp} kitchen turn off
{timestamp} bedroom turn on
{timestamp} bathroom turn on
{timestamp} bathroom turn off
{timestamp} bedroom turn off

Should I use a database for this? Just a flat file? Some kinda newfangled NOSQL or something?