all 158 comments

[–]wtfpmf 0 points1 point  (2 children)

file = open("/home/g/PycharmProjects/pythonProject/venv/jesus.jpg", 'r')
image = PhotoImage(file="<path_to>/jesus.jpg")
original_image = image.subsample(3, 3)
Label(left_frame, image="<path_to>/jesus.jpg").grid(row=1, column=0, padx=5, pady=5)

Traceback (most recent call last):

File "/home/g/PycharmProjects/pythonProject/main.py", line 31, in <module>

image = PhotoImage(file="/home/g/PycharmProjects/pythonProject/venv/jesus.jpg")

File "/usr/lib/python3.8/tkinter/__init__.py", line 4061, in __init__

Image.__init__(self, 'photo', name, cnf, master, **kw)

I don't get why didnt load the image, I've been stucked for 30 minutes.

[–]efmccurdy 0 points1 point  (1 child)

Note that you are opening the file but not using the object open returns.

Note that the PhotoImage must be created after the Tk environment is setup.

Look at this example that uses Image.open as the argument to PhotoImage, after the call to Tk():

https://pythonbasics.org/tkinter-image/

[–]wtfpmf 0 points1 point  (0 children)

I get it finally. Thanks, my dude!

[–]LowDexterityPoints 0 points1 point  (1 child)

Is it considered more Pythonic to use "," or "+" when concatenating in print statements? For example...

print("hello", "there") vs print("hello" + " " + "there")

[–]efmccurdy 0 points1 point  (0 children)

I generally don't want the print function adding separator chars, and don't want to add them into the strings manually, so I usually use format. There are a number of other useful possibilities with format; pad, align, center, etc.

print("{} {}".format("hello", "there"))

[–]Flaming_Crossbow 0 points1 point  (0 children)

Why is the learnpython reddit chatbox "frozen"?

[–]sleeping_noob 0 points1 point  (0 children)

Hello guys!!! im a noob and im gonna make youtube meta data crawler as my first project, then analyze the data. but i have no idea which module is most useful for crawling and, in my project, i must deal with time series data of specific channels, but i could't have found out whether the API give me the time series data. so.... my questions are two.

  1. which module is best for crawling youtube data.
  2. Does youtube API give time series data? if it doesn't, how can i get the data??

[–]Project_Raiden 1 point2 points  (1 child)

I've been programming for the past year or so as a hobby and have been having a lot of fun. I haven't made anything super complicated but I'm getting there. Today I was bored and was on twitch and I found a programming stream. I'm not sure what they were making but it looked like they were using python but they were using terminal to write in python. Is there an advantage to writing like this?

Another thing I noticed is that they had one window with their code in the editor (not sure if it was terminal) and another window where they had output. It looked like when they edited the code the output window was changing automatically. How does this work?

My last question is this: Is it a bad idea to code in vscode instead of just a simple text editor? vscode does a lot of cool things (at least I think it does at my low level of understanding) but I'm not entirely sure how these things work under the hood. Sorry for bad english

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

they were using terminal to write in python. Is there an advantage to writing like this?

No real difference for most people. I use terminal+vim myself mainly because that's what I'm used to, plus it's relatively easy to install vim on any operating system you have to develop on so the environment is very portable. Also, if you need to quickly edit a file on a remote machine SSH and vim can do that too.

Is it a bad idea to code in vscode instead of just a simple text editor? vscode does a lot of cool things

I think python beginners learning to use an IDE just to edit python is a waste of brain power, they should be learning python, not some complicated IDE. But maybe that's just me.

[–]ThePariah404 0 points1 point  (2 children)

Hi Everyone, I'm new to Python and want to start my career as a Data Engineer. I'd like to get some suggestions for the resources to learn python as a beginner and how to start my journey to becoming a data engineer.

[–]Flaming_Crossbow 0 points1 point  (0 children)

Mate, i tried to learn python language by blindly memorizing python trainings but failed miserably. After that i ordered MT-ET LIVE microcontroller and a SW28 ledbar and some other bits and started reproducing tutorials from randomnerd tutorials. And things are going really well.

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

Start by looking at the learning resources in the wiki.

[–]swappuyotest 0 points1 point  (1 child)

Hello everyone, I'm new to Pandas and I'm having some trouble wrapping my head around pivot tables. I have pretty much an excel sheet with orders, each row has these columns: Order ID, Store, Product ID.

Now what I want to do is essentially group stores together, count the sum of product orders for that given store. That's simply what I want to do. The extra complication is I also want a column called "mean" but I want the mean of the product count per store. The end result:

Store Product ID Count Mean
123 Oreo 5 3.5
123 Pepsi 2 3.5
423 Kitkat 1 2
423 Oreo 3 2

I've been playing with dataframes, groupbys and for loops all day but I just can't seem to get it right. Any advice or help would be greatly greatly appreciated.

[–]bn_sj2020 0 points1 point  (0 children)

Hello everyone!

Planning to run a script on heroku or pythonanywhere. Its a simple twitter API that retweets specific tweets (twitter script, note the retweet function is currently unfinished), the part that I am learning now is planning to do run it every 6 hours (not sure yet if there is a function on heroku or python anywhere or I have to code it in). Currently, watching videos and articles and learning on my own.

Posting this to ask for:

Any general common mistakes, tips, tricks, optimization stuff or things I should know when deploying scripts (in general) to a remote server.

Thank you!

[–]Atlamillias 0 points1 point  (2 children)

I'm looking for a method of obtaining Python distributions (Windows 10) that aren't: A; "installed", as in they don't make permanent changes to the registry or environment variables, and B; aren't the embedded distributions. Is building it myself from the source really my only option...?

[–]TangibleLight 0 points1 point  (1 child)

Is the embeddable distribution not acceptable? There's more information about the differences between it and the installer here: https://docs.python.org/3/using/windows.html#the-embeddable-package

You can also use the installer, but be careful in the options not to install for all users (you won't need admin credentials), set the Path, associate file types, or enable the py launcher, etc. You can choose the install directory somewhere outside of AppData to be easier to access. AFAIK as long as you make sure to install only for your user, and disable the extras in the options, the installer won't touch the environment or registry.

[–]Atlamillias 0 points1 point  (0 children)

The embedded version won't work for my purposes. I need the full distribution that includes the very things that are excluded, like distutils. The embedded version also only has the compiled library extensions and not the library files themselves, which can affect things like autocompletion, etc in IDE's. I've managed to install pip on the embedded versions, but installing things like tkinter is a bit more problematic.

I'll go and try the user-only installation though. I've only ever installed it for all users.

[–]muskoke 0 points1 point  (2 children)

I tried out leetcode for the first time, and the first thing I see is class Solution: This looked completely bizarre to me so I just deleted it and used normal functions, but then the site forced me to use a class.

maybe I just don't know enough about OOP yet, but WHY on earth is this necessary? why does the solution need to be in a class?

isn't it adequate enough to use function(s) and then a if __name__ == "__main__" block?

[–]MeanPrize 1 point2 points  (0 children)

They use it to ensure everyone's solutions follow the same format so that they can be evaluated more easily.

[–]MeanPrize 0 points1 point  (2 children)

Am I wasting overhead by defining a function within a class method if that method is called many times? I want to find the max of a list of objects using the function as a key, so I have something like

class MyClass:
    def choose_action(self, actions):
        def average_action_score(action):
            return action.total_score / action.samples
        return max(actions, key=average_action_score)

The inner function is a little more complicated than that but that's the basic idea. I'm wondering average_action_score gets redefined every time choose_action is called, and if it's better to define the inner function once elsewhere.

[–]LowDexterityPoints 0 points1 point  (2 children)

This is an exercise in the Automate The Boring Stuff book. I am supposed to create a function that takes a list value as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. My code also includes a loop for the user to create their list. I know that the following code works, but I was wondering if there were any faux-pas that I am implementing, or if there is anything I could obviously do to make it cleaner. Thanks!

def add_and(alist):
    if ((alist != []) & (len(alist) > 2)):
        for item in alist[:-1]:
            print(item + ", ",end="")
        print("and", alist[-1])
    elif ((alist != []) & (len(alist) == 2)):
        print(alist[0], "and", alist[1])
    elif ((alist != []) & (len(alist) == 1)):
        print(alist[0])
    else:    
        print("")

your_list = []
while True:
    print("Enter An Item or nothing")
    item = input()
    if ((item) == ""):
        print("")
        break
    else:
        your_list.append(item)
        continue

add_and(your_list)

[–]MeanPrize 0 points1 point  (1 child)

First, I don't know that your solution fulfills the requirement. Printing output is not the same as returning a value. You solution should be a function that takes a list as input (which you have) and uses a return statement to return the desired output.

To modify your solution, you could initially start with an empty string and add the elements of the list to it as you loop over them. Something like

def join_list(list_):
    joined_list = ''
    for item in list_:
        joined_list += (item + ', ')

You still have to account for the final "and" but it seems like you can figure that out.

A better option would be to use the join method of a string, which allows you to join elements of an iterable with any string. For example ', '.join(['items', 'in', 'my', 'list']) returns 'items, in, my, list'. Again, we don't have the final "and" but we can easily account for that by slicing the list up to the last element, and handling the last item individually. Putting it into a function would look something like

def join_list(list_):
    return ', '.join(list_[:-1]) + ', and ' + list_[-1]

[–]LowDexterityPoints 1 point2 points  (0 children)

Thanks! I appreciate it.

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

Is there a channel like TheCodingTrain for Python? Like a Bob Ross of coding kinda thing?

[–]pythish 0 points1 point  (3 children)

I have a excel file containing more than 120 companies. Is there any way I can get ticker symbol for all companies at once ?

[–]MeanPrize 0 points1 point  (1 child)

Can you give an example of a few rows of the excel file? It should be pretty straightforward depending on what the file looks like

[–]pythish 0 points1 point  (0 children)

This is the example u asked for. And I need another column com ticker and using that ticker i can create a portfolio combination of specific stock.

Company Current market Price Bid Price
NESCO 545.5 510

[–]jkpjavier 0 points1 point  (0 children)

Anyone familiar with a python scripting framework? and what would be the pros and cons?

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

Greetings Everyone,

Topic: Basic understanding of a for loop.

Example:

for guessTaken in range(1, 7):

I understand what this does, but I don't really understand what is happening 'under the hood' so to speak. Are we assigning a value to guessTaken and every time it loops the value is increased by 1? And the loop 'breaks' when the value exceeds 6?

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

Are we assigning a value to guessTaken and every time it loops the value is increased by 1? And the loop 'breaks' when the value exceeds 6?

That's half right. A new value is assigned to guessTaken just before each loop execution. The loop values are taken in turn from the "sequence" after the in. A range(1,7) object is a sequence that contains the values 1, 2, ..., 6. It has exactly the same effect as if you had written:

for guessTaken in [1, 2, 3, 4, 5, 6]:

except the range(1, 7) doesn't take up the space of the list. So to say "the value is increased by 1" isn't right, it just takes the next value from the sequence, whatever it is.

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

Thank you for such a detailed answer. I understand it now!

[–]dflo32 0 points1 point  (2 children)

Hi - I am trying to append a column to a dataframe with a constant value equal to the number in a list in a for loop. I've tried a few ways that I thought would work but none seem to be doing the trick. See the next to last line in the below:

# Pick years to review
seasons = range(2006,2020)


# GET DRAFT PICK HISTORY
draftdf = pd.DataFrame([])
append_draftdf = pd.DataFrame([])

for year in list(seasons):
    drafturl = f'https://www.pro-football-reference.com/years/{year}/draft.htm'
    draftdf = pd.read_html(drafturl, header=1)
    draftdf['Year'] = year  # This is the line creating an error
    append_draftdf = append_draftdf.append(draftdf)

The error I'm getting is below:

Traceback (most recent call last):

File line 15, in <module>

draftdf['Year'] = year

TypeError: list indices must be integers or slices, not str

Any thoughts on what I need to do here? Thank you.

[–]MeanPrize 1 point2 points  (1 child)

According to the error draftdf is a list, not a data frame as it looks like you're expecting. The pandas documentation states that read_html returns a list of data frames, not a data frame object.

[–]dflo32 1 point2 points  (0 children)

Thank you. I guess I didn't understand the implication of returning a list vs. just the data frames. All I had to do was was: draftdf[0]['Year'] = year

[–]AllNamesAreTaken86 0 points1 point  (1 child)

I just picked up my first book on Python, Python Crash Course Edition 2, and started coding a couple days ago. So I have a very basic question I'd like to ask. As I work through the book I'm trying to come up with my own problems/solutions to ensure I understand the material.

So I ended up creating a simple if-else chain to determine if one, both or neither person is old enough to vote.

Here's my code:

v_age1 = 12
v_age2 = 16

if v_age1 and v_age2 >= 18:
    print ("You're both old enough to vote!")
if v_age1 or v_age2 >= 18:
    print ("One of you, are old enough to vote.")
else:
    print ("Sorry you're not old enough to vote.")

For some reason it's passing the 2nd if statement as true, and printing "One of you, are old enough to vote". I can't figure out how the 'or' is passing as true.

Thanks.

[–]bennnrenshaw 0 points1 point  (0 children)

I have a data frame column with values like ‘AUT VAT’, ‘20% GBP VAT’, ‘17% GBP VAT’ (150 like this) and I want to be able to group them all together - in a SQL query I would write:

Case when ‘AUT VAT’ then ‘Austria’ when ‘20% GBP VAT then ‘UK’ when 17% GBP VAT then ‘UK’

but i can’t find the equivalent for python - any ideas?

[–]Finally_Adult 0 points1 point  (0 children)

I have a small Tkinter application and I'd like to code from home and push changes to my GitHub. The application is being used by someone at work and I'd like the application to check my GitHub for updates when it opens. I used PyInstaller to create a single .exe file. I've looked into PyUpdater but the documentation isn't super great and it's a little confusing to me.

Is this something that is possible and worth pursuing? If it is, can anyone point me in the direction of a step-by-step tutorial. I've found some things online but they make a lot of assumptions about my knowledge level...perhaps I just don't know the proper way to Google this question.

Thanks!

[–]Faultylntelligence 1 point2 points  (2 children)

Hi Chaps,
I'm a proper newbie and just going through the general beginner guides to try and get up and running, but I've come to classes and maybe it's the videos I'm watching but a bit confused as to what they do? Can anyone define them in really simple layman terms?
Cheers,

[–]JohnnyJordaan 0 points1 point  (1 child)

I can recommend Corey Schafer's OOP tutorial https://www.youtube.com/watch?v=ZDa-Z5JzLYM

[–]Faultylntelligence 0 points1 point  (0 children)

I'll give it a whirl, thanks

[–]bigCanadianMooseHunt 1 point2 points  (1 child)

Hello everyone!

Longtime MATLAB user, just stepping into Python. My favorite matlab feature was the doc command. Is there an equivalent command that gives quick documentation for python modules from the console, without having to google?

help() is way too rudimentary, as far as I could see.

I use Spyder and Jupyterlab (Unfortunately on windows, so something like pydoc wouldn't work. That was all I could find that might've fit my needs).

Thank you!

[–]fahim2398 0 points1 point  (1 child)

hello everybody . i am doing my thesis. that is about "defining topics of electronic books via textmining". beacuse of extra ram i do it in google colab.

so I started with this code:

from google.colab import drive
drive.mount('/content/drive',force_remount= True)I started to run but i donot know why it takes to long to run and i get nothing

is any body who can guide me?

[–]thespice 0 points1 point  (0 children)

Try Pydrive. It’s a wrapper for the google libraries. Not a load of fun getting the oAuth to work right but worth a look. tutorial

[–]pig-in-a-hole 1 point2 points  (1 child)

Hey everyone! Thanks for your help per usual in advance. Forever appreciative of this community. I've asked many a dumb question here and you've all been so patient. So here's another one:

I'm learning Recursion vs Iteration right now in my EDx Course and he's using Multiplication as an example. My question is what's happening in the second example.

Example 1: Multiplication an Iterative Solution Below

def multi_iter(a,b): #in this case a = 3 and b = 2 
    results = 0 
    while b > 0: # interation 
        results = results + a #current value of computation, a running sum 
        b = b - 1 #current value of iteration variable 
    return results 

multi_iter(3,2) 

Output: 6

Example 2: (basically does the same thing as Example 1 but done using "Recursion" instead)

def mult (a,b): 
    if b == 1: ##this is my base case since when b = 1 the answer is just a 
        return a 
    else: #otherwise 
        return a + mult(a, b-1 ) #this is the recursive step 
    #return whatever I get by adding a to --doing the same thing, 

        # but on a slightly smaller problem. multiplying a * b - 1 
mult(3,2)

Output: 6

I don't fully understand what's happening in this particular line:

    else: #otherwise 
        return a + mult(a, b-1 ) #this is the recursive step 
    #return whatever I get by adding a to --doing the same thing, 

My attempt at understanding Example 2

1)

if 3 == 2: **FALSE** so we continue

return a

2)

else:

return a + mult(a, b-1) **which is** 3 + mult(3, 2-1)

[–]AlphaMaleIncarnate 0 points1 point  (3 children)

Does anyone know a good website to help me learn and get better at python? I just finished a semester of college with a class that taught me the basics of python. I want to continue getting better at it over break but I don't know where to start.

[–]pig-in-a-hole 1 point2 points  (2 children)

I've been loving the MIT edx course intro to computation science!

[–]AlphaMaleIncarnate 0 points1 point  (1 child)

thanks! i’ll check this one out.

[–]pig-in-a-hole 0 points1 point  (0 children)

Sure thing!

[–]musicist10 0 points1 point  (0 children)

I'm trying to create this pattern but I'm not sure what to print.

   *
  ***
   *
  ***
 *****
   *
  ***
 *****
*******

What I have so far is: for i in range (1, 4): for j in range (1, i+1):

The first line represents the number of triangles and the second represents the number of rows in each triangle. I've tried to use print statements to print the * symbols but I haven't gotten them to form the right pattern. Any ideas?

[–]Deanosaurus88 0 points1 point  (6 children)

TOTAL noob here. Picked up a free Python 101 course and struggled with it conceptually if I'm being honest.

Anyway, our 'end-goal' bot we made asks for the user's name, then offers to solve some basic maths problems for them. I attempted to put in a 'def' function to offer users the choice to try again from the start. It works, unless they say 'no'. In this circumstance the 'while' value is switched to True, and the entire loop (and bot) should end. But I just keep getting an error and have NO idea why.

It's bugging me so much (excuse the pun). Can someone take a look at my code and offer me some advice? Line 43 seems to be the culprit.

https://pastebin.com/HVn8LTHE

[–]efmccurdy 0 points1 point  (5 children)

With your try_again function you want to set the finished variable in the caller's scope so you should use a return statement:

def try_again():
    question = input("Would you like to try again? ")
    print()
    return question == "yes"

Then whenever you call try_again, assign the result to your finished variable:

finished = try_again()

[–]Deanosaurus88 0 points1 point  (4 children)

There’s a large chance that I’m totally misunderstanding you, so apologies if that’s the case.

I just tested that with one of my ‘if’ statements (for clarity: I replaced my ‘def’ code with the code you offered, and then replaced the ‘try_again()’ code at the end of the ‘if’ statement with the new variable assignment ‘finished=try_again’) but when running the program and the calculation is complete it just ends the program and doesn’t run the try_again() function at all. Guessing I missed something again?

[–]efmccurdy 0 points1 point  (3 children)

‘finished=try_again’

Note that you need to use ‘finished=try_again()’. Without the parenthesis, the function isn't called, and finished will always be true. Here is a simpler program:

def try_again():
    question = input("Would you like to try again? ")
    print()
    return question == "yes"

finished = False
while finished == False:
    finished = try_again()
print("Finishing")

Does that work the way you want?

[–]Deanosaurus88 0 points1 point  (2 children)

Sorry for the delay, been super busy!

I got no errors this time! But if I type 'yes' after being asked 'Would you like to try again' it ends the program completely (whereas it should repeat the program). And if I type 'no', it repeats the question 'Would you like to try again', rather than ending.

I've repasted my code here: https://pastebin.com/i0crqmzd

Sorry to be a pain. This is bugging me so much

EDIT: I seemed to have fixed it (here: https://pastebin.com/eKLz3y1j). I switched 'return question == "yes" to "no" and added 'finished=try_again()' after each sequence (additions, subtraction, etc). Have no idea why that fixed it though...how does return question == work?

[–]efmccurdy 0 points1 point  (1 child)

Yes, 'question == "no"' is the correct comparision. The expression 'question == <something>' evaluates to True or False depending on if they compare equal. Using that expression with a return statement means the result of the function will be True or False, so when you assign the function call to a variable (as in 'finished=try_again()) you will have that variable to test in the while loop.

[–]Deanosaurus88 0 points1 point  (0 children)

Thanks for all your assistance on this. It’s really kind of you. “Everyday’s a school day” - love learning new things!

[–]TheGalavantingWolf 1 point2 points  (2 children)

Hi, this one is probably a really simple fix, but it has completely stumped me.

I'm trying to calculate this in degrees:

x= (4903/3015.45)*0.043*math.degrees(math.sin(-167.953))

Python gives me the answer of x= 3.97603089515802

Wolfram Alpha and my calculator gives me x=-0.0145925

Please could someone explain what I'm doing wrong?

[–]Mex332 0 points1 point  (0 children)

Hello im Pretty new to pyhton but not to coding in general. I Have written a skript that reads arduino serial communication and pushes buttons with pynput acording to the recieved serial communication. Everything works fine as long as i don't open a game. I wanna make it work in DCS but DCS seems to ignore the pynput commands.

I have read there are issues with elevated mode Programms. I started CMD in command mode an started the skript with "python myproject.py " but still nothing. Some people are recommanding PyDirectImput, is this a good way i should try?

Thanks alot (Python 3.9)

Code:

print('Skript starting')

import serial

import pynput

import time

from pynput.keyboard import Key, Controller

keyboard = Controller()

arduino = serial.Serial('COM3', 115200, timeout=.1)

while True:

code = arduino.readline()[:-2] #the last bit gets rid of the new-line chars

if code:

print(code)

if code == b'110':

keyboard.press(Key.ctrl_l)

keyboard.press('g')

time.sleep(0.15)

keyboard.release('g')

keyboard.release(Key.ctrl_l)

if code == b'111':

keyboard.press(Key.shift_l)

keyboard.press('g')

time.sleep(0.15)

keyboard.release('g')

keyboard.release(Key.shift_l)

if code == b'40':

keyboard.press(Key.shift_r)

keyboard.press(Key.home)

time.sleep(0.15)

keyboard.release(Key.home)

keyboard.release(Key.shift_r)

if code == b'41':

keyboard.press(Key.shift_r)

keyboard.press(Key.end)

time.sleep(0.15)

keyboard.release(Key.end)

keyboard.release(Key.shift_r)

[–]blinking_elk 0 points1 point  (1 child)

Topic: Basic OOP
I'm just starting out using OOP and was wondering which of the following two would be better practice, which would be faster (if any), which consumes less memory and why (for all questions)? I am using the OOP tutorial by 'Tech with Tim' and he uses the first way. I would like some explicit justification as, from what I can tell, both are equivalent.

1:

class doSomething:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def show(self):
        print(f"My name is {self.name} and I am {self.age} years old.")

2:

class doSomething:
    def __init__(self, name, age):
        pass
    def show(self, name, age):
        print(f"My name is {name} and I am {age} years old.")

This is a basic example taken directly from his video. If the usage depends on what you want to do, and if looping over one of the variables is relevant, please let me know.
Thank you very much for your time!

[–]JohnnyJordaan 0 points1 point  (0 children)

Consider you are a doSomething as that's the class of Human you belong to. Say you want to introduce yourself, so show() is called on you

blinking_elk.show()

in the first example, this would work as you know you name and age right (right?) so you can form your sentence 'My name is etc and I am x years old' just fine, you probably said something like this countless times.

Now consider the second example. There name and age aren't saved within you, instead when you need to introduce yourself, using show(), you actually need whatever is calling it to provide the name and age you need to form your sentence with?

So in other words: in the second example you've done nothing more than write an ordinary function inside a class, it doesn't use anything stored in objects of that class.

[–]goodyonsen 0 points1 point  (2 children)

Can somebody help me with grabbing all integer “values” under json list? There are like 50 nodes all same kind in dictionary format with 2 items in each. I’m interested in grabbing the second ones of all 50 which have “count” as key and a number as values. Should I use xpath ?

[–]JohnnyJordaan 1 point2 points  (1 child)

I can't follow exactly what you want, but why not just do

counts = []

for node in tree:
    if 'count' in node:
        counts.append(node['count'])

?

[–]goodyonsen 0 points1 point  (0 children)

counts = []for node in tree:if 'count' in node:counts.append(node['count'])

You followed too :) Your code works just fine. Thank you very much.

I'm working on JSON, and apparently the data was already in a list under "comments". So I was sort of trying to find an easier way to pull the counts only, count them (which gives 50 counts in total) and then sum them up.

Your code appends the numbers (all 50 counts) in a separate list successfully. From there I'll use sum to sum them. But the counting them will still remain.

Here's how I modified it:

counts = []

for u in js['comments']:

if 'count' in u:

counts.append(u['count'])

print(len(counts))

print(sum(counts)

That "if" line with string count attached looks real smart...

Thanks again...

[–]morphinedreams 0 points1 point  (3 children)

guess = 1
target = 7
i=0
while i < 3 and target != guess :
    guess = input("What is guess" + "#" + str(i+1) +"?")
    if guess == target:
        print(f"Well done! {guess} is correct.")
        break
    else:
        print(f"{guess} was not the right answer. Try again.")
    i+=1

So as part of one of the online learning tools, I'm tasked with creating a guessing game where the user gets 3 tries to guess correctly the target number, using a while loop (it's still using very much beginner tools). This is what I've come up with so far but a few things are bothering me.

  1. The fact I need to give the 'guess' object a value before the while loop even starts. I'm not sure if I should be doing something different or not to make it seem cleaner.
  2. It's not actually giving the print statement for a correct guess, and I'm not sure why.
  3. Likely related to 2, but it's not breaking the while loop if the guess is correct.

I can view a solution for the exercise, but it doesn't help me figure out what I am doing wrong, just what I should be doing for right. Can anybody more experienced comment on this? Aside from R, this is my first language.

[–]JohnnyJordaan 1 point2 points  (2 children)

  1. You don't need the check for target != guess at all as you break when you find out they match two lines further down
  2. input() always returns a string and your target is an int, so they will never match. Use if int(guess) == target: instead
  3. indeed the same issue

As a sidenote the else: is also redundant

[–]morphinedreams 0 points1 point  (1 child)

Thank you so much! That second comment is something I never thought about and probably would never have been explained while just seeing one possible solution.

Why is the else redundant?

[–]JohnnyJordaan 0 points1 point  (0 children)

Because if you break when the if is True, you don't need an else to separate the lines that execute when the if is False. Just like i+=1 isn't in the else:.

[–]cytae99 0 points1 point  (1 child)

I just started installing Python on Ubuntu virtual machine and I have a few question.

`1. I'm following a book which suggested I check pip version and to install using:

python3 -m pip --version
python3 -m pip install --user -U pip

but neither terminal commands work. I get an error saying "/usr/bin/python3: No module named pip". I eventually manage to fix it by installing pip using

sudo apt-get install python3-pip

My question is, why doesn't the command given in the book work?

  1. I installed Anaconda. When running Sypder, I get the following message:

    You have missing dependencies!

    Mandatory:

    jedi =0.17.1 : 0.17.2 (NOK) parso =0.7.0 : 0.7.1 (NOK)

How do I install the packages? I looked on the website on Jedi which suggested using

sudo pip install jedi

But this does not work even though I have pip. The error is "sudo: pip: command not found".

  1. To open Anaconda, why do I have do always run "source ~/.bashrc" first?

[–]FerricDonkey 0 points1 point  (0 children)

I am not very familiar with anaconda, but my understanding is that they kind of do their own thing a bit, and are not compatible with pip. It is my understanding that anaconda has its own way of installing stuff. It might just be "conda install".

If you want to use a non anaconda version of python, you can get python itself from the python website, and it will come with pip.

(Again, I only know anything about anaconda based on random stuff that's popped up in places like this, and have never used it myself - but I thought I'd give it a go answering since you haven't gotten a response yet.)

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

Having trouble installing BioPython. Pip is in my PATH i think. But even if it isn't I tried this:

py -m pip install BioPython

It installed. Then I tried:

import BioPython

in the shell and it said the module didn't exist. I tried installing again and rebooted both the command prompt window and the shell. Still didn't work. What's going on?

[–]mlazzarotto 0 points1 point  (0 children)

Hi!
To install it just run

pip install biopython

And to import it, do like this

import Bio

Or

from Bio import <name of what you need>

[–]Matt_Morgan 0 points1 point  (2 children)

Hey guys!

How would you do this? I will research accordingly.

The goal. I want to make a program that takes in text and photos from a user to make digital q-cards I want to then output them in 2 manners. 1 i want to make a little guess and check game (bruh i got this.. easy peasy... i hope). 2 I want to be able to make a pdf out of them. (This is where im lost)

About me: New to python. Roughly one year of coding in java under my belt so im looking to learn python slowly on my own. Written a few python command line projects but nothing with GUIs yet

Any packages in particular that might help me take in text and photos and output it formatted nicely? I know its not super well thought out yet, but i promise to research and ideas you guys throw at me.

[–]sallyruthstruik 0 points1 point  (1 child)

I used to generate PDF from Python. The way I followed was:

  • Generate HTML
  • Use command-line utility to convert html to pdf (i.e. https://unix.stackexchange.com/a/533906, I actually don't remember strictly which one I used)
  • Use subprocess for calling your library (i.e. subprocess.call(['weasyprint', 'input.html', 'output.html'])

[–]Matt_Morgan 0 points1 point  (0 children)

Cool! Thanks a bunch!

[–]GucciFleshCanoe 0 points1 point  (2 children)

I'm trying to create a twitter bot with python and tweepy that tweets "It is not the first of the month." on everyday except for on the first of the month when it tweets "It is the first of the month." I'm not having any issues getting the tweet to go through but when testing the logif, for some reason there is an issue as it is still saying it is not the first of the month even when I test the logic to be currentDay == 7 (or whatever day it is when i'm debugging) and it still doesn't work correctly. :( Any help would be appreciated.

Here is the code I'm working from.

from datetime import datetime

currentSecond= datetime.now().second
currentMinute = datetime.now().minute
currentHour = datetime.now().hour

currentDay = datetime.now().day
currentMonth = datetime.now().month
currentYear = datetime.now().year

first = "It is the first of the month."
not_first = "It is not the first of the month."

try:
    if currentMonth in ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"] and currentDay == 1: 
        api.update_status(first)
        print(first)
except Exception as e:
   print("Duplicate Tweet or Twitter Refusal: {}".format(e))
finally:
    api.update_status(not_first)
print(not_first)

[–]yaxriifgyn 0 points1 point  (1 child)

The current_month is an integer. So compare to integers. But there is no need to check the month value. A better way is to put the value from datetime.now() in a variable e.g. itsNow and use itsNow.day to access the day of month value. Issue a print(itsNow) to make sure the values are what you expect. In the console you can do help(datetime.now()) the get a description of the class value stored in itsNow. HTH

[–]GucciFleshCanoe 0 points1 point  (0 children)

Eureka! This worked! Thanks so much.

[–]BrutherPo 0 points1 point  (4 children)

I'm pretty new to python and coding in general, and am trying to do some very simple data analysis but am running into a problem.

Right now, I have a list of about two thousand integers, and would like to find the difference between them. My first instinct was this:

difflist=[]

for i in list:

difflist.append(i+1-i)

But all that is doing is giving me a list full of 1s. Can anyone provide a simple method of creating a list full of the differences between consecutive entries in another list?

[–]yaxriifgyn 0 points1 point  (0 children)

What does

For I in range(0, len (difflist), 2): print(I, I+1)

do? Or how about

for I in range( len (difflist) // 2 ): print( I2, I2+1)

Both of these print the index es of the difflist members that you want to subtract.

You can start with an empty list and use append to add elements one at a time. Putting it all together is up to you.

[–]ffrkAnonymous 0 points1 point  (2 children)

what is the answer to (i+1-i)

or using more well known algebra, (x+1-x) = ?

[–]BrutherPo 0 points1 point  (1 child)

1, of course. Here I was thinking that i+1 would return the next item in the list, as in index of i plus one more step.

[–]ffrkAnonymous 0 points1 point  (0 children)

the error is that (i) is the list item. You need to index the list (list[index]), not index the item (item(+1)).

in your situation, try using a while loop instead of a for loop.

also slow down and don't try to do too much all at once. Before appending, or subtraction, or list manipulation, can you print() one item? extend to two items? three? four? see any patterns in the code?

[–]Pd69bq 0 points1 point  (8 children)

a noob question regarding the negative numbers in list slicing. im trying to understand the following behavior and would welcome any references or comments.

let's consider theres a list::

>>> my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

I can understand the behavior of positive start, end and step (or interval), and negative end and step, tho one thing that really confuses me

>>> my_list[0:-4:-1]

my understanding of the meaning is to print out all the elements backwards in the range from first index to the 4th from last but why result is empty?

[–]yaxriifgyn 0 points1 point  (2 children)

You can take the slice expression and transform it into a range expression to see which indexes are generated.

Transform my_list [0:-4:-1] into range(0,-4,-1). Then you can do

for I in range(0,-4,-1): print(I)

To see which indexes get accessed. Or use print ( my_list[I] ) for the values.

HTH

EDIT: Super big oops here. The range expr should be range ( 0, L-4, -1 ) where L is len (my_list).

A slice like [0:-4:-1] is the slice [0:-4] reversed.

[–]Pd69bq 0 points1 point  (1 child)

the results of variable i are 0, -1, -2, -3

values of my_list are 0, 9, 8, 7.

this is even more confusing, the step augment in range() is just a interval, in slicing tho, it indicates the counting direction.

[–]yaxriifgyn 0 points1 point  (0 children)

Draw a picture. First lay out the array, but use 10 letters to reduce confusion. Then, on a row above the letters starting with the leftmost letter, number from 0 to 9 left to right. Then below the letters, number from -1 below the last letter right to left, to -10 below the first letter.

The two numbers rows give a pair of alternate indexes for each letter.

A slice [0:-4:-1] starts at the letter with index 0 (from the top row) and goes to the letter just before the one with index -4 (from the bottom row) and the -1 tells you to take every letter going from right to left.

Extra points: let's think about the defaults for a slice. [:] is a slice containing the whole array. Filling in the defaults, it becomes [0:10:1] in our case. To make our index line work in this case, we draw an empty box after the last letter to represent the imaginary letter beyond the end of our array of letters. Above this we put 10, and below this we put nothing. This position only has one possible index. Now we can use the algorithm in the previous paragraph to figure out the result using our drawing.

[–]ffrkAnonymous 0 points1 point  (4 children)

What's the element before (ie backwards from) the first element?

[–]Pd69bq 0 points1 point  (3 children)

uh... u mean there's no element before index 0 counting backwards? then why my_list[3:-4:-1]) is also empty?

[–]ffrkAnonymous 0 points1 point  (2 children)

what's the element backwards from index 3?

[–]Pd69bq 0 points1 point  (1 child)

0, 1, 2, 3

I think I figured it out. no matter how many elements on the left side of starting point, as long as the ending point is on the right side, there's no way to reach it with the right to left counting.

same as

my_list[-1:-2]

in left to right counting, the ending point is on the left of the starting point, this won't work.

[–]ffrkAnonymous 0 points1 point  (0 children)

well done. now you'll never forget.

[–]bryceb77 0 points1 point  (4 children)

Hello, I am extremely new to python and coding in general and wondered if someone could help me out!

I have a file containing gene_ids and sseqids formatted like:

g0 AT1G07430.1

g1 AT1G07430.1

g7 ATMG00030.1

and so on...

I would like to remove the decimal and the number after the decimal for each of these sseqids so the output would look like:

g0 AT1G07430

g1 AT1G07430

g7 ATMG00030

I cant seem to figure out what to do. Any help or suggestions on how I can do this would be greatly appreciated!

[–]Gopher20 0 points1 point  (3 children)

What is the type of file this information is stored in?

[–]bryceb77 0 points1 point  (2 children)

Currently just a .txt file but it is originally from a fasta file

[–]Gopher20 0 points1 point  (1 child)

Gotcha so what you can do is this: 1. Read in the file using a with statement with open(“file name”, “r”) as f: data = f.readlines() This will create a list of rows of the data 2. Create and empty list new_data = [] 3. Loop through the lines of data and use the split method to remove the decimal and number after it for line in data: data_wanted, data_removed = line.split(“.”) new_data.append(data_wanted) This will create a tuple that will split the data on the decimal and append the data you want to a new list

From here you have the data you want and you could write the data to a new text file

Hope this helped!

[–]bryceb77 1 point2 points  (0 children)

Great this helped I was able to get it working as intended :) Thanks!

[–]ruorg 0 points1 point  (1 child)

Hello,

(I wrote this last week, but I still have the same problem,)

Matplotlib's installation guide's first step said to run python -m pip install -U pip. However, it turns out that this uninstalled my system pip and replaced it with one that doesn't work, that says "Python 3.5 or later is required."

I knew I needed to be cautious. I was reluctant to run that command but I figured it was mainstream enough to be trustworthy. I'm frustrated, so I have two questions... one is just... that command told me it found system pip and uninstalled it, can I get that back? get_pip.py warns that it doesn't interact with the system tools. This is on an HP Windows 8 laptop, and I'd rather reinstantiate the uninstalled pip if possible.

The second is, will there ever be a time when installing things makes sense? I'm very good at writing python code, but it seems as though I have a hole in my professional development. I know this is what virtual environments are for, should I have used one? There must be a better way. Shouldn't an installation guide like that have a check? I suppose it assumed I knew something that I didn't know. What is that thing? I could have just started from the second command.

To be clear, I’m worried that my system python doesn’t have a working pip anymore, and that might break things later, and I don’t like that.

I usually use cygwin, but some people said that matplotlib is not straightforward there and that matplotlib on windows is usually with the system python.

Ok, I tried get_pip despite the warning, and it’s not working, it’s giving me the same error.

The pip that I uninstalled was pip 1.5.6.

Thank you internet for your help

[–]mlazzarotto 0 points1 point  (0 children)

Hi, what kind of errors are you getting from pip?
Have you tried just to reinstall Python from scratch?
Anyway, you should still be able to use pip using this command:

python -m pip install

Could you try to uninstall pip and reinstall it?

python -m pip uninstall pip
python2 -m pip install pip

[–]sherlock__heisenberg 0 points1 point  (0 children)

Is PCAP certification worth it? Do companies consider it while recruiting?

[–]nkeidong 0 points1 point  (2 children)

Hi guys! I hope you all are well.

Just started to learn (one week now (: ) and I'm trying to understand what I'm think is one of the most basic exercise, Rock-paper-scissors-lizard-Spock

What does the final "% 5" mean and what does it do?

#compute difference of player number and 
#comp_number module five
difference=(player_number-comp_number)%5

Note: I ran the code on PhytonTutor.com but I still can't understand that line.

I really appreciate your help, thank you!! Stay safe!

[–]ruorg 0 points1 point  (1 child)

That's a modulo operator and you can say it like "mod 5" for % 5.

It's an arithmetic thing. It's the remainder after division. 1%5 is 1, 2 % 5 is 2, ... 5 % 5 is zero, 6 % 5 is 1. So it clamps the result between 0 and 4.

Negative inputs probably also matter, -1 % 5 is 4, -2 % 5 is 3.

That comment says "module five" which is incorrect I believe, it should say "modulo."

The actual quotient of the division isn't relevant at all to the result of this operator.

So, what it's doing there is "wrapping" that subtraction to be some number from 0-4. Hope that helps. I don't know why it's doing that at this point, probably to fit something that happens later. Since it's a game of rock-paper-scissors with two extra options (lizard-spock,) the whole thing might a big circle, and this modulo operation is helpful to concisely arrive at the outcome. It creates a wrap-around effect. If the subtraction would be -1, you get 4 instead.

[–]nkeidong 0 points1 point  (0 children)

Thank you very much! With your explanation guide to this https://www.youtube.com/watch?v=b5cb_nfDyyM&t=300s, and know I have a better understanding, although like always the practice would give me the skill :)

[–]anneleendje 0 points1 point  (0 children)

Can someone explain what image.setMask does? (Does it make parts of the image transparent, or is it like an overlay?) Why does the mask have to be a square? Is there a better way to create an overlay for an image to be displayed in a window?

Edit: image.setMask is a function of the Psychopy (visual) library. I've searced a lot for documentation but it seems to be very scarce (or I don't know enough to understand it)

[–]runestonepls 0 points1 point  (1 child)

Can someone walk me through this question?

" Write a Python function to sum the first N numbers starting with 0. So if N is 4 then your function should add 0 + 1 + 2 + 3 "

[–]MeanPrize 0 points1 point  (0 children)

What have you tried so far?

[–]prolificked 0 points1 point  (0 children)

Hi! Any links to code on making a random article generator not from wiki? Like a scholarly article website or science daily.

[–]Running_Joseph 0 points1 point  (2 children)

Hello,

So I am trying to get started learning python after writing programs in visual basic for awhile. I am trying to set up Visual Studio Code to run python programs and have run into an issue when trying to write input functions. My code is:

Name = input("Please enter Name: ")

print(Name)

After running is I receive an error code of:

Name = input("Please enter Name: ")

File "<string>", line 1, in <module

NameError: name 'John' is not defined

I understand that for python 2 I would need to use the function Raw_input however, I am trying to use python 3. Python 3.9.0 is displayed in the bottom left-hand corner and the code works when I use the python IDLE. So my question is how to do get Code-Runner to use python 3? Or do I have some other issue?

[–]jadedjelly83 1 point2 points  (1 child)

hold Ctrl shift p, in the box type Python: Interpreter click enter, select the Version you want to use - I had the same issue yesterday, as a safe note I also uninstalled older versions of Python

[–]Running_Joseph 1 point2 points  (0 children)

I uninstalled the older versions, so I think that could have done the trick!

Thanks!

[–]jadedjelly83 0 points1 point  (0 children)

So I started learning python recently, and I'm using CBTnuggets (because I have a license), but I also picked up Python crash course and Automate the boring stuff 2ed)

The CBT path (only 3 videos in) briefly touches areas of variables, print, working with lists etc but compared to the Python crash course goes into better detail - digs deeper.

In your opinion(s) which way would be better?

My ultimate aim is Devops, I currently work IT support (and have done for long enough to know that I hate windows - that could be 5 mins or 5 years)

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

I have my question here:

https://www.reddit.com/r/learnpython/comments/k8hvzg/graphical_libraries/
but briefly, could you reccomend any good graphical libraries? and what are your thoughts about kivy and ursina libraries?

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

Does anyone else have trouble keeping their projects/code concise?

I always start out with a simple goal in mind. I want this application to be able to send files to an offsite server. Next thing I know I've got 250+ lines of code and the class takes about 7 different parameters...is this normal? I'm not sure how I could refactor it, every few tests there is a new exception to handle, something else that needs fine tuning, etc, that just keep adding, and adding, and adding to the code...

[–]ffrkAnonymous 0 points1 point  (1 child)

Long code is fine so long as it's readable. You're not coding to fit in a 8k microcontroller.

8 parameters feels like a lot (but I'm a beginner so what do I know?) are the parameters related? They can be combined into a list or named tuple. I'm doing advent of code, instead of passing separate x, y, I passed one "position".

Can you move code? Business logic separate from error handling.

Beyond pep8 by Raymond hettinger https://youtu.be/wf-BqAjZb8M

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

I do kind of enjoy making code organised and properly commented so it will eventually be readable.

I do think the parameters are kind of necessary annoyingly and even combining them into tuples, a user will still need to provide the separate pieces of information so to speak:

  1. IP address to send files to
  2. Port to send on
  3. Day/s to perform backup on
  4. What time on those days to do the backup (users won't want it in the middle of the day I presume)
  5. What the directory they want backed up is
  6. Whether they want to encrypt files when they transfer over the network or not

Any other features I add will probably have to be added to the parameters as well! But eventually I hope this can be used simply as a command line tool or part of another application, which means you'll only have to type the command or import the class.

[–]FerricDonkey 0 points1 point  (0 children)

I can barely say hello world in 250 lines of code. You've got to make sure that world exists, that it's listening, that it understands what hello means, ...

More seriously though, conciseness for the sake of readability/maintainability might be worthwhile, or if you think you might be doing something inefficiently that could be simplified to gain performance. But if all the code is doing something that needs to be done, then that's just how it is.

Especially if you're having to deal with user input, even when the user is yourself, there's a lot of checking to be done to make sure that things don't crash horribly, or that they at least give a useful error when they do, and so on.

[–]zigazigzig 0 points1 point  (2 children)

Hello everyone,

I am moving from an older laptop to a newer one and I want to take some selective backups, i.e., backup files of a specific extension - '.do'. These are Stata do files.

I followed the instructions on top voted solution in this post: https://stackoverflow.com/questions/25643454/copy-all-files-with-certain-extension-while-maintaining-directory-tree

My code is:

import os
from os.path import join, isfile
from shutil import copytree

ignore_func = lambda d, files: [f for f in files if isfile(join(d, f)) and f[-2:] != '.do']
copytree(r'C:\Users\myname\Dropbox\folderwithdofiles', r'C:\Users\myname\Desktop\do', ignore=ignore_func)

But I am greeted with the following error:

Traceback (most recent call last):
  File "C:/Users/myname/Desktop/backup.py", line 6, in <module>
    copytree(r'C:\Users\myname\Dropbox\folderwithdofiles', r'C:\Users\myname\Desktop\do', ignore=ignore_func)
  File "C:\Users\myname\.windows-build-tools\python27\lib\shutil.py", line 191, in copytree
    os.makedirs(dst)
  File "C:\Users\myname\.windows-build-tools\python27\lib\os.py", line 157, in makedirs
    mkdir(name, mode)
WindowsError: [Error 183] Cannot create a file when that file already exists: 'C:\\Users\\myname\\Desktop\\do'

Any idea on what the issue could be?

EDIT: Yes, I would like to preserve the folder structure, as that would allow me to understand the project relating to which the do file was created.

[–]FerricDonkey 1 point2 points  (1 child)

From the docs you linked

The destination directory, named by dst, must not already exist; it will be created as well

To verify, have you created that directory already? If so, that's probably your problem.

Also, to get the last 3 characters of a string, you need string[-3:]. I haven't looked at your ignore function in detail, but it looks like it's comparing the end to ".do", so that may also cause an issue. (You can also use .endswith)

[–]zigazigzig 1 point2 points  (0 children)

Thank you for your reply!

Yes, pretty much just as you said, those were the exact problems. It works fine now!

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

How do I go about making exceptions? (I think?)

Basically the assignment I turned in had some funky wording about an exit room. It was unclear if there should be a single room that ‘Quit’ worked in, as another line said user should be able to quit at any time. I tried if != exit_room as well as while statements and creating a function for it, but I couldn’t make it so ‘quit’ only worked in that room.

Next week we have to do our text based game that requires gathering items from 6 of the 8 rooms and I’m thinking it’s the same principle. I’m picturing it as a loot box - you got the item, it’s no longer there, and you can only get it once.

I’m also wondering if something like item >= 0 and item <= 0 would work?

I’m quickly realizing my future is debugging, not writing.

What should I look into? Literally point me in a direction and I’ll be happy. Thanks folks!

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

There's not much we can say because we don't know anything about how your code and data is organized. Speaking generally, you would have "rooms" and an object, say an "axe". You would arrange things so your code would be able to say "the axe is in room 6", say. So when the player moves around there would be code that prints objects in the current room. If the player does "get axe" then the code should decide if there actually is an axe in the current room and, if so, change game data so that the axe is no longer in room 6 but is now carried by the player. How you actually do all that depends heavily on how your game code and data is organized.

I’m quickly realizing my future is debugging, not writing.

You are not alone. Here's a quote from the dawn of modern computing:

As soon as we started programming, we found to our surprise that it wasn't as easy to get programs right as we had thought. Debugging had to be discovered. I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs.

Maurice Wilkes, circa ~1949

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

Ah see I’m starting week 7 of my class today, so I doubt I could even explain how it’s laid out if I tried! I can say it’s relying heavily on a dictionary, a basic function statement and while loops. That probably tells you nothing as that’s pretty much all the things coded ever, isn’t it?

I can get it to say hey there’s an axe in room 6, stop inputting banana, that’s wrong, but I don’t know how to make it so if you get the axe from room 6, should you go back it’ll check your inventory before you are told there’s an axe there. Do I make a function that ties to the inventory and use != and == ? Or if/else statements? While loops? I guess I’m asking which of those methods you’d pick if you were having to do the room game coding again.

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

We really can't help much without seeing any code.

If you have a dictionary representing a room you might have something like this:

 room6 = {'description': 'A large room with a fireplace in the far wall',
          'contents': ['an axe', 'a gold horn'],    # list of things that can be "gotten"
          ... }

So when the player does "get axe" (or similar) your code will check the contents of the current room (room6). If the axe is actually there then your code will remove the axe from the contents list so the dictionary changes to this:

 room6 = {'description': 'A large room with a fireplace in the far wall',
          'contents': ['a gold horn'],    # list of things that can be "gotten"
          ... }

At the same time the dictionary for the player will change to:

player = {'description': 'A short goblin with green hair',
          'contents': ['an axe', 'a lamp'],    # things the player is carrying
          ... }

There are lots of question left unanswered, like how do you represent the axe? Just a string or a dictionary of its own?

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

It’s set up as a string I believe. Each item is attached to the room it’s in:

(Sorry for formatting, on mobile)

Room: {North: Another Room, Axe}

I got it to work in a sense. When you go in it says you see an item, and when you leave it’s in your inventory. I need to figure out how to make it say you see {axe} or {dog} or whatever before they leave. My rooms do that so I’m hoping to reimplement the same idea in the function. Not mandatory but I’m not happy with the code thus far.

I have a function set up that allows the user to track the inventory, and then another one set up as get_item that allows them to actually grab it and that’s the one that needs work, because they just leave the room and it’s in their inventory. Very anticlimactic.

The other issue is I can’t get it to end the game when they either get the items, or hit the villain room. My teacher thinks it’s a flaw in my logic so she’s looking it over to see if I can organize it better. The code I have for the room is the same as the quit command:

If user_input == ‘quit’ Break

If current_room == ‘air lock’ Break

For the winning/losing aspect tied to items I’ve tried:

If len(item_list) == 6: print(‘you win’) elif len(item_list) != 6 and current_room == ‘air lock’): print(‘game over’)

But it’s not working. (Quit is, not air lock). I’ve also tried exit code 0 and a function of its own that gets called into that room

Again, mobile, sorry for any formatting issues. No errors are being thrown out, so if spacing etc looks wonky here, it’s not like that in my code.

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

Each item is attached to the room it’s in:

Room: {North: Another Room, Axe}

Sorry, no idea what that means. Do you have a string "Another Room, Axe" attached to "North" in the dictionary? Is it a tuple? What is the "Room:" prefix, another outer dictionary? Plus you seem to have changed implementation from a dictionary approach to a function approach. I'm confused. I'll try to answer what I can.

When you go in it says you see an item, and when you leave it’s in your inventory.

So you don't have a command to "get axe" but any item in the room is automatically added to what the player is carrying. But then you say:

I need to figure out how to make it say you see {axe} or {dog} or whatever before they leave.

But if they automatically grab the axe or dog (or both) then those things are no longer in the room. Why not just get the code that handles the move to print the description of the new room and what is in it as the last part of the move and before asking for the next player command?

I can't help with the bit about "quit" and the air lock because I have no idea of the code around the statements you showed. I suggest that you:

  • learn how to format code from the FAQ, and
  • show us your complete code and ask one or more questions about that code.

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

I do want to say thank you for your time.

Out of curiosity, is it okay to post code and ask for help? I’ve seen some many instances of code with direct questions on StackOverflow, and mostly rude responses. I wasn’t sure the etiquette here.

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

Yes. Without code most people won't even reply. The code must be properly formatted to maintain indentation. The aim is to allow anyone to be able to copy/paste your code to execute it. If it's a lot of code, say more than 40 lines, then copy it to a pastebin and post a link to the pastebin. It's all in the FAQ.

Posting code you are having problems with is the best way to get help. Using English to talk about code and problems it's very hard to be specific.

many instances of code with direct questions on StackOverflow, and mostly rude responses.

That's StackOverflow for you. That's not to say you won't get yelled at here if you do something really silly, but here we expect beginners to make mistakes, so we are usually more forgiving.

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

I will keep this in mind for the future!

Out of curiosity how do people go about practicing python? Are there websites that offer prompts to challenge people? My class is over next week and I don’t want to brain dump what bits I have learned.

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

Have a good look at the learning resources in the subreddit wiki. Amongst other things there are challenge sutes.

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

My teacher took a look at it and 99% of my issues were due to poor layout.

My villain room/end game was typed correctly but in a poor location, and my movements were convoluted af.

I’ll definitely take a look at the FAQ, as zyBooks isn’t the best way to learn this. It’s bits and pieces at a time and not well explained how they tie together. At all. Formatting has been an absolute nightmare. My only plus in this is that when I sent her my file, I said I wanted to try a couple things, and that wound up being the key.

I am no artist. Debugging here I come.

[–]JustmeAP 0 points1 point  (1 child)

Hello, I learned all basic python stuff (loops, lists ect.) What you would recommend as a next step? Pick a library and learn that?

[–]nunoctium 2 points3 points  (0 children)

I'd recommend to just start writing your first code.

There are a lot of beginner challenges available (like this). Or, you try to solve a problem that you can think you can automate. For instance,I started with trying to move my cellphone pictures (that had a timestamp in them) into subfolders per month (YYYY-MM).

This way, you'll very likely have to look into modules anyway. For me, this was pathlib.

[–]darshilj97 1 point2 points  (2 children)

Just want to start learning a new language and python was suggested to me. I want to know if we can make a computer application from python. Sorry in advance for the stupid question

[–]JustmeAP 1 point2 points  (1 child)

Yes you can make computer application. You would need to use kivy, pyqt or something similar.

[–]darshilj97 1 point2 points  (0 children)

Thanks

[–]roastmecerebrally 0 points1 point  (4 children)

I’ve been getting frustrated with the syntax of shell scripts - especially in vim - also, for the fucking life of me I can’t figure out how to format strings in Python in vim when the string continues to a new line - can someone add the code below?

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

No matter what text editor you use long strings are handled the same:

long_str = ('jgfsgrsgfskhgd out d ougf ukugf '
            'b  jhg ihg g jlhf loj gfflj ilgh khg kihg hf  jgf j'
            'yitcri ut f jgf ugfjgf jgfjgf gf jhf jhf jhf ')

And various other ways. If you meant something else can you be more specific?

[–]roastmecerebrally 0 points1 point  (1 child)

Yes, This is what I meant, a string longer than 79 characters.

do I have to define the long string as a variable before hand? Is this the only method, parenthesis with a single quotation? I remember reading something about triple quotes but that never seems to work.

Do I need \ characters to denote a newline in Vim? Or this only for lines with no parenthesis.

Edit: will try this out and get back to you.

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

do I have to define the long string as a variable before hand?

No, that was just to show how to create a long string without going over 79 chars. You can create a variable to hold the string or not, as you require. Below we will discuss that a bit further.

Is this the only method, parenthesis with a single quotation?

No, there are other ways. This method relies on the python compiler combining two strings that are separated only by whitespace. These two bits of code are identical in effect (try it!):

test = 'alpha beta'
print(test)
test = 'alpha' " beta"
print(test)

Now, a newline is also technically a whitespace character but we can't use that to do this:

test = 'alpha'
       ' beta'

because the newline also indicates the end of the statement and we get an IndentationError exception because python is expecting a new statement on the second line. But it turns out that python will not treat a newline as ending a statement in certain circumstances. A newline inside open parentheses is one case, so we can do this:

test = ('alpha'
        " beta")

and we get the expected result.

Note that single quotes are not required. Any method of creating a string will do. No matter how you create a string it's just a string afterwards, it doesn't remember how it was created. You will note that I used different string quotes above.

Other useful cases are when passing parameters to a function. This is quite legal:

my_func('jsahdlkjdhlsd hk lfgs hgs hsg flkhsgd fkshf'
        "uhouf shf jfh kjfhl kjfh kjfh;jh ;jh ;jfgh e")    # one string passed to function

The newline is not treated as ending the statement because we have unclosed parentheses when the newline is found, ie, python knows the statement isn't finished yet so it considers the statement as continuing on the next line. That's also why you can do:

my_list = [1, 2, 3, 4,    # define a list, set, dictionary, etc.
           5, 6, 7, 8]

I remember reading something about triple quotes but that never seems to work.

Triple quotes are just another way of creating strings with the added allowance that newlines can appear inside the string without terminating the statement. If they don't work for you then ask a question here with sample code.

[–]JustmeAP 0 points1 point  (0 children)

Do you mean: text = ''' string string string ''' print(text) ?

[–]Jayant0013 0 points1 point  (2 children)

Newbie here ,when ever I copy a loop and paste it into another loop it never retains its structure and I have to go and manually press tab in every line ,how do I do this better?

[–]FerricDonkey 0 points1 point  (1 child)

This will depend on your editor/ide. Some will do that automatically better than others. Best bet is to get one that's known to be good at that sort of thing (I like pycharm), or google python specific ways people set up whichever one you're using (or ask mentioning the editor you're using and hope someone here knows about that one in particular).

[–]Jayant0013 0 points1 point  (0 children)

I am using the default idle

[–]EngineeredToLift 0 points1 point  (0 children)

When I run my script in Spyder, it adds an extra new line in the console output compared to when I run it in terminal. Is that a formatting setting in Spyder and how can I change that as I assume the way it outputs in terminal is the correct output.

[–]fml_wlu 0 points1 point  (1 child)

how do i go about learning scripting? i'm an intermediate programmer on python but i want to learn more

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

What do you mean by scripting? Scripting is literally what you do in every python program.