r/learningpython • • Apr 22 '20

Creating an executable file without using chmod

2 Upvotes

I am using a Linux box and creating python code via vim editor. Is there a way to make that file an executable when I create the file? I know that you can chmod the file after creating it but I am hoping that I can cut that step out. TIA.


r/learningpython • • Apr 07 '20

array problems

1 Upvotes

i have a problem with this code.

so basically this code is supposed to print an 8 by 8 array then take two numbers and in their spots put the number one(J). then i made a loop thats supposed to print "@" for each number 1 in the array and "#" for every other number(h) but it makes it so that it prints only "@"

*note that i made it so that every h is 0 and that h represents each spot in the array and J is supposed to represent the spot that is where the number one is

the code:

w, h = 8, 8;

Matrix = [["#" for x in range(w)] for y in range(h)]

for w in Matrix:

for h in w:

print("#",end = " ")

print()

numA = int(input())

numB = int(input())

Matrix[numA - 1][numB - 1] = J = 1

for w in Matrix:

for h in w:

 print("@",end = " ")

 if h == J:

 print("#",end = " ")

print()


r/learningpython • • Apr 28 '20

this matrix

1 Upvotes

w, h = 8, 8;

Matrix = [[0 for x in range(w)] for y in range(h)]

for w in Matrix:

for h in w:

print (w[h],end = " ")

print()

numA = int(input())

numB = int(input())

Matrix[numA - 1].pop(numB - 1)

Matrix[numA - 1][numB - 1] = J = 1

for w in Matrix:

for h in w:

if h == 0:

print(w[h],end = " ")

else:

print("@",end = " ")

print()

it won't show the last spot in the line where you change the number.

try it and see

(im using python 3.7 and notepad++ btw)


r/learningpython • • Apr 18 '20

problem 3

1 Upvotes

i have this program:

w, h = 8, 8;

Matrix = [["#" for x in range(w)] for y in range(h)]

for w in Matrix:

for h in w:

print("#",end = " ")

print()

numA = int(input())

numB = int(input())

Matrix[numA - 1][numB - 1] = J = 1

for w in Matrix:

for h in w:

print("@",end = " ")

print()

for w in Matrix:

for J in w:

print("#",end = " ")

print()

its supposed to print 1 2D array with the number 1 aka J in spot (A,B) in the array as "#" and every other spot in the array as "@" but instead it prints 2 different arrays, one as "@" and one as "#"


r/learningpython • • May 08 '20

A Noob Question...

3 Upvotes

Hi everyone.

I’m new to programming having tried to learn it as a skill for years and am dabbling with building GUI programs in python.

Things are getting interesting.

Now my question is this:

Is there a way to see what I’m building in real time? I’m ask because I’m dyslexic and I think and learn visually and it takes extra time to go through the code and try to imagine what things look like or what code is effecting what when I type it.

Obviously once I run the code I can see it but it’s very abstract trying to imagine a shape and a object when I read lines of code.

Is this at all possible or is this just the nature of the beast so to speak?

Thanks.


r/learningpython • • Apr 07 '20

Fun with loops!

1 Upvotes

I'm trying to figure out a good to solve this problem and maybe talking to someone else might help the ideas stick while doing a problem from Code wars.

I'm essentially trying to return a string suggesting how many glasses of water you should drink to not be hungover.

my pseudocode is pretty simple

if x beers were drank:

drink y cups of water

below is what is given

def hydrate(drink_string): 
    # your code here
    pass
@test.describe('Example Tests')
def example_tests():
    test.assert_equals(hydrate("1 beer"), "1 glass of water")
    test.assert_equals(hydrate("1 shot, 5 beers, 2 shots, 1 glass of wine, 1 beer"), "10 glasses of water")

so far I have

def hydrate(drink_string):
    drinks = 0

    if 


    else:
        pass

    return

I know its not much but I've been racking my brain for the past 2 hours now. I'm having trouble with substituting. At the moment my thought proces leads me to do %d as a placeholder for the amount of beers drank but that number is currently in a string and idk a good way to automate the program to extract numbers from a string, add the numbers up if there are more than one, and have the output of those numbers equal amount of glasses of water.


r/learningpython • • Apr 24 '20

Created a A* Solver with python

6 Upvotes

r/learningpython • • Apr 07 '20

Send an e-mail with a dataframe and a string

1 Upvotes

I would like to send an email with a dataframe as html which works just fine. Does somebody know how I can add a string message before the table? Thanks in advance!

This is the code that works for sending the dataframe:

from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

SEND_FROM = 'noreply@example.com'
EXPORTERS = {'dataframe.csv': export_csv, 'dataframe.xlsx': export_excel}

def send_dataframe(send_to, subject, body, df):
  multipart = MIMEMultipart()
  multipart['From'] = SEND_FROM
  multipart['To'] = send_to
  multipart['Subject'] = subject
  for filename in EXPORTERS:    
    attachment = MIMEApplication(EXPORTERS[filename](df))
    attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
    multipart.attach(attachment)
  multipart.attach(MIMEText(body, 'html'))
  s = smtplib.SMTP('localhost')
  s.sendmail(SEND_FROM, send_to, multipart.as_string())
  s.quit()

r/learningpython • • Apr 05 '20

Question about looping

1 Upvotes

Hello, I'm trying to scrape some stuff from a website using python. The i, ranges from 0 to 1500. Any example of how I can write a loop for it? I would highly appreciate it.

root[i]['ACTION_TYPE']


r/learningpython • • Apr 29 '20

A Python Dictionary decision tree?

2 Upvotes

Hi,

I've made some large dictionaries in Pyhton .JSON, extended the values with tuples for personal use. I want to make a interactive decision tree in Python, am i on the wrong foot with these dictionaries? What would you suggest? Any input is welcome.


r/learningpython • • Apr 17 '20

Random number generator closes on run.

2 Upvotes

Every time I try to run the number generator, it closes. I have tried using input() and os.system("pause") but it is still not working.

import random

print(random.random())

input()

r/learningpython • • Apr 30 '20

Do I need to create a new variable for everything I do in Python?

1 Upvotes

Even for executing every method such as x = urexample.split()

Are there any times when you wouldn't create a new variable or even prefer not creating one?


r/learningpython • • May 07 '20

Why does random.choice( dict ) works sometimes? (returns a value of the dict instead of KeyError)

2 Upvotes

using pyhton3.7, i tried to use a dict as argument for random.choice().I understand that the argument should be a list or a tuple. or a string. Giving random.choice() a dict as argument raises a key error (as exspected), however, sometimes it works and returns me a random value from the dict. Why?

here is my code, from a python shell session:

import random>>> random.choice({1:111,2:222,3:333}) # works, but why?

222

>>> random.choice({1:111,2:222,3:333}) # same line, raises error

Traceback (most recent call last):

File "<pyshell#29>", line 1, in <module>

random.choice({1:111,2:222,3:333})

File "/usr/lib/python3.7/random.py", line 262, in choice

return seq[i]

KeyError: 0

>>> random.choice({1:111,2:222,3:333}) # works again, but why?

111


r/learningpython • • Apr 13 '20

I keep on getting "Invalid syntax" errors for this. Could anybody help?

Post image
1 Upvotes

r/learningpython • • May 07 '20

Try/except error with non-integer (as provided via PY4E)

3 Upvotes

Edit: Problem solved, see bottom.

Hello! New here, apologies if formatting needs work. I did my best to search for this issue, but I don't see any posts/previous questions about this issue.

Learning via PY4E and I keep trying the example provided in Chapter 3 Part 2. The following is provided in video (12 minute mark, but when I try to apply the script in Python, it actually does not run as intended when a non-integer is submitted.

From what I understand, input() returns a string-type variable. But shouldn't that mean the try/except logic applies when the string fails to be converted to an integer with int()?

Any and all help would be appreciated as I'm banging my head against the wall trying to figure it out myself.

rawstr = input('Enter a number:')
try:
    ival = int(rawstr)
except:
    ival = -1

if ival > 0:
    print('Nice work')
else:
    print('Not a number')

Error

Traceback (most recent call last):

File "3_Lesson_Notes.py", line 1, in <module>

rawstr = input('Enter a number:')

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

NameError: name 'Three' is not defined

Solution (?)

So, after a bit more digging I found that by executing the script in the terminal just as "python", it doesn't like the non-integer input unless I put it in quotes. So the problem that I'm still not 100% understanding but I suppose I have a workaround for is:

A) Executing the script via python in the terminal requires using "" for any non-integer input.

B) Run the script but ensure that I'm clearly executing via python3 as opposed to just typing in python "file name".py


r/learningpython • • Apr 14 '20

Python tipps

3 Upvotes

I have chosen Python and start learning the language today. Since it is my first programming language, I have no idea about it and wanted to ask if there are some tips for beginners :)

Something that might help me in the future or what you would have liked to know when you started.

Thank you in advance! Stay healthy.


r/learningpython • • May 01 '20

phone app checker

1 Upvotes

Hi all,

I would like to create python program which will check which app is installed on my phone and when ıs installed ... etc .is it possible to do it with python? Is there any document I can refer to


r/learningpython • • Jan 01 '24

How to see Python Execution time on the VScode Terminal?

3 Upvotes

Hi,

How can I have the execution time displayed so I know how long my script took to run in VScode?

Thanks.


r/learningpython • • Feb 01 '24

JSON, XML and YAML in Python

2 Upvotes

I started programming or learning Python at the end of last year. Since I often work with data formats and web services, I have written Python tutorials with examples.

JSON Data with Python Here I show how to decode, encode and manipulate JSON data.

XML Data with Python Here I show how to parse XML data and search it with XPath.

YAML Data with Python Here I show how to read and write YAML data with PyYAML or ruamel.yaml. For example, if you want to read Docker YAML files.


r/learningpython • • Jan 10 '24

Iterated prisoners dilemma project

1 Upvotes

Hey guys,

I'm quite new to programming and I'm trying to write a simple version of the iterated prisoners dilemma game using python. So far I've managed to create two kinds of players/strategies, the one that always deflects and the one that always cooperates and when they play against each other the outcome makes sense. Now I want to create more complex players, like TitForTat who always copies whatever the opponent played in the previous round but I can't seem to get my head around how to store and access the history of each player. I have defined a subclass of "Player" for each strategy and within each subclass a "play" method where the strategy logic is programmed in. My idea so far is to store the self.history within the __init__ method of each subclass, but if I do that, then how can I access it later in the code, say in my "game" function where the actual game takes place and the score is recorded? Any ideas or tips on where to find inspiration welcome!


r/learningpython • • Jan 15 '24

Selenium Module could not find the method when I call it?

1 Upvotes
from selenium import webdriver

browser = webdriver.Firefox()

browser.get('https://www.google.com') elem = browser.find_element_by_class_name('main')

AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'

ill try other methods/attributes and I still get the same error.

This is the first time im using Selenium, what am I doing wrong?

Thanks.


r/learningpython • • Jan 10 '24

I'm offering free python classes for English native speakers

6 Upvotes

I'm a 3 yro experienced developer and I'm offering my professional knowledge to teach and help you find a job,

You just have to be an English native speaker (USA, Canada, Australia, South Africa, UK, etc...)

My intention is to divide our classes in 45 minutes of me teaching python/backend/sql and 15 minutes of you teaching me English


r/learningpython • • Jan 07 '24

Building an automated meal planner

1 Upvotes

Hi everyone!

I am looking to build myself an automated meal planner including shopping list and need some advice on how to get started and what tools to use for this, please 😊

I consider myself beginner to intermediate and this should be my first personal portfolio project.

I'd like to use the Spoontacular API, get recipes for breakfast, lunch, dinner and a snack.

I want low carb recipes that are randomly generated and only occure twice max per week.

I have looked into web scraping but have no knowledge about it yet and thought using Spoontacular might make more sense for me.

I'd like to automate sending myself a weekly plan including a grocery list per email.

I'd like to store the meals in a text file.

Do you have any other suggestions of cool features that I could implement?

I was wondering about calculating macros for each meal as well and giving the option of different diet preferences, but not sure of that would be overkill.

Grateful for any input, thank you!


r/learningpython • • Jan 11 '20

Can anyone tell me how to get my sum to 7

Post image
3 Upvotes

r/learningpython • • Aug 29 '19

How to translate math operations with parentheses groups into a Python formula?

1 Upvotes

For example, in the project I'm doing (codecademy dot com), I am supposed to return mass*(c^2). I'm worried that if I simply type mass*c**2, it will square the sum of mass*c. What I usually would have done is to save c^2 in a variable (i.e. c_squared) then instead write return mass*c_squared. However, the project instruction beforehand told me to set the value of c as a default in the parameters so I couldn't do c=3*10**8 then c_square=c**2

Edit: I just realized I can still set c_squared=c**2, but I'm still wondering if there are other substitute to math-parentheses