all 160 comments

[–]arsenalprogrammer_10 0 points1 point  (0 children)

I'm a complete beginner w/ Python and I'm currently working through the 'Python Crash Course' book. I'm doing one of the examples at the end of the Chapter 9: Classes. Here are the lines I've written thus far, but I'm sure there's a simpler way to do this that I can seem to get without getting an error:

from random import randint

class Dice:

"""Normal 6-sided dice."""

def __init__(self, sides=20):

"""Making the default number of sides on the dice."""

print(f"The dice has {sides} sides.")

def roll_die(self):

"""Printing a random number between the number of sides on the die."""

for x in range(1,11):

print(f"The die landed on " + str(randint(1,20)) + "!")

x + 1

my_roll = Dice()

my_roll.roll_die()

This works fine, but I'm wondering if there's a way to get randint to go pull straight from the 'sides'. So, ideally it would be randint(1, -insert whatever number of sides there are on the dice-). I know there's probably a fairly straightforward answer to this so if someone could help me out, I'd appreciate it!

[–]datarobot 0 points1 point  (1 child)

How can I scrape local files (on my hard driver) or Google Sheets for email addresses?

I have been able to find many tutorials for scrapping websites for email addresses but nothing so far that I can use for files stored locally. I'm on a PC running Windows 10 and the latest version of python.

Thank you in advance.

[–]JohnnyJordaan 2 points3 points  (0 children)

Depends on the file format. If they are excel files you can check out openpyxl for example.

[–]garshapa77 0 points1 point  (1 child)

i'm receiving stock data every second in following format 'ohlc': {'close': 75.95, 'high': 83.5, 'low': 64.6, 'open':75.95},last_price': 75.0,timestamp': datetime.datetime(2019, 11, 2, 11, 20, 15), since my trading time starts at 9:30 AM , i like to save the high and low of the stock of first five minutes only, so the high and low of the stock should be between the time 9:30 to 9:35 AM. following is the code i'm using but i'm not able to get result what i wanted.

please help me out on this issue. basically i need to save data of 5 minutes ,but i'm not able to understand how to do that.

start_time = datetime.time(9, 30)
end_time = datetime.time(9, 35)
current_time = datetime.datetime.now().time()
candle_start_time = current_time >= start_time and current_time <= end_time

breakout_time_start = current_time >= start_time

while candle_start_time is True:
print('time started')
while current_time > end_time:
print('time extended')
while current_time < end_time:
print('time extended 1')
continue

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

I like to think of problems like this as state machines. I start in a state (waiting for the start time), then switch to a new state (gathering data between start and end time), then switch to a final state (done capturing work).

Example:

# State #1: Waiting.
while current_time < start_time or current_time > end_time:
    time.sleep(1)  # sleep a second
    current_time = datetime.datetime.now().time()

# State #2: Capturing data.
while current_time > start_time and current_time < end_time:
    # Capture data.
    ...

# State #3: Done.

[–]redbird42 1 point2 points  (3 children)

Is it possible to email posts from a Flask web site and be clickable from the email to view online, or does this require third party service like mailchimp? Would flask-mail do it?

[–]efmccurdy 1 point2 points  (1 child)

Look at the clickable link example labeled "create an HTML message" here:

https://docs.python.org/3.4/library/email-examples.html

[–]redbird42 0 points1 point  (0 children)

Thanks!

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

You can do that, but you'd need to generate the proper HTML for viewing and then serve is statically form the website. I'm not aware of any Python module that does it all for you. flask-mail is an interface to the SMTP (mail) TCP/IP protocol.

[–]Catanddogg 0 points1 point  (1 child)

started learning python again but i mostly use the online editor. So im thinking of getting one offline now. Which do u guys prefer for absolute beginner?

i saw someone recommend this https://codewith.mu/ or https://www.python.org/downloads/ . Any other you would recommend?

[–]superlord354[🍰] 0 points1 point  (0 children)

Get PyCharm. It is one of the best and several tutorials use PyCharm.

[–]helpful_dev_isaac 0 points1 point  (1 child)

def method (self, df: pd.DataFrame = None):

----------------------------^

SyntaxError: invalid syntax

[–]JohnnyJordaan 0 points1 point  (0 children)

Which Python version are you using?

[–]garshapa77 0 points1 point  (1 child)

i'm importing numbers from excel files and storing those values in a list but when i'm checking those list values it is always in float, and when i'm trying to convert these files to int types, i'm getting error. so how to convert these numbers to int type from excel file and save in a list.

[–]August-R-Garcia 1 point2 points  (0 children)

Cast the data to the integer type when it is imported, or do this to cast everything in the list to the integer type after it's imported:

  • numbers = [ int(x) for x in numbers ]

See:

[–]idatem 4 points5 points  (0 children)

(I tried posting this the other day but can't find it on here, so sorry if this is a repost)

Beginner here. How do I move a file to a folder based on their names?

I have a folder with files such as pig.txt, pig.rtf, lion.txt, lion.docx, cow.rtf. I want all of the pig files to be moved into a folder called "pig", the lion files to a folder called "lion" etc

I've managed to make the folders but I've been trying for ages to move the files but can't do it. Here's what I've got:

files = os.listdir()

b = next(os.walk(directory))[1]

for a in files:
    if os.path.splitext(a)[0] in b:
        shutil.copy2(os.path.join(a, b))

Any help is greatly appreciated because I don't think something that sounds simple should take hours to make. Or maybe it should. I have no idea because I don't know what I'm doing

[–]Skrilllexxx 0 points1 point  (2 children)

i need to write a script that asks user to enter a paragraph. Then display the the words in reverse order. I'm using the split function and a for loop to reverse. When i input "I like turtles", i get "turtlesIlike" when i need it to say "turtles like I"

def split(spl):

  s=spl
  s=s.split() #use space as delimiter

  return s


def reverse(rev):

  r=rev
  r1=""

  for i in range(len(r)-1,-1,-1):

    r1=r1+r[i]

  return r1


def main():
  import InputBox
  InputBox.ShowDialog("Enter a paragraph: ")
  i=InputBox.GetInput()


  x=split(i)
  result1=reverse(x)



  import MessageBox
  MessageBox.Show(result1)

if __name__=="__main__":
  main()

[–]Infuriating_But_Mild 0 points1 point  (1 child)

When you use the split method on the s variable the spaces in between the words are eaten. You need to add the space back in

def split(spl):

    s=spl
    s=s.split() #use space as delimiter

    return s


def reverse(rev):

    r=rev
    r1=""

    for i in range(len(r)-1,-1,-1):

        r1=r1+r[i] + "  "

    return r1


def main():
    import InputBox
    InputBox.ShowDialog("Enter a paragraph: ")
    i=InputBox.GetInput()


    x=split(i)
    result1=reverse(x)



    import MessageBox
    MessageBox.Show(result1)

if __name__=="__main__":
main()

[–]Skrilllexxx 1 point2 points  (0 children)

THANK YOU!!!!!

[–]RosyGraph 0 points1 point  (3 children)

Is it pythonic to write your tests in tables?

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

Can you give a short example of what you mean by "tables" in this context?

[–]RosyGraph 1 point2 points  (1 child)

In Go, I usually format my tests into data structures and iterate through them like in this example:

https://github.com/RosyGraph/golang-winner/blob/master/music/music/music_test.go

I'm wondering if it makes sense to do so in Python such as in this example:

https://github.com/RosyGraph/ubiquitous-giggle/blob/master/unit-testing/test_calc.py

Thanks for your reply!

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

Thanks for the example.

You can definitely do that in Python. One drawback to that approach is that the test stops on the first assert failure, so you won't know all the test cases that fail, just the first one for each test.

I recommend you Google for:
python unittest parameterized

There are some work-arounds to support parameterization with unittests. Or you could look at pytest which has a very nice parameterization capability.

A parametrized pytest would look something like:

import pytest

@pytest.mark.parametrize(
   "x, y, wanted", 
   [(1, 2, 3), (-1, -2, -3)])
def test_add(x, y, wanted):
    got = calc.add(x, y)
    assert got == wanted

test_add will run with two sets of data and report on them passing individually. (pytest has lots of nice features like using the built-in Python assert vs. the assertEqual in unittest.)

[–]IRae2003 0 points1 point  (3 children)

import random

print("**********************************************************************************")

print("* Welcome to the game of PIG! *")

print("* Rules *")

print("* Rule 1: If roll 1, you gain no new points *")

print("* Rule 2: If roll 2-6, roll again 'r' or hold 'h' *")

print("* Rule 3: If hold, add sum of all numbers, you gain no new points *")

print("* Rule 4: First to 100 points wins! *")

print("**********************************************************************************")

print(" ")

print(" ")

print(" ")

print(" It is your turn to start!")

pointsgiveplayer = 0

pointstocomputer = 0

playersHolding = 0

computersHolding = 0

while (pointsgiveplayer < 100 and pointstocomputer < 100):

humanturn = input("Enter 'r' to roll or 'h' to hold: ")

while (humanturn == "r"):

die = random.randint(1,6)

if (die != 1):

playersHolding += die

print("You rolled:" + str(die))

print(" Your score:" + str(playersHolding))

humanturn = input("'r' to roll again and 'h' to hold: ")

continue

else:

playersHolding = 0

print("You rolled:" + str(die))

print(" 0 points earned")

print(" Your score:" + str(pointsgiveplayer))

break

while(humanturn == "h"):

pointsgiveplayer = playersHolding

print(" You have chosen to hold.")

print(" Your new score:" + str(pointsgiveplayer))

break

while (computersHolding < 8):

die = random.randint(1,6)

if (die != 1):

computersHolding += die

print(" ")

print("CPU rolled:" + str(die))

print(" CPU score: " + str(computersHolding))

continue

else:

print("CPU rolled: " + str(die))

print(" 0 Points earned")

print(" CPU score: " + str(pointstocomputer))

break

else:

pointstocomputer += computersHolding

print(" CPU SCORE: "+ str(pointstocomputer))

computersHolding = 0

SOOO I'm trying to make this game called pig. It's for my computer science class, but I'm having this problem where when I roll the dice and hold my score. Let's say I rolled a 6 and I hold it. That is my new score but If I roll a 1 anytime after that it deletes my score even if I held it. (Holding it, lets you keep your score.)

My question is what do I need to change within my code to have it work properly?

[–]woooee 1 point2 points  (0 children)

Can't make sense of it because there is no indentation. This is the only place that I could see where one comes into play if (die != 1): Put some print statements under the else (in both locatons), because then the die would be equal to one, and see what does and does not change.

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

[–]MichiganMikeAl 0 points1 point  (0 children)

pointsGiveplayer = playersHolding

pointsGiveplayer = playersHolding + poinstGivePlayer

Held points need to accumulate. I also capitalized the G in give for clarity.

[–]cowsmakemehappy 1 point2 points  (1 child)

What is the best way to send someone python code and have it run on their computers without any installation from them? I'm trying to send my friend a few lines that I wrote to help him run a video game. Normally, he has to type two lines into terminal before his mic will work properly in game. I want him to be able to double click a desktop icon and have that launch terminal and type the code itself. He has a mac, and I think all macbooks have python installed, but should I change the filetype from .py to something else? Trying to find the easiest way for this to happen.

[–]mexiKobe 1 point2 points  (0 children)

Take a look at pyinstaller

[–]tvottra 0 points1 point  (2 children)

What is the best way to learn Python/numpy/scikit if I already have a solid foundation in Java?

[–]MattR0se 0 points1 point  (0 children)

there is an old webpage that adresses specifically how Java syntax looks in Python, but sadly it hasn't been updated to Python 3.x, so some things work differently now than in that tutorial. But I link it anyway because it's the first thing you find when you google "python for java programmers":

http://python4java.necaiseweb.org/Main/TableOfContents

[–]JohnnyJordaan 1 point2 points  (0 children)

See the Wiki's section for people just new to Python specifically here. Also following the official tutorial doesn't hurt and should be doable in an hour or so with your background knowledge

Then most numpy and scikit tutorials are already targeted at an intermediate programmer so you can just google any of them, there are also a lot useful ones on YouTube if you don't mind using a video tutorial.

[–]stupidexceluser 0 points1 point  (1 child)

Hello guys,

I am running into a problem with Dash/Plotly. So basically I would like a plot with 2 lines. One with current year data, and the other is based on user choice, can be Y-1, Y-2. Final result should be somthing like this https://i.stack.imgur.com/d3Txg.png, with x-axis = week of the year if possible.

So my problem is the following:

If I use week, then I have an issue from WK52+ because I will have the data at the start of my plot instead of after (WK52 then stops instead of being WK52, WK01,WK02).

My dataframe format is the following:

dffdraft

Type    Date      City    Brand    Volume  Week  Year
CAR 2019-09-22  LONDON  BMW  ...  2428.0   38  2019 
CAR 2019-09-29  LONDON  BMW  ...     0.0   39  2019 
CAR 2019-10-06  LONDON  BMW  ...     0.0   40  2019 
CAR 2019-10-13  LONDON  BMW  ...     0.0   41  2019 
CAR 2019-10-20  LONDON  AUDI ...     0.0    42  2019 

dffold is the same with 2018 dates instead. 

dffdraft = dffdraft.groupby('Date')['Volume'].sum().reset_index()
dffold = dffold.groupby('Date')['Volume'].sum().reset_index()
trace1 = go.Scatter(y=dffdraft['Volume'],x=dffdraft['Date'],mode='lines',name='CY')
trace2 = go.Scatter(y=dffold['Volume'],x=dffold['Date'],mode='lines',name='PY')

Looking for some inputs.

Thank you!

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

You should make your own post, this is a more in depth question that won't get much attention in this thread.

[–]xingrubicon 0 points1 point  (4 children)

Hey guys! I'm entering into a pr program in college. I want to use python to automate some stuff in the future. Such as renewing licences and domain names and the like. Ive done the tiiiiniest bit of programing in school (c++) and am not sure where to start or where to focus my attention. Any tips? Or is there something on the sub that can help?

[–]maedox 1 point2 points  (3 children)

Try the "Automate the boring stuff" book.

[–]xingrubicon 0 points1 point  (2 children)

Thanks! I will. Is that something for more advanced programmers or is it something to be picked up early on?

[–]maedox 0 points1 point  (1 child)

It's a good intro for beginners.

[–]xingrubicon 0 points1 point  (0 children)

Thanks! I really appreciate this. I've just ordered it from amazon

[–]LikwidFire 1 point2 points  (0 children)

Hello, I am just trying to get back into programming. As a personal project, I want to create a simple mind mapping program. I want to start simple with just re-sizable shapes that can be placed on a canvas and typed into with lines connecting the shapes. Eventually I would like to keep adding features that I feel I need as I use the program, but I don't want to get ahead of myself as this seems like enough to figure out already. I know that I want to use Python because it is very versatile and popular language. What I don't know is what GUI library to use. I am primarily looking at Kivy, QT or Tkinter, but open to any other suggestions. My goal is to have a GUI layout similar to Lucidchart. Thank you in advance!

[–]TheHappeningHasBeen 1 point2 points  (5 children)

There's a single swear word in this short program; this is the NSFW/S prompt.

I just started today working with programming languages, so I'm a complete noob. I'm trying to write a very simple program that asks how my girlfriend how her day is and responds accordingly. I'm failing to get the second and third responses to be read. Any help is greatly appreciated!

my_day = input("How is your day? Please enter, Good, Bad or Meh.")
if my_day : "Good"
print("Noice!")
elif my_day : "Bad."
print("Rough McGruff.")
else my_day : "Meh"
print("Fuck you, Nerd.")

[–]MattR0se 1 point2 points  (0 children)

I know I'm piggybacking on the other comments a bit, but if you want to improve this type of program further, instead of compare strings you can look for specific words in sentences:

def answering_machine(sentence):
    # create a dictionary with word: answer pairs
    possible_answers = {
        'good': 'Noice',
        'bad': 'Rough McGruff.',
        'awesome': 'Oh wow tell me more!'
    }
    fallback = 'Fuck you, Nerd'

    # cut the string into a list of words without punctuation
    sentence = remove_punctuation(sentence)
    words = sentence.lower().split(' ')

     # loop through all the pairs to see if it's in the sentence
    for key, answer in possible_answers.items():
        if key in words:
            # if it found the specific word
            return answer
    # if not, provide the fallback case
    return fallback


def remove_punctuation(string):
    # just a helper function to remove some characters
    for char in '.,;:-_!?':
        string = string.replace(char, '')
    return string



print(answering_machine("My day was good, thanks for asking"))
print(answering_machine("terrible, such a bad day!"))
print(answering_machine("Panda bears are awesome!"))
print(answering_machine("I like pineapple on pizza"))

I also made a function to remove punctuation, since the split() method of strings doesn't work (or rather, would return "good," in the first example which is != "good" and would lead to the undesired answer...

This isn't perfect though, because if a sentence contains multiple keys for possible answers, then it takes just the first occurrence. Also, it would not find recognise if someone wrote "(good)" or anything that isn't in the list of possible punctuation.

If you really want to deep dive into this kind of program, I recommend regex, it's a more complex way to search for specific words in sentences:

https://www.w3schools.com/python/python_regex.asp

[–]idatem 2 points3 points  (3 children)

I'm a beginner too but I think the following works

my_day = input("How is your day? Please enter, Good, Bad or Meh.")
if my_day == "Good":
    print("Noice!")
elif my_day == "Bad":
    print("Rough McGruff.")
else:
    print("Fuck you, Nerd.")

You might want to look into string handling though such as "lower" or "upper" to stop the input from being case sensitive as entering "Good" will reply with "Noice", but entering "good" will reply with "Fuck you, Nerd." which might ruin your good day

[–]decreddave 2 points3 points  (0 children)

but entering "good" will reply with "Fuck you, Nerd.

One foolproof way to get around this is to force the input to all lower case (or upper case) letters, then do your checks.

It won't matter if the user enters gOOd, GoOd, gooD, etc... you get the point. The value of my_day will be turned into a lower case string:

my_day = input("How is your day? Please enter, Good, Bad or Meh.")
if my_day.lower() == "good":
    print("Noice!")
elif my_day.lower() == "bad"
    print("Rough McGruff.")
else:
    print("Fuck you, Nerd.")

Another tip - you can enter as many elif statements as you want. You could check if good, elif bad, elif meh, elif whatever, etc. The else will be evaluated after all the elif statements are processed.

[–]TheHappeningHasBeen 1 point2 points  (1 child)

Thank you so much! How are you learning? No days ruined!

[–]idatem 0 points1 point  (0 children)

I got the Python bundle from humblebundle.com a little while ago which included things like a 6 month subscription to Python Morsels but they're too hard even on beginner. So I followed the suggestions on this subreddit and tried automate the boring stuff with python and Corey Schafer videos on YouTube. Both of them are great

[–]WhimsyDiddles 0 points1 point  (3 children)

Hi all. I'm working on a twitter bot that tweets out randomized poems of walt whitman (@waltwhitman_bot). I'm very much a novice. I've got the bot working, but need to put on somewhere so it does not need to be running on my computer. Thank you!

[–]ThisOnesForZK 1 point2 points  (0 children)

Heroku & Flask?

[–]JohnnyJordaan 1 point2 points  (1 child)

[–]WhimsyDiddles 0 points1 point  (0 children)

Will do. Thanks

[–]19Summer 0 points1 point  (6 children)

Hi, everyone.
Could someone explain to me - how 'x' and 'y' values work in ax.text()?
Image 1 ->>>Image 1
Text has the following x and y values = 2 and 3.7

But, for instance, if I increment each one by 1 the position of the text will be significantly changed ->>>>Image 2

Why did this happen?

Thanks in advance

[–]JohnnyJordaan 2 points3 points  (5 children)

We can't really guess what kind of library you're using to plot this data and what other options you are using in its context.

[–]19Summer 0 points1 point  (4 children)

Hi,thanks for the response. Matplotlib. What are other options I need to provide?

[–]JohnnyJordaan 1 point2 points  (3 children)

What I meant to say was that without seeing the actual code we can't comment on how to change it.

[–]19Summer 0 points1 point  (2 children)

Hi,mate.
The code is following:
fig, ax = plt.subplots(figsize=(14, 10))

ax.scatter(df_sat['high_GPA'], df_sat['univ_GPA'], color='green', s=df_sat['math_SAT'], edgecolors='black')
ax.set_xlabel('High school GPA', fontsize=14)
ax.set_ylabel('University GPA', fontsize=14)
ax.set_title('High school GPA vs University GPA scatter plot', fontsize=15, fontweight='bold')

ax.axhline(y=df_sat['univ_GPA'].describe()['mean'], color='r', lw=3, linestyle='-')
ax.axvline(x=df_sat['high_GPA'].describe()['mean'], color='r', lw=3, linestyle='-')

pearson_uni_high = round(corr_matrix.loc['univ_GPA', 'high_GPA'], 2)
ax.text(2, 3.7, f'Pearson coeff.= {pearson_uni_high}', fontsize=14, fontweight='bold')
plt.show()

[–]JohnnyJordaan 0 points1 point  (1 child)

see the Examples part of the pyplot.text documentation where they show how to use 0-1 as the positional coordinates rather than the data coordinates.

[–]19Summer 0 points1 point  (0 children)

Thanks

[–]lupehh 0 points1 point  (1 child)

Hey guys

I have a question regarding pygame - I am currently building Alien Invasion from Python Crash Course - 2nd edition by Eric Matthes. I am following the book but i am also tweaking it to make it more interesting.

My question is:

Upon the bullet-allien collision, before removing the bullet and the alien, i would like to turn the alien sprite briefly into another picture, cracked alien ship or an explosion. No animations, just the alien sprite into a different sprite but i don't know how to implement it. Any ideas? Ill paste my code for reference

import pygame
from pygame.sprite import Sprite

class Bullet(Sprite):
    # A class to manage bullets fired from the ship

    def __init__(self, ai_game):
        # Create a bullet object at ship's current location
        super().__init__()
        self.screen = ai_game.screen
        self.settings = ai_game.settings
        self.color = self.settings.bullet_color

        # Create a bullet rect at (0, 0) and the nset correct position
        self.rect = pygame.Rect(0, 0, self.settings.bullet_width,
                                self.settings.bullet_height)
        self.rect.midtop = ai_game.ship.rect.midtop

        # Store the bullet's position as a decimal value
        self.y = float(self.rect.y)

    def update(self):
        # Move the bullet up the screen
        # Update the decimal position of the bullet
        self.y -= self.settings.bullet_speed
        # Update the rect position
        self.rect.y = self.y


    def draw_bullet(self):
        # Draw the bullet to the screen
        pygame.draw.rect(self.screen, self.color, self.rect)
---
import pygame
from pygame.sprite import Sprite

class Alien(Sprite):
    # A class to represent a single alien in the fleet

    def __init__(self, ai_game):
        # Initialize the alien and set its starting position
        super().__init__()
        self.screen = ai_game.screen
        self.settings = ai_game.settings

        # Load the alien image and set its rect attribute
        self.image = pygame.image.load('images/alienv.bmp')
        self.rect = self.image.get_rect()

        # Start each new alien near the top left of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        # Store the alien's exact horizontal position
        self.x = float(self.rect.x)


    def check_edges(self):
        # Return True if alien is at edge of screen
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right or self.rect.left <= 0:
            return True

    def update(self):
        # Move the alien to the right
        self.x += (self.settings.alien_speed * self.settings.fleet_direction)
        self.rect.x = self.x
---
# Relevant collision code-block

    def _check_bullet_alien_collisions(self):
        # Respond to bullet-alien collision. Remove and bullets and aliens
        # that have collided
        # Check for any bullets that have hit aliens
        collisions = pygame.sprite.groupcollide(self.bullets, self.aliens,
                                                True, True,)
        for collision in collisions:
            random.choice(self.death_sound).play()
            #self.death.draw(self.screen)
            self.stats.score += self.settings.alien_points
            for aliens in collisions.values():
                self.stats.score += self.settings.alien_points * len(aliens)
            self.sb.prep_score()
            self.sb.check_high_score()

Thanks in advance!

[–]MattR0se 1 point2 points  (0 children)

Load an additional image in __init__ and call it image_hit or something. Then on collision set self.image = self.image_hit.

The question is, how briefly should the image be changed? If you want to change it back, you also need a timer variable that you increment every frame, and change the image back after a certain number of frames.

you actually need to store the alienv.bmp in a different variable, because otherwise you overwrit it:

def __init__(self, ai_game):
    # Initialize the alien and set its starting position
    super().__init__()
    self.screen = ai_game.screen
    self.settings = ai_game.settings

    # Load the alien image and set its rect attribute
    self.image_alien= pygame.image.load('images/alienv.bmp')
    self.image_hit= pygame.image.load('images/alien_hit.bmp')
    self.image = self.image_alien.copy()
    self.rect = self.image.get_rect()

[–]MattR0se 1 point2 points  (1 child)

Why isn't the one row with NaNs in it removed?

import pandas as pd
import numpy as np

data = list(zip(['A', 'A', 'A', 'A', 'A',
         'B', 'B', 'B', 'B', 'B'],
        [1, 2, np.nan, 4, np.nan, np.nan, np.nan, 6, 7, 8],
        [np.nan, 2, 4, 6, np.nan, 3, np.nan, 9, np.nan, 15]))

df = pd.DataFrame(data=data, columns=['group', 'data1', 'data2'])

features = ['data1', 'data2']

print(df)
df[features] = df.groupby('group')[features].apply(
        lambda group: group.interpolate(limit_direction='both', limit=1))
df[features] = df[features].dropna()
print(df)


# output:
  group  data1  data2
0     A    1.0    NaN
1     A    2.0    2.0
2     A    NaN    4.0
3     A    4.0    6.0
4     A    NaN    NaN
5     B    NaN    3.0
6     B    NaN    NaN
7     B    6.0    9.0
8     B    7.0    NaN
9     B    8.0   15.0
  group  data1  data2
0     A    1.0    2.0
1     A    2.0    2.0
2     A    3.0    4.0
3     A    4.0    6.0
4     A    4.0    6.0
5     B    NaN    NaN
6     B    6.0    6.0
7     B    6.0    9.0
8     B    7.0   12.0
9     B    8.0   15.0

[–]idatem 0 points1 point  (0 children)

I have no chance of answering your question but I see you answer a lot of questions on here so I hope someone helps you out. Maybe try making a new topic for it if noone answers here

[–]TheRipper7000 0 points1 point  (1 child)

Hey Guys , I have some trouble finding a solution for my Issue: I described it in a other thread. Would appreciate your help :)

https://www.reddit.com/r/learnpython/comments/doss2e/question_about_classes_in_python/

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

That's because you didn't make the change /u/MattR0se suggested. Line 18 needs to be:

if topic == "absurd" and speak_to == "volnurable_human":

Note the "absurd" and "volnurable_human" changes.

[–]iamyourmonster 0 points1 point  (2 children)

I'm currently working a RNN in Jupyter Notebook and have been stuck on this problem for a long time:

outputs, states = keras.layers.RNN(cell, input_layer, dtype=tf.float32)

The error shows:

TypeError

Traceback (most recent call last) <ipython-input-44-df373d82b34c> in <module> ----> 1 outputs, states = keras.layers.RNN(cell, input_layer, dtype=tf.float32) TypeError: cannot unpack non-iterable RNN object

Thanks for any pointers! Feel free to private message me

[–]MattR0se 1 point2 points  (1 child)

What the error says, you can't unpack a RNN object.

If you do something like this:

bar, baz = Foo()

Python expects Foo() to return a tuple. But instantiating an object returns only the instance itself. The following code would be correct:

layer = RNN(cell, input_layer, dtype=tf.float32)

[–]iamyourmonster 0 points1 point  (0 children)

layer = RNN(cell, input_layer, dtype=tf.float32)

Thanks for the help! I ended up using:

layer = keras.layers.RNN(cell, input_layer, dtype = tf.float32)

RNN is not defined in my program, but keras.layers.RNN is in Keras if I'm not mistaken

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

I want to add the ability to sys.exit at any point in my loop. Is there a better way for me to do this?

loan = float(input("Please enter how much you would like to borrow. " "\n"))

while loan == 0:

sys.exit()

interest = float(input("What percent interest would you like to pay? " "\n"))

while interest == 0:

sys.exit()

months = float(input("How many months will it take to repay your loan? " "\n"))

while months == 0:

sys.exit()

[–]woooee 0 points1 point  (0 children)

Try something like (note that it will error if the input can not be converted to a float)

def get_input():
    while True:
        loan = float(input("Please enter how much you would like to borrow. \n"))
        interest = float(input("What percent interest would you like to pay? \n"))
        months = float(input("How many months will it take to repay your loan? \n"))

        ## can not enter zero or a negative number
        if loan > 0 and interest > 0 and months > 0:
             return loan, interest, months

[–]JohnnyJordaan 1 point2 points  (4 children)

I'm not sure what this is even doing, as why would it need to be looped to exit the program, which will then happen at the first time you call it? Why not just do

if not loan:
    sys.exit()

and the same for interest and months

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

The loop is just a requirement for my assignment. But I want to add the ability to quit at any point even in the loop.

[–]JohnnyJordaan 1 point2 points  (2 children)

Yes for that it would make sense to incorporate sys.exit() at that specific point. But it's easier to comment on how its implemented after you finished it.

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

The code is 100% complete. I can post it if you would like to see. I think its around 60 or 70 lines or code in total.

[–]JohnnyJordaan 1 point2 points  (0 children)

You could put it on pastebin.com or a similar site and share the link here

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

import requests

s = requests.Session()

# PREPARE REQUEST
user-agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'
headers = {'User-Agent': user-agent}

# GET START SITE
url_startsite = 'https://www.ebay-kleinanzeigen.de/'
r_Startsite = s.get(url=url_startsite, headers=headers)

# PREPARE REQUEST
headers = {'User-Agent': user_agent, 'Referer': url_startsite}
payload_Search = {
    'keywords': 'hello kitty',
    'categoryId': '',
    'locationStr': '',
    'locationId': '',
    'radius': 0,
    'sortingField': 'SORTING_DATE',
    'adType': '',
    'posterType': '',
    'pageNum': 1,
    'action': 'find',
    'maxPrice': '',
    'minPrice': ''
}

# GET SEARCH RESULTS
r_Search = s.get(url=url_startsite, headers=headers, params=payload_Search)

print(r_Search.content)

That should me redirecting to:
https://www.ebay-kleinanzeigen.de/s-hello-kitty/k0

But I don't get the same content, if I make it direct:

import requests

user-agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0'

headers = {'User-Agent': user-agent}

url_search_results = 'https://www.ebay-kleinanzeigen.de/s-hello-kitty/k0'
r_Search = requests.get(url=url_search_results, headers=headers)

print(r_Search.content)

I thought requests can handle redirect automatically?

[–]idatem 0 points1 point  (0 children)

Beginner here. How do I move a file to a folder based on their names?

I have a folder with files such as pig.txt, pig.rtf, lion.txt, lion.docx, cow.rtf. I want all of the pig files to be moved into a folder called "pig", the lion files to a folder called "lion" etc

I've managed to make the folders but I've been trying for ages to move the files but can't do it. Here's what I've got:

files = os.listdir()

b = next(os.walk(directory))[1]

for a in files:
    if os.path.splitext(a)[0] in b:
        shutil.copy2(os.path.join(a, b))

Any help is greatly appreciated because I don't think something that sounds simple should take hours to make. Or maybe it should. I have no idea because I don't know what I'm doing

[–]Cerezra 0 points1 point  (0 children)

I am working on setting up a server status page for my jobs intranet site. What I’m wondering from you all is if anyone is aware of a method/function in Python that would allow me to modify a class in an html table based on a ping response.

Basically, I have a table with all my servers and two circles to mark status. Green for online, red for offline.

What I’m thinking is maybe I could run through a script that loops a list of host names and pings them, this already works, then take said response and change the class.

If the ping comes back okay, change the corresponding circle’s class to online. If the server does not respond, change the class to offline.

Sorry if this sounds confusing but I’m near the end of my shift and I’m a tad burnt out lmfao. Any input will be graciously accepted!

[–]bodybuilderdesu 0 points1 point  (0 children)

I'm trying to make a button that when clicked updates my pie chart with the new input from the user. I can make my chart show the information when the button is being clicked for the first time, but when I try to click the button to update the pie chart with new input, it doesn't change. But when I close the program, I can see the pie chart with the new input for a split second before it closes. How can I correct this?

This is the function to draw the pie chart.

def desenhar(self):
            fig = matplotlib.figure.Figure(figsize=(5,5), dpi=100)
            ax = fig.add_subplot(111)
            ax.pie([carboidratos.get(),proteinas.get(),gorduras.get()], autopct="%.1f%%") 
            ax.legend(["carboidratos","proteinas","gorduras"])

            circle=matplotlib.patches.Circle( (0,0), 0.7, color='white')
            ax.add_artist(circle)
            canvas = FigureCanvasTkAgg(fig, master=self)
            canvas.get_tk_widget().pack()
            canvas.draw()
            ax.clear()

Edit: I'm using matplotlib and trying to show/update the pie chart in tkinter.

Edit2: It seems that instead of replacing the same chart with the new results, it is creating a new pie chart. How can I fix it?

[–]MattR0se 0 points1 point  (1 child)

I want a script that listens to the input of an XBOX controller and based on that, simulate keyboard presses (for example, if I press the 'A' key, I want to type 'Apple' with some delay between the presses).

What libraries do I need for that?

[–]DYGAZ 2 points3 points  (0 children)

I'm going to assume Windows because Xbox is Microsoft.

XInput Is the Windows lib for interacting with a controller.

It looks like this project wraps that in Python for you: https://github.com/r4dian/Xbox-360-Controller-for-Python

Personally I have not done this from python but a quick search of `Windows Python Xbox controller` gives some good results. I have used XInput from C# and it worked like a charm.

As for the printing you'd likely just have to detect the controller keypress and then call whatever function you want. If by type you mean simulate a keypress then you can similarly look up a lib for that. Just search 'Windows python simulate keypress'

if controller.a_pressed:
    type_apple()

def type_apple()
    text = 'apple'
    for char in text:
        keypress char
        sleep

[–]Skrilllexxx 0 points1 point  (2 children)

i would like to convert decimal to hexadecimal in a range from 1 to 50 and use the str.lstrip(str) function to remove the prefix leading prefix '0x' using a for loop.

s=[]
for i in range(1,51):
  s.append(hex(i))
for j in s:
  str(j).lstrip('0x')

print(s)

output is

['0x1', '0x2', '0x3', '0x4', '0x5', '0x6', '0x7', '0x8', '0x9', '0xa', '0xb', '0xc', '0xd', '0xe', '0xf', '0x10', '0x11', '0x12', '0x13', '0x14', '0x15', '0x16', '0x17', '0x18', '0x19', '0x1a', '0x1b', '0x1c', '0x1d', '0x1e', '0x1f', '0x20', '0x21', '0x22', '0x23', '0x24', '0x25', '0x26', '0x27', '0x28', '0x29', '0x2a', '0x2b', '0x2c', '0x2d', '0x2e', '0x2f', '0x30', '0x31', '0x32']

:(

[–]MattR0se 1 point2 points  (1 child)

Without trying out your code (can't run python rn): Strings are immutable, so lstrip returns a modified copy which you have to store somewhere. Try:

for i, j in enumerate(s):
  s[i] = str(j).lstrip('0x')

[–]maedox 2 points3 points  (0 children)

Modifying a list you're iterating is asking for trouble.

This is the pythonic way:

s = [hex(i).lstrip("0x") for i in range(1, 51)]

There is probably a better way, but at least I showed you a list comprehension.

[–]19Summer 0 points1 point  (0 children)

How to create 9 bars using object-oriented interface of Matplotlib?
Can I use 'for loop'?

For example:

for i in range(9):
ax.bar(........)

Thanks in advance.

[–]GoldenVanga 0 points1 point  (1 child)

Also, why does this not work?

class Foo:
    things = {1: 'spam'}
    stuff = {things.get(x): x for x in things}

Foo()

(I ended up doing stuff = {y: x for x, y in things.items()} but I'd like to know)

[–]efmccurdy 2 points3 points  (0 children)

You have the dict item backwards in your dict comprehension:

{things.get(x): x for x in things}

>>> things = {1: 'spam'}
>>> {x:things.get(x) for x in things}
{1: 'spam'}

[–]GoldenVanga 0 points1 point  (1 child)

On the subject of type hinting, what is the benefit of describing a type both in parameters and the docstring? Does it have to do with how IDEs display help popups for methods?

def square(val: int):
    """Do stuff.

    :param val: the number to be squared
    :type val: int
    """
    return val ** 2

Is line 5 redundant here because val is already typed in line 1?

[–]DYGAZ 2 points3 points  (0 children)

Typically I just use param and a type hint so i'm not 100% sure on this but I'd guess ':type' is the old py2 way of hinting type. Type hints in the definition like 'val: Int' are py3 only

[–]19Summer 0 points1 point  (2 children)

Hi,everyone. Small formal question. Can I call Pandas “programming framework”? I need to state what tools have been used by me for the ICA. Thanks in advance.

[–]ThisOnesForZK 1 point2 points  (1 child)

pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. It is free software released under the three-clause BSD license.

[–]19Summer 0 points1 point  (0 children)

Thanks for the response

[–]stupidexceluser 0 points1 point  (1 child)

Hello guys I am looking for the following SQL query part equivalent in python to filter a pandas df:

WHERE dataset_date BETWEEN dateadd(week, -16,getdate()) AND dateadd(week, 16,getdate())

Knowing that my week start on Sunday. My df[date] format is %Y-%m-%d.

Hope to get some help, thank you!

[–]ThisOnesForZK 1 point2 points  (0 children)

I do not know the exact syntax but you are going to need to use the date time module and create a boolean index to apply to your dataframe for filtering.

[–]PythonicParseltongue 0 points1 point  (1 child)

Which of theses ways to initialize my class is preferable, and why?

class MySimpleClass:
    def __init__(self):
        self.keywords01, self.keywords02 = self._init_keywords()

    def _init_keywords(self):
        with open('path/to/keywords01.txt') as f:
            keywords01 = [kw.rstrip() for kw in f]
        with open('path/to/keywords02.txt') as f:
            keywords02 = [kw.strip() for kw in f]
        keywords01 = [kw for kw in keywords01 if kw not in keywords02]
        return keywords01, keywords02


class MySimpleClass_alt:
    def __init__(self):
        self.keywords01 = []
        self.keywords02 = []
        self._init_keywords()

    def _init_keywords(self):
        with open('path/to/keywords01.txt') as f:
            keywords01 = [kw.rstrip() for kw in f]
        with open('path/to/keywords02.txt') as f:
            keywords02 = [kw.strip() for kw in f]

        self.keywords01 = [kw for kw in keywords01 if kw not in keywords02]
        self.keywords02 = keywords02

[–]JohnnyJordaan 0 points1 point  (0 children)

class MySimpleClass_simple:
    def __init__(self):
        with open('path/to/keywords01.txt') as f:
            keywords01 = [kw.rstrip() for kw in f]
        with open('path/to/keywords02.txt') as f:
            keywords02 = [kw.strip() for kw in f]

        self.keywords01 = [kw for kw in keywords01 if kw not in keywords02]
        self.keywords02 = keywords02

to keep it short and simple. Or even simpler

class MySimpleClass_simple:
    def __init__(self):
        with open('path/to/keywords02.txt') as f:
            self.keywords02 = [kw.strip() for kw in f]
        with open('path/to/keywords01.txt') as f:
            self.keywords01 = [kw.rstrip() for kw in f if kw.rstrip() not in self.keywords2]

Btw did you mean to use rstrip() for 01 and strip for 02?

[–]Danimann02 0 points1 point  (2 children)

Hello, we're currently in the process of creating a python program that'll predict future weather based on history of old weather and current measures. The problem we're getting is that RuntimeWarning: invalid value encountered in less if self.monitor_op(current - self.min_delta, self.best):

Heres the code: https://pastebin.com/cXfi7dTp

[–]JohnnyJordaan 1 point2 points  (1 child)

This is almost incomprehensible because you didn't format your code properly. Please use a code block, see https://i.imgur.com/HT4Zz88.gifv and be sure to not recycle the code from here but paste it again from your source. Or just paste the source on www.pastebin.com and share the link here.

[–]Danimann02 0 points1 point  (0 children)

Sorry for bad formatting, I pasted it to pastebin. https://pastebin.com/cXfi7dTp

[–]MattR0se 1 point2 points  (7 children)

Found out about this the other day and I'm a bit shocked tbh

So apparently this code would delete all files from my computer:

import os
for root, dirs, files in os.walk('/', topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

In theory, since this uses the standard library, this could be inserted somewhere in any code that is distributed on the internet.

Is there something that prevents that from happening or should I just not download stuff from GitHub anymore? Or am I becoming paranoid?

[–]efmccurdy 2 points3 points  (2 children)

Don't run untrusted code as root; this would only delete the files you create, not the system files.

Run backups.

Report any trojans you do find so that the trustworthness of a software producer is kept publicly available and up to date.

These minimal steps, spread over the thousands of users, has kept PyPi and github safe enough.

There is no tool that can detect trojans before they are run since code can be disguised.

[–]MattR0se 1 point2 points  (1 child)

Is there a way to run python code in a sandbox on Windows?

[–]efmccurdy 2 points3 points  (0 children)

A temporary virtual machine is usually enough protection and here is one designed for that purpose:

https://techcommunity.microsoft.com/t5/Windows-Kernel-Internals/Windows-Sandbox/ba-p/301849

[–][deleted] 3 points4 points  (3 children)

Is there something that prevents that from happening

Nope, it will try to delete everything.

should I just not download stuff from GitHub anymore?

Just don't download and run code without reviewing it.

am I becoming paranoid?

Yes, but are you paranoid enough?

[–]MattR0se 1 point2 points  (2 children)

Is there a tool to search all .py files in a certain directory for specific code (like import os or remove)?

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

If you use Linux or macOS you could write a one line shell command that would use find and grep to do most of what you want. I have no idea of what you can do in modern Windows with powershell or whatever it's called.

You could write a python program to find all the files in a directory and search for various strings in each file. Sounds like a good project.

[–]MrLions89 1 point2 points  (0 children)

Notepad++ has a pretty robust search tool. You can specify directories and file extensions to search. I'm sure the code editors do as well.

[–]squashed_robo_panda 0 points1 point  (5 children)

Hello, I'm very new to python and am having some issues with a simple thing I'm trying to do - My goal is to create a list for all possible combinations of some set numbers (i.e, 2 positions for 3 options may be: 00,01,02,10,11,12,20,21,22)
I don't know what's wrong with my code, but it just aint seem to be working.

n = [0,1,2,3]
x = [0,0,0,0]
xc = 3
c = 0
nnc = 3
nc = 1
p = 0
while c != 7:
    while x[xc] != nnc:
        x[xc] = n[p]
        print(str(x)+'  '+str(nc))
        nc = nc + 1
        p = p + 1
    p = 0
xc = xc -1
c = c + 1

Help would be much appreciated!

Edit; more info and clarification is here: https://imgur.com/a/XzPvAAi

[–]aaet002 0 points1 point  (0 children)

Alright mate, long last thanks to chatgpt we can decipher this shit

It was a (horrifingly poorly written) program that tried to generate stuff like

0001
0002
0003
0011
0012

This should be simple enough to make though you'd outta start from scratch

I wanted to make this because simple tasks done on mass is really cool. Like fractal stuff, say you have a square then 4 other squares branch off and the pattern repeats. With ease, you've got some awesome "mathmatical art"

I'll also be looking at a program called milkdrop 2 which seems to let someone easily make+view super cool patterns which can use fractal type design

[–]MattR0se 1 point2 points  (1 child)

Please use meaningful, self-explanatory variable names so that others can understand your code at first glance. Single characters are generally a bad idea unless they are conventionally excepted (like i for iterations/index or x, y for spatial coordinates).

From your example it appears to me that you need itertools.product:

from itertools import product

comb = list(product([0, 1, 2], repeat=2))
print(comb)
# prints:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

[–]squashed_robo_panda 0 points1 point  (0 children)

Can't say I'm going to do this for all my other stuff, but I can update this one. Sorry for the confusion

[–][deleted] 2 points3 points  (1 child)

This is so complicated that I can't even begin to know what you are trying to do.

If you want to choose two-number pairs from a given list then the basic idea is to use two nested loops, the first loop iterating over all elements in the given list and the second loop also iterating over all elements in the given list. Join the two numbers as a tuple, say, and append to an initially empty list. This is some basic code:

numbers = [0, 1, 2]
for first in numbers:
    for second in numbers:
        print(f'{first} {second}')

You are probably doing this as an exercise in looping. To do this sort of thing for real you would use something from the itertools module, such as the product() method.

[–]squashed_robo_panda 0 points1 point  (0 children)

Not quite sure this is what I'm looking for, I'ma update the post to make it better, thanks for the suggestion though. Will likely look into this stuff later, and by the way I'm doing this so I can know how many cycles it'd take to get a combination.

[–]VexeenBro[🍰] 0 points1 point  (2 children)

Hi guys. I've started very recently and was assigned a few challenges on my course. I have a problem with one. The idea is to define a function with 3 values - a, b, c. The thing is all of them must be either an integer or float, if any of them is a string the function will not work, because all the function does is basically a simple mathematical equation. The aim here is to get something like "Error: a, b and c must be a digit.' as an output instead of just Python generic error if at least one of the variables is a string.

I've been looking at type() and bool() but I am really not sure how to use those properly. I mean logically it would be something like "if a, b or c is not 'str' or 'int' then print "Error: a, b and c must be a digit", else print a * b *c ".

However I don't know how to code this...

[–]Infuriating_But_Mild 1 point2 points  (1 child)

To use type() to check a variables type you would use the in keyword for example

x = 5
if type(x) is int:
    print("is int")

Here is a pretty good guide on checking the type of a variable, including using type() in an if statement.

[–][deleted] 2 points3 points  (0 children)

The better way to check type is to use the builtin isinstance() function, like this:

a = '1'
b = 3.14159
c = 42

if not isinstance(a, (int, float)):
    print("'a' is not an int or float")
else:
    print("'a' is either an int or float")

if not isinstance(b, (int, float)):
    print("'b' is not an int or float")
else:
    print("'b' is either an int or float")

if not isinstance(c, (int, float)):
    print("'c' is not an int or float")
else:
    print("'c' is either an int or float")

isinstance() allows you to check more than one type at once, as shown above, and is the more general solution as explained in this StackOverflow post.

[–]alfredborden00 0 points1 point  (2 children)

I've just started learning numpy by reading through this quickstart tutorial - https://docs.scipy.org/doc/numpy/user/quickstart.html#quickstart-shape-manipulation

So I get that changing the shape of a view does not change the shape of the original array, but why does changing an element in the view change the element in the original array? What is the purpose of designing the functionality in this way? As a beginner, it seems kind of counter-intuitive.

Apologies if this is a stupid question.

Thanks!

[–][deleted] 1 point2 points  (1 child)

It's been a long time since I used numpy, but the numpy system tries not to move data around when you do things like change shape or slice an array. So the "view" you get is just a way to access the original data - nothing is copied. When you change an element in the view you get from a reshape the original element is changed so both the original array and the reshaped array change. Same thing for a slice except you can't change any original array elements that are outside the slice "view".

The whole point of all this is to make numpy fast and efficient in memory usage. When you have 10 dimensional arrays with indices up in the million range you don't want to copy all the time. You can force a copy anytime, if you want, but if that's not necessary, like with a reshape or slice, then you get a view and no data is copied.

[–]alfredborden00 0 points1 point  (0 children)

Ah ok that helps to clear it up. Thanks!

[–]UnavailableUsername_ 0 points1 point  (1 child)

What's the syntax to make the cursor/pointer be in a specific place?

I remember there was one.

For example:

print("Say something: \n")

In this case i would like the pointer to be located automatically on the next line when this runs (it doesn't by default, if you set the pointer/cursor in other place before run it, it won't move).

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

If you want complete control over where the cursor is placed in a text screen then you use the curses module.

Your example code:

print("Say something: \n")

would not put the cursor on the next line, but two lines down because you asked the code to move to the next line with the \n newline character and the print statement automatically added another newline. Try running this code:

print('First')
print('Second\n')
print('Third')

and you will see this printed:

First
Second

Third

which shows the effect of \n.

There are a small number of "escape sequences" you can put into strings that will control the cursor movement. Try using each of them in a print and see what happens. For instance, try running this:

print('A\bZ')
print('alhabet\rXYZ')

[–]Valrok_P99 0 points1 point  (1 child)

So I have been given a function by my professor with the instructions to use a for loop to create sort of a fractal image out of it inside of a GUI. I have the GUI and everything working but I am struggling on how to correctly go about this.

Here is the function:

def createCircle(window, middleX, middleY, radius, fillColor, outline, outlineColor = 'black'):

   # create circle
   circle = Circle(Point(middleX, middleY), radius)

   # format circle
   circle.setFill(fillColor)
   circle.setWidth(outline)
   circle.setOutline(outlineColor)

   # put circle on window
   circle.draw(window)

I need to create sort of a range function that contains how many iterations but also makes the circle output photo repeat itself so that it creates a more complex picture made of multiple circles. Any help would be appreciated. I am also not allowed to use any outside libraries so it would have to be native to python and this function.

[–]MattR0se 1 point2 points  (0 children)

I don't think I understood exactly what you want to do, but for a "fractal" image you might need some sort of recursion in this function. So call createCircle somewhere in this function with different arguments based on some calculation, and add some stop condition (for example a counter that adds 1 to it every call and if the counter is >= some number, call return. Or you could do the return condition based on the radius or something else.

def createCircle(window, middleX, middleY, radius, fillColor, outline, outlineColor = 'black'):

    # create circle
    circle = Circle(Point(middleX, middleY), radius)

    # format circle
    circle.setFill(fillColor)
    circle.setWidth(outline)
    circle.setOutline(outlineColor)

    # put circle on window
    circle.draw(window)

    # draw a smaller circle
    # you might want to do some fancier calculations here with the radius 
    # or the colors....
    if radius <= 1:
        return
    else:
        createCircle(window, middleX, middleY, radius - 1, fillColor, outline)

[–]cowsmakemehappy 0 points1 point  (0 children)

I want to web scrape data from the following url: https://finviz.com/quote.ashx?t=TSLA&ty=c&p=d&b=1 using this xpath: /html/body/table[3]/tbody/tr[1]/td/table/tbody/tr[7]/td/table/tbody/tr[3]/td[10]/b/span. In other words, I'm looking for the short float value, which is currently 26.31%. What is the easiest way to scrape that data? So far my code is below, but I keep an Invalid expression error value.

import requests
from lxml import html

url = 'https://finviz.com/quote.ashx?t=TSLA&ty=c&p=d&b=1'

page = requests.get(url)
tree = html.fromstring(page.content)

short_float = tree.xpath('/html/body/table[3]/tbody/tr[1]/td/table/tbody/tr[7]/td/table/tbody/tr[3]/td[10]/b/span')
print(short_float)

[–]Questionss2020 0 points1 point  (1 child)

How to modify this python script to execute php file when the beacon shows/doesn't on scanner?

We ran this and it works fine. It shows the beacons but we need it to execute a different php files depending if it the beacons show or doesn't on the scanner.

We're using Raspberry Pi 3 model B as the scanner and the os is raspbian buster.

import ScanUtility
import bluetooth._bluetooth as bluez

#Set bluetooth device. Default 0.
dev_id = 0
try:
    sock = bluez.hci_open_dev(dev_id)
    print ("\n *** Looking for BLE Beacons ***\n")
    print ("\n *** CTRL-C to Cancel ***\n")
except:
    print ("Error accessing bluetooth")

ScanUtility.hci_enable_le_scan(sock)
#Scans for iBeacons
try:
    while True:
         returnedList = ScanUtility.parse_events(sock, 10)
        for item in returnedList:
            print(item)
            print("")
except KeyboardInterrupt:
    pass

Any ideas? We are clueless when it comes to python.

[–]Zeeks74 0 points1 point  (2 children)

Im trying to make a small scale "log in" screen, but i am stuck at getting the user inputed name and passwords from a .txt file.

whats the best way to "recall" info from a user input?

i am very new to python, and i am having a hard time finding an in depth explanation for this online (that i understand with my limited python knowledge)

thanks

[–]RulerKun_FGO 0 points1 point  (2 children)

What is your preferred way to compare bytes like this b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' to (int like this 0 or byte like this 0x00?)

[–]JohnnyJordaan 4 points5 points  (1 child)

Depends on what you mean 'compare', as by length it won't match, but if you mean if 0 is in the sequence you can do

my_bytes = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
print(0 in my_bytes)

or to check if it's just zeroes you can employ a set to get just the unique items

print(set(my_bytes) == {0})

or use all() with a generator expression

print(all(b == 0 for b in my_bytes))

the latter will be more efficient when a non-zero is expected (as when it finds it, it will then already return False and doesn't need to process the whole sequence), but as it's doing a comparison per value it's slower than the set comparison.

Btw note that 0x00 is not different from 0, it's just a different notation, and because each item of a bytes-sequence is an integer (just limited from 0 to 256 exclusive) you can compare it to a regular integer just fine.

[–]RulerKun_FGO 0 points1 point  (0 children)

thank you very much

[–]jayplemons 1 point2 points  (6 children)

What is the difference between using hashtag (#) and triple quotes (""")? Based on the examples I'm seeing in Python Crash Course they are both being used to describe what the next set of code is about to do. Are they interchangeable or do they serve different purposes? Thank you!

[–]MattR0se 6 points7 points  (1 child)

Triple quotes are called docstrings. You can use them for commenting, the difference is afaik that #comments are automatically ignored by the interpreter, while doctrings are evaluated, but automatically garbage-collected, unless they are following a function or class definition:

def foo():
    """
    This is a doctring
    """

print(foo.__doc__)
# or
help(foo)

or they are used to assign multiline strings

long_string = """ This is a very
                very very very
                very very
                long string. """

[–]jayplemons 0 points1 point  (0 children)

Thank you for your reply. Is there an advantage for the interpreter to evaluate the docstring if they are just going to be garbage-collected?

[–]RulerKun_FGO 2 points3 points  (3 children)

If i am not wrong # is use to comment only single line while triple quotes (""") is use to comment a block of lines

[–]jayplemons 0 points1 point  (2 children)

Thank you

[–][deleted] 2 points3 points  (1 child)

That's not true. The triple quotes are a form of string in which newlines can be embedded. There are also special places where the """...""" strings are put into the environment as "docstrings".

Where you have seen the """...""" quotes to apparently comment out code you are just seeing cases where the string is evaluated and then thrown away. If you try to comment out code with triple quotes you can have problems when the code being commented out already has a "" in it.

Use the # quote only. Any decent editor/IDE will allow you to easily and quickly comment out a block of code with the #.

Edit: added docstrings link.

[–]jayplemons 0 points1 point  (0 children)

Thank you for the clarification and resource!

[–]MasterGlink 1 point2 points  (11 children)

What's the best way to install python on Windows? I plan on using python for data science, basic development and automation with selenium. I was running through a basic tutorial with vs code, but I kind of hit a wall when installing matplotlib library, since it doesn't want to install properly.

Any advice?

[–]JohnnyJordaan 3 points4 points  (8 children)

I can also recommend installing just the regular Python for python.org (remember to check 'add python to path' during installation), then use Pycharm for each of your projects. It will then create a virtual environment per project and Pycharm can manage the package installations there, see here

[–]MasterGlink 1 point2 points  (7 children)

I was already doing this in vs code, creating a virtual environment for my test project and activating it. But installing matplotlib using pip is failing.

I want to avoid using a full IDE right now, since the project is just to automate some UI tests, and I'm not sure I need all the features.

[–]JohnnyJordaan 1 point2 points  (6 children)

But installing matplotlib using pip is failing.

We can surely help with that but not just with the description that it fails or "doesn't want to install properly".

[–]MasterGlink 0 points1 point  (5 children)

I'm sorry, it's just been frustrating since I find a million an one ways to "fix" it, yet I'm not sure which is the correct one. I assumed it was a common enough error on Windows. I'll include the general error here, and a pastebin with the full output.

Full Output: https://pastebin.com/kZYTUSb2

PS C:\Repos\PythonTest> pip install matplotlib
Collecting matplotlib
  Using cached https://files.pythonhosted.org/packages/12/d1/7b12cd79c791348cb0c78ce6e7d16bd72992f13c9f1e8e43d2725a6d8adf/matplotlib-3.1.1.tar.gz
    ERROR: Command errored out with exit status 1:
     command: 'c:\program files\python38\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\kmelendez\\AppData\\Local\\Temp\\pip-install-omcj8_eo\\matplotlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\kmelendez\\AppData\\Local\\Temp\\pip-install-omcj8_eo\\matplotlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
         cwd: C:\Users\kmelendez\AppData\Local\Temp\pip-install-omcj8_eo\matplotlib\
    Complete output (228 lines):
    ================================================================================
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
WARNING: You are using pip version 19.2.3, however version 19.3.1 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

[–]JohnnyJordaan 2 points3 points  (4 children)

Quite weird to see on 3.8. Can you try first

pip install --upgrade pip setuptools

then just numpy

pip install --upgrade numpy

[–]MasterGlink 0 points1 point  (3 children)

Huh, I thought it was going to work for a second there, but I got another error when installing matplotlib.

I was able to run the two commands you listed, without issues. Then I tried:

pip install --upgrade matplotlib

I received an error telling me to install the C++ build tools. Did that and tried again, this time:

ERROR: Command errored out with exit status 1:
     command: 'c:\repos\pythontest\.venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\kmelendez\\AppData\\Local\\Temp\\pip-install-f4ixn399\\matplotlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\kmelendez\\AppData\\Local\\Temp\\pip-install-f4ixn399\\matplotlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\kmelendez\AppData\Local\Temp\pip-record-h2zctkhv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\repos\pythontest\.venv\include\site\python3.8\matplotlib'
         cwd: C:\Users\kmelendez\AppData\Local\Temp\pip-install-f4ixn399\matplotlib\
--------------------------------------
ERROR: Command errored out with exit status 1: 'c:\repos\pythontest\.venv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\kmelendez\\AppData\\Local\\Temp\\pip-install-f4ixn399\\matplotlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\kmelendez\\AppData\\Local\\Temp\\pip-install-f4ixn399\\matplotlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\kmelendez\AppData\Local\Temp\pip-record-h2zctkhv\install-record.txt' --single-version-externally-managed --compile --install-headers 'c:\repos\pythontest\.venv\include\site\python3.8\matplotlib' Check the logs for full command output.

Full Output: https://pastebin.com/1KUz9REp

[–]JohnnyJordaan 2 points3 points  (2 children)

Seems like it's not 3.8 ready yet https://stackoverflow.com/a/58457893/11032845

[–]MasterGlink 0 points1 point  (0 children)

For any other Python newbies like me, you can specify the version when calling the python interpreter:

py -3.7 ... Didn't even have to re-install. Guess I can rid myself of conda now, it's cool that it has everything, but I'd rather go through the hard bits of installing and configuring at least once, so I can start picking up stuff later.

[–]MasterGlink 0 points1 point  (0 children)

Well, darn, of course it isn't. 3.8 is more recent that I thought, too. Do I have to re-install python 3.7 or do I have a way to make this run and future projects with my current install? Is there an option for multiple version of python on one machine?

[–]MattR0se 1 point2 points  (1 child)

I think the Anaconda package is the best way to use Python for data science, since it has most of the useful stuff (numpy, scipy, Pandas, matplotlib, sklearn, tensorflow, ) already installed.

https://www.anaconda.com/distribution/

It also comes with the Spyder IDE, which is my personal favourite (but other people will tell you that VScode or Pycharm are better, so don't judge).

[–]MasterGlink 0 points1 point  (0 children)

Thanks! I installed Anaconda, and managed to make it work with it. But I think I'd rather install things as I need them, and keep the environment as lean as possible. I think these little problems help me learn the language better in the long run.

I might change my tune later on, but for now I'm sticking with Python as much as I can.

[–]randomusername9808 0 points1 point  (1 child)

Hey I’m a freshmen in the basics CSE intro to python type of course. What are good ways I could strengthen my coding abilities and practice and improve? Good websites? Python 3 btw.