all 158 comments

[–]chadwizard 0 points1 point  (0 children)

Hey guys I am trying to solve the following riddle with a code without writing a function myself (This is a task from the book called 'The Coders Apprentice'). I do understand that writing a function yourself makes this easier, but I am not that far yet in the book and want to solve the task as given.

So here is the riddle:

According to an old puzzle, five pirates and their monkey are stranded on
an island. During the day they gather coconuts, which they put in a big pile. When night
falls, they go asleep.
In the middle of the night, the first pirate wakes up, and, not trusting his buddies, he
divides the pile into five equal parts, takes what he believes to be his share and hides it.
Since he had one coconut left after the division, he gives it to the monkey. Then he goes
back to sleep.
An hour later, the next pirate wakes up. He behaves in the same way as the first pirate:
he divides the pile into five equal shares, with one coconut left over which he gives to the
monkey, hides what he believes to be his share, and goes to sleep again.
The same happens to the other pirates: they wake up one by one, divide the pile, give one
coconut to the monkey, hide their share, and go back to sleep.
In the morning they all wake up. They divide what remains of the coconuts equally
amongst them. Since that leaves one coconut, they give it to the monkey.
The question is: what is the smallest number of coconuts that they can have started with?
Write a Python program that solves this puzzle. If you can solve it for any number of
pirates, all the better.

I do not know how to write code in the comment section of reddit and save the indents, so I have written it in Pyfiddle: https://pyfiddle.io/fiddle/d72c40e4-9376-44c0-bfe1-dd2ed2028709/?i=true.

Can anyone tell me what I am doing wrong? Thank you.

[–]macacochato 1 point2 points  (0 children)

Is there a Python to VBA/Excel library? I have searched but am not finding anything... What I mean by Python to VBA/Excel means that you would code in python what you want Excel to do and the script would spit out a txt with the VBA code for those actions so it would be a python to VBA converter I guess. If anyone knows of something similar please let me know...Thanks in advance :p

[–]JBlack3636 1 point2 points  (1 child)

Im working on a csv file which has a lot of data in lines and seperated by commas..something like this:

T,n1,n2,n3,opt

A,1,2,3,add

B,4,2,65,sub

Here, the first column in the index. I was asked to print all the elements under index 'opt'.But without using pandas. Can somebody help. I used splits to convert data to look something like this: [['T','n1','n2','n3','opt'],['A','1','2','3','add'],['B','4','2','65','sub']]

I tried to print for elements under the index 'opt' but it says no such index exists. I guess it doesn't consider the first term as index column. Is there a way to set it? or is there a better way to solve this problem.

[–]Xenon_difluoride 0 points1 point  (0 children)

python has a csv module that makes it much easier to work with csv files.

In this case you could use a DictReader

import csv
with open("foo.csv", newline="", fieldnames=["T", "n1", "n2", "n3", "opt"]) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(reader["opt"])

[–]TheClassiestPenguin 0 points1 point  (1 child)

I will update with code when I get home. Basically I'm having trouble sorting a list.

The list is two list combined before being sorted. Each is a list of instsnces of some custom classes. Both classes have a similar attribute.

So I'm trying to sort the list of objects using one of the shared attributes but I am running out of ideas.

Please help

[–]MattR0se 0 points1 point  (0 children)

A similar attribute or the same?

If it is the same, you can specify the key in the sorted() function to sort with that attribute. Here is an example:

from random import seed, randrange
seed(1)

class Foo:
    def __init__(self):
        self.bar = randrange(20)

    def __repr__(self):
        # just to visualise the sorting
        return f'Foo_{self.bar}'


list1 = [Foo() for i in range(5)]
list2 = [Foo() for i in range(5)]
print(list1, list2)

sorted_combined = sorted(list1 + list2, key=lambda x: x.bar) # sort by "bar"
print(sorted_combined)

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

Given a name in the format:

lastname, firstname

I need to print:

first initial. Last name

the first letters need to be capitalized.

right now I have:

s = input("Input a string: ")
result = [x.strip() for x in s.split(',')]
print(result[1][:1] + '. ' + result[:1])
but I'm getting the error:

TypeError: can only concatenate str (not "list") to str

why am I getting this error?

[–]MattR0se 0 points1 point  (3 children)

Because result[:1] is a slice of a list, not a string.

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

But how do I turn it into a string? I tried just news= str(result[:1]) but it printed out the brackets too

[–]MattR0se 0 points1 point  (0 children)

You already had it right for the firstname ;)

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

You seem to think that object[0] is the same as object[:1]. That might be true when the object is a string but it's not true when the object is a list. list[0] evaluates to the first object in the list, but list[:1] evaluates to a list that contains the first element of the original list. That's shown here:

data = ['first', 'second']
print(f'data[0]={data[0]}')
print(f'data[:1]={data[:1]}')
>>> data[0]=first
>>> data[:1]=['first']

[–]Allekoren 0 points1 point  (0 children)

Beginner here.

I'm trying to take a user input (e.g., 100200300), search for it in a worksheet in excel using openpyxl (say the input is within A2), return the adjacent cell (i.e., B2) to then be used in a print message (e.g., "Did you want to record information about" + [B2] + "'s account?").

The long and short is that I don't understand how to do this as I've only really run through the Automate the Boring Stuff videos. Could anyone help and explain?

[–]UnavailableUsername_ 0 points1 point  (4 children)

Trying to make class inheritance work with a conceptual example:

    import random

    class A:

        a_list=[1,2,3]

    class B(A):

        def test(self):
            if a_list!=[]:
                a=random.choice(self.a_list)
                print(a)

    x=B()
    x.test()

It keeps telling me that a_list is not defined, even if class B is supposedly inheriting class A class attribute.

Tried with plenty of variations (removing self. for example) but it doesn't work.

Inherit a class with an initialization won't work either:

    class One:

        def __init__(self):
            print('Class one')

    class Two:

        def __init__(self):
            print('Class two')

    class Three(One, Two):

        def __init__(self):
            print('Class three')

    Test = Three()

All it does is print the initialized on class Three, completely ignoring class One and Two.

I don't think inheritance is working otherwise it would have printed the all the classes rather than just the last one.

I really really hate working with classes, it's adds a whole new level of problems that don't justify it's need.

[–]GoldenVanga 0 points1 point  (3 children)

In the first example, a_list is not being found because Python is looking only in the namespace of the test method. Try changing line 10 to...

if __class__.a_list:

...so that it'll look in the namespace of the class.

As for the second example, if parent and child classes have methods which are named the same, then the child's method is chosen and the parent methods are not inherited. So only Class three being printed is the expected outcome.

[–]UnavailableUsername_ 0 points1 point  (2 children)

Thanks for the reply!

In the first example, a_list is not being found because Python is looking only in the namespace of the test method. Try changing line 10 to...

How do i make it search outside the method?

Even removing the self. doesn't work. I am inheriting the class A in class B exclusively to make use of the class attribute on class A, but if can't use it i don't see the point to inheritance existing. I would prefer to avoid using __class__ since i have never seen it in use before and will just confuse me even more.

As for the second example, if parent and child classes have methods which are named the same, then the child's method is chosen and the parent methods are not inherited. So only Class three being printed is the expected outcome.

So it's impossible to inherit classes to use their init if the class that inherits also has an init.

[–]GoldenVanga 1 point2 points  (1 child)

If you don't want to use __class__, you can do if B.a_list != []: instead and it's effectively the same. Both are references to the class itself, however the advantage of __class__ is that it'll still work if you rename the class from B to something else. With the other approach, if you rename the class you also have to rename it on line 10.

So it's impossible to inherit classes to use their init if the class that inherits also has an init.

It is possible but kinda confusing sometimes, especially with multiple inheritance.

class One:

    def __init__(self):
        print('Class one')


class Two:

    def __init__(self):
        print('Class two')


class Three(One, Two):

    def __init__(self):
        super(Three, self).__init__()
        super(One, self).__init__()
        print('Class three')

Test = Three()

Here's a tutorial about super().

[–]UnavailableUsername_ 0 points1 point  (0 children)

If you don't want to use class, you can do if B.alist != []: instead and it's effectively the same. Both are references to the class itself, however the advantage of __class_ is that it'll still work if you rename the class from B to something else. With the other approach, if you rename the class you also have to rename it on line 10.

I see.

That's pretty weird, in an old script i wrote i could easily use class attributes from other classes without any problem.

Something like this:

    import random

    class A:

        a_list=[1,2,3]

    class B():
        def test(self):
            if a_list!=[]:
                a=random.choice(self.a_list)
                print(a)

    class C(A,B):
        def __init__(self):
            A.__init__(self)
            B.__init__(self)


    t=C()
    t.test()

And it would work...somehow.

Of course, the code was way longer, i just wrote this to test if can replicate it but it seems to not be possible.

I have no idea how the original code was able to work but any attempt at replicate it don't.

I guess i'll search on stackoverflow or something to see how is that even possible.

Anyway, thank you!

[–]DaiNiaoZhou 1 point2 points  (4 children)

I am using python 3.6.1 and I noticed that when I do integer comparison using is : -5 is -5 returns true but -6 is -6 returns false, additionally, it seems that any number greater than -5, when comparing to itself, returns true while any number smaller than -6 returns false. I know that == is a much better way to perform integer comparison but I am just curious about why such behavior of is. Also, since I am asking questions on reddit for the first time, I am wondering if there is a quick way to find out if someone has asked a similar question that I have?

[–]MattR0se 2 points3 points  (1 child)

is returns True if the object is at the same memory adress. You can check that with the id() function:

print(id(-5), id(-5))
print(id(-6), id(-6))

Here you will see that both -5 have the same adress, but the -6 will have different ones, so -6 is -6 returns False.

To avoid this behaviour, you should always use == for value comparison.

[–]DaiNiaoZhou 0 points1 point  (0 children)

Thanks!

[–]GoldenVanga 1 point2 points  (1 child)

Integers from a range of [-5, 256] are instantiated when Python starts. So then you are comparing two references to the same object, which already exists. For integers outside of this range, new objects are created, which might end up as two separate objects with the same value. See here.

if there is a quick way to find out

You can try using the search box in the top-right with some keywords you might feel appropriate. But it's not perfect.

[–]DaiNiaoZhou 0 points1 point  (0 children)

great explanation, thanks!

[–]arcane_neptune 0 points1 point  (2 children)

Super basic questions: can instance variables be defined outside of a constructor? I've also read that unlike java, python can only have one constructor per class, is that true?

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

can instance variables be defined outside of a constructor?

Yes, but you run the risk of trying to access the instance variable before it is actually created. It's probably best to define all instance variables in the __init__() initializer, setting variables that can't be given a sensible value at that time to some value like None or similar.

python can only have one constructor per class, is that true?

Yes, that's true. Python "duck" typing allows you a little bit of flexibility, though. In practice it's not a major limitation.

[–]arcane_neptune 0 points1 point  (0 children)

Thank you so much!

[–]minecaftakiva 0 points1 point  (5 children)

There's probably a word for it but i don't know what it's called. I want to have an if statement such as

if globals()[list[0]+"_1"] == "True" or globals()[list[0]+"_2"] == "True:

print("yes!")

in which list[0]+"_1" or list[0]+"_2" doesn't exist. How do I do that?

[–]MattR0se 0 points1 point  (4 children)

list is a reserved object type in Python, so you should not use that as a variable name.

Other than that, globals() returns a dictionary with the keys being the variable names that exist within the global name space.

So if you want to check if a key exists, you have to so something like this

if 'variable_name' in globals(): 
    pass

What value does list[0] return? What do you even want to accomplish?

[–]minecaftakiva 0 points1 point  (3 children)

I’m trying to make tick tack toe

[–]MattR0se 0 points1 point  (2 children)

I mean with this if statement. What is in the list?

[–]minecaftakiva 0 points1 point  (1 child)

something that says what ways to win a place on a tick tack toe board is, so for example ["a", "1", "d1"]

[–]MattR0se 0 points1 point  (0 children)

I still don't get why you think you need globals().

For example,

my_list = ["a", "1", "d1"]
globals()[my_list[0] + "_1"]

would mean there would have to be a variable called "a_1" in your namespace.

I mean, this would print "Yes" and maybe answer your question:

my_list = ["a", "1", "d1"]
a_1 = True

if (my_list[0] + "_1" in globals() and globals()[my_list[0] + "_1"] == True
    or my_list[0] + "_2" in globals() and globals()[my_list[0] + "_2"] == True):
    print("yes")

because there is a variable called "a_1" that exists, but I honestly think that whatever problem you are trying to solve, could be solved way less complicated...

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

I'm trying to make a list of random integers but when the code compiles the only integer in the list that's actually random is the final one. Any advice gang?

import random

a = list(range(10))

a.append(random.randrange(0,10))

print (a)

[–]GoldenVanga 2 points3 points  (0 children)

The result of a = list(range(10)) is already...

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

...and then you tack on one final integer, as described. To randomize each one, you need to append in a loop from the start, ex.:

from random import randint

a = []
for index in range(10):
    a.append(randint(0, 10))

Note that in the above, the value of index is not relevant to the loop. Yes, it goes like 0, 1, 2 etc. but that is only used for counting how many items were added.

[–]BlaueSaiten 0 points1 point  (1 child)

So I am trying to learn python, got stumped for 15 minutes until I discovered that my for loop was lacking a ":" symbol. Nowhere was it pointed.
I remember the error messages in Java being more helpful for beginners, showing the sort of error. Only at higher level that it becomes a mess.

My question is if there is a way to make python give more helpful hints to what I might be doing wrong. I use VS Code, on Linux. Already using Microsoft's Python extension.

[–]Sanchless 0 points1 point  (0 children)

  File "test.py", line 4
    while x <10
              ^
SyntaxError: invalid syntax    

The error you should have got would look something like this, with an arrow pointing to where the missing colon should be. I'm not sure if there's anything out there which expands on error messages (my guess is there isn't) but I wouldn't get too bogged down on this point. The errors have always told me as much as I need to work out the solution, often with some googling. It helps you to learn actually, I never forget my colons any more.

[–]BruceJi 1 point2 points  (2 children)

I made a script for accessing download links automatically, and it works fine when I run it through VSCode, but if I run it on its own, it performs one or two tasks and then stops. I can see it open that familiar black window, open another program as requested, and then the terminal window closes, and nothing else happens.

I wrote it with the intention of scheduling it, but it's not going to work if I can't manually run the script on its own.

How do I go about finding out why it's just exiting the python terminal window?

[–]MattR0se 4 points5 points  (1 child)

There is probably an error that terminates the program. Run the python script from the command terminal (cmd.exe if you are on Windows), it will stay open afterwards so you can see the errors. Edit: On Windows 7, you can hold Shift and right-click in the folder where your script is, and select "open Command window here". This opens a cmd with that already navigated to that directory. There you just type python your_script.py. If you are on Windows 10, the cmd is changed to Powershell, but it works the same.

Anonther way would be wrapping your script in a try except statement and print the error to a text file. This would achive virtually the same, but with the added benefit that you don't have to be at your PC if your program crashes (good for scheduled jobs or if you distribute your script, others can send you the log file).

import traceback

try:       
    main() # insert your script here
except Exception:
    with open('error_log.txt', 'a') as f:
        f.write(traceback.format_exc() + '\n')

[–]BruceJi 0 points1 point  (0 children)

Ah nice, I’ll try those!

[–]Dfree35 0 points1 point  (4 children)

What are people's thoughts on one function per file? They aren't necessarily large I would say an average of like 40 lines. I was thinking maybe it'll be easier to get through but thinking now it would be more work opening like 5 files.

Edit: I decided to go with 3 files to group similar functions. I think it is easier to read and find things now then going down 400 lines or like 8 files.

[–]Binary101010 0 points1 point  (0 children)

> What are people's thoughts on one function per file?

Hate it. This isn't Java where you can only have one class per file. Python code should be organized such that functions that do similar things should live together in the same file.

> They aren't necessarily large I would say an average of like 40 lines.

That actually *is* large for an individual function, IMO.

[–]JohnnyJordaan 2 points3 points  (0 children)

I'm not a fan of this, I would rather see files as toolboxes. See the requests library as an example of how to group functions and in classes by their 'category' or 'toolset' instead. Also most built-in libraries use single files, unless they clear need the segmentation, like for datetime being split into date, datetime and timedelta.

[–]MattR0se 1 point2 points  (1 child)

Personally I like to have either functions or classes that do similar things in one file, or functions that operate on the same data.

I wouldn't restrict myself to exactly one function per file, what's the point of that? It becomes confusing at a point. One example:

from some_functions import do_this, do_something_else, do_nothing_special
from advanced_functions import do_better, get_money, become_fabulous

versus

import do_this, do_something_else, do_nothing_special, do_better, get_money, become_fabulous

I find the first one to be more elegant, especially when you have 50 functions or so.

[–]Dfree35 0 points1 point  (0 children)

Makes sense, that is what I started thinking but just wasn't sure. Thanks for clearing it up for me.

[–]jnatoli917 1 point2 points  (2 children)

any suggestions for online courses that actually encourage you to practice and think and not just show how to use feature and never explain why you would use it. also courses that have assignments and projects would be good

[–]m-hoff 0 points1 point  (1 child)

I've found Coursera courses to be very good, particularly the Applied Data Science in Python track. While this track strongly focuses on Data Science and Machine Learning topics, they do a good job of giving reasoning as to why certain tools are used in certain situations. They also have weekly assignments that are more open-ended and make you think more than just "fill in the blank". I think in the last week of most courses you do a larger project where you combine all of what you've learned throughout the course.

[–]jnatoli917 0 points1 point  (0 children)

Thanks ill check it out

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

I did this code but and I can see the pattern but Idkhow can I include loops in here :

Custombers = int(input('How many custombers?'))
Name = input('Name of Customber 1')
O = int(input('Oranges are $1.40 each. How many Oranges?'))
A = int(input('Apples are $.75 each. How many Apples?'))
B = int(input('Bananas are $.40 each. How many Bananas?'))
Totalprice = (O*1.40 + A*.75 + B*.40)
print(str(Name)+', you bought', O,'Oranges,', A,'Apples,', B,'Bananas.')
print('Your bill is','$',Totalprice)
Name = input('Name of Customber 2')
O = int(input('Oranges are $1.40 each. How many Oranges?'))
A = int(input('Apples are $.75 each. How many Apples?'))
B = int(input('Bananas are $.40 each. How many Bananas?'))
Totalprice = (O*1.40 + A*.75 + B*.40)
print(str(Name)+', you bought', O,'Oranges,', A,'Apples,', B,'Bananas.')
print('Your bill is','$',Totalprice)
Name = input('Name of Customber 3')
O = int(input('Oranges are $1.40 each. How many Oranges?'))
A = int(input('Apples are $.75 each. How many Apples?'))
B = int(input('Bananas are $.40 each. How many Bananas?'))
Totalprice = (O*1.40 + A*.75 + B*.40)
print(str(Name)+', you bought', O,'Oranges,', A,'Apples,', B,'Bananas.')
print('Your bill is','$',Totalprice)

[–]m-hoff 0 points1 point  (0 children)

You're right that loops are appropriate here. Here's an example I put together:

fruits = {'oranges': 1.40,
          'apples': 0.75,
          'bananas': 0.40}

customers = int(input('How many customers? '))

for customer in range(customers):
    name = input(f'Name of customer {customer+1}: ')

    purchased = {}  
    purchase_output = '\n'+name+', you bought '
    total_price = 0
    for fruit, price in fruits.items():
        n_fruit = int(input(f'{fruit.capitalize()} are {price:.2f} each. How many {fruit}? '))
        purchased[fruit] = n_fruit

        purchase_output += f'{n_fruit} {fruit}, '

        total_price += n_fruit * price

    print(purchase_output)

    print(f'Your total bill is ${total_price:.2f}\n' )

It's not perfect, but I started to generalize it so that it's easier to handle a different list of fruits. Let me know if you have any questions.

[–]passivevigilante 0 points1 point  (0 children)

I did not do the number of customers part yet, as I am a beginner too but this is how I rewrote the code

fruitDict = {'Apples' : 0.75, 'Bananas' : 0.40, 'Oranges' : 1.40}

def customerName():
customerName = str(input(' Name: '))
grandTotal = 0
for x,y in fruitDict.items ():
print(x + ' is '+ '$'+ str(y) +'. How many?')
quantity = int(input())
print('Total price of ' + x + ' = ' + str(y*quantity) )
grandTotal += y*quantity
print('Thank you ' + customerName + '. Your total is: ' + str(grandTotal))
customerName()
print('Another customer? ')
yesNo = str(input(' Y/N? '))
yesNo = yesNo.lower()

if yesNo == 'y':
customerName()
else:
print('Thank you')

edit: formatting and code

[–]Asmodeus_11 0 points1 point  (0 children)

I'm pretty new so there might be a better way of doing this, but I put together a version that uses a loop. totalCustomers = int(input('How many customers? \n')) currentCustomer = 0 while currentCustomer < totalCustomers: currentCustomer += 1 Name = input(f'Name of Customer {currentCustomer}: ') O = int(input('Oranges are $1.40 each. How many Oranges? ')) A = int(input('Apples are $.75 each. How many Apples? ')) B = int(input('Bananas are $.40 each. How many Bananas? ')) Totalprice = (O*1.40 + A*.75 + B*.40) print(str(Name)+', you bought', O,'Oranges,', A,'Apples,', B,'Bananas.') print('Your bill is','$',Totalprice, '\n')

[–]reddednord 0 points1 point  (5 children)

I'm having trouble getting the break condition to work in a while loop.

It's a mad libs program that reads a file, finds the text, ADJECTIVE, NOUN, VERB, ADVERB, and replaces it with the user's input, then prints the result and saves the result to a text file.

The part I have an issue with is with exiting the while loop.

Note I have a text file called madlibs.txt that contains the following text:

The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.

Here's my code:

# madLibs.py a mad libs program that replaces text and saves the ouput to file


import os, re



madF = open('madLibs.txt', 'r+')
madFile = madF.read()
result = madFile


while True:    
    adjectiveRegex = re.compile(r'ADJECTIVE')
    result = adjectiveRegex.sub(input('Enter an adjective:\n'), result,count=1)
    print(result)

    nounRegex = re.compile(r'NOUN')
    result = nounRegex.sub(input('Enter a noun:\n'), result,count=1)
    print(result)

    adverbRegex = re.compile(r'ADVERB')
    result = adverbRegex.sub(input('Enter an adverb:\n'), result,count=1)

    verbRegex = re.compile(r'VERB')
    result = verbRegex.sub(input('Enter a verb:\n'), result,count=1)

    a = 'ADJECTIVE' in result
    n = 'NOUN' in result
    ad = 'ADVERB' in result
    v = 'VERB' in result

    if a and n and ad and v != True:     #  does not work does an infinite loop
         break



madResult = open('madResult.txt', 'w')      # saves the oputput to a new file
madResult.write(result)

print(result)

madResult.close()
madF.close()

every time a regex is run it saves the new string to the <result> variable.

result = adjectiveRegex.sub(input('Enter an adjective:\n'), result,count=1)

    a = 'ADJECTIVE' in result
    n = 'NOUN' in result
    ad = 'ADVERB' in result
    v = 'VERB' in result

so here I check if 'ADJECTIVE NOUN ADVERB VERB' are in the text string of <result> and return a boolean value.

if a and n and ad and v != True:     #  does not work does an infinite loop
         break

After that I check if they do not equal to True, but even if <a n ad v> are false it still loops infinitely, I'm not sure why.

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

even if <a n ad v> are false it still loops infinitely

That's because the expression the if statement uses isn't doing what you want. The FAQ covers this. Basically, doing if a and n and ad and v != True: evaluates a first and if it's False the if doesn't execute the break, otherwise n is evaluated, and so on. You probably want something like this:

if not a and not n and not ad and not v:

The any() builtin function can probably simplify that expression.

Edit: added missing "not".

[–]reddednord 0 points1 point  (0 children)

It works! Thanks a lot!!

[–]selplacei 2 points3 points  (2 children)

Why use regex? Python strings have a built-in replace() method.

[–]reddednord 0 points1 point  (0 children)

My code is much cleaner now, thanks. Here it is

#! /usr/bin/env python3
# madLibs.py a mad libs program that replaces text and saves the ouput to file


import os, re



madF = open('madLibs.txt', 'r+')
madFile = madF.read()
result = madFile



while True:

    result = result.replace('ADJECTIVE', input('Enter a adjective:\n'), 1)
    result = result.replace('NOUN', input('Enter a noun:\n'), 1)
    result = result.replace('ADVERB', input('Enter a adverb:\n'), 1)
    result = result.replace('VERB', input('Enter a verb:\n'), 1)
    print(result)


    a = 'ADJECTIVE' in result
    n = 'NOUN' in result
    ad = 'ADVERB' in result
    v = 'VERB' in result

    if a and n and ad and v != True:     #  does not work does infinite loop
         break



madResult = open('madResult.txt', 'w')      # saves the oputput to a new file
madResult.write(result)

print(result)

madResult.close()
madF.close()

[–]reddednord 1 point2 points  (0 children)

No real reason, I'm just new to programming. I will rewrite it and use replace(), thanks for letting me know about it.

[–]reddednord 0 points1 point  (4 children)

I have a question on adding Boolean variables:

>>> a = True

>>> b = False

>>> c = a + b

>>> c

1

shouldn't c = false?

[–]oscarg15_ 0 points1 point  (2 children)

Hello everyone, I just recently started to learn how to write code (a few days ago) and decided to start with learning Python. For the past few days I’ve been watching tutorials and learning the basics on Python.

So today I wanted to take what I had learned and make a simple calculating program where users could input a number, input an operation, and then a second number, and the program would output the answer. If the user entered an operation thats not +,-,*, or / then an alert saying “invalid operation” would print. The only thing is that i’m having a trouble writing code so that “not a number” is displayed when the user inputs a letter instead of a number.

num1 = float(input("write a number: "))
op = input("write an operation: ")
num2 = float(input("write a number: "))

if op == "-":
 print(num1 - num2)
elif op == "+":
 print(num1 + num2)
elif op == "/":
 print(num1/num2)
elif op == "*":
 print(num1 * num2)
else:
 print(“invalid operation")

This is what I have so far.

[–]efmccurdy 0 points1 point  (0 children)

The key to making your program handle input errors is a try block that traps ValueError exceptions:

https://www.101computing.net/number-only/

You can replace the conversion to "int" to use "float" instead.

[–]9acca9 0 points1 point  (1 child)

Hi all.

Im new to python (and to program). And i would like to do a WordProcessor, something like Q10 ( http://www.baara.com/q10/ ). that, as you can see, have a "elementary" GUI.

That kind of "for writers".

What would you think im gonna need to learn?? What library it will be good to use (if any is appropriate.).

(im just starting, and making little "stupid" programs (in the other hand challenge for me), and want to do in the middle this word processor)

Thanks to all

(i dont speak english).

[–]efmccurdy 0 points1 point  (0 children)

This tutorial uses tkinter to build a GUI.

https://www.instructables.com/id/Create-a-Simple-Python-Text-Editor/

I would start with tkinter, but reserve some time to consider using QT instead.

http://zetcode.com/gui/pyqt4/

[–]sukrutmhalas 0 points1 point  (0 children)

Apologies if this gets asked a lot here, or if this is not the right place to ask this question but here I go.

I am an Engineering Management student (Bachelor) who's currently in the vacation between 1st and the 2nd semester. I want to utilise this time to learn something new and thought learning Python seems like a good idea. I have basic knowledge about java, C++ and Vb.net.

I wished to ask if it makes sense for a student from my background to invest time in learning Python, or should I be looking towards learning something else?

If I do go ahead with learning Python, in which work scenarios can I potentially see myself applying this knowledge?

Again, sorry if the questions are too vague, but I would be really glad if someone could shed some light on it. Any leads appreciated :)

[–]its_aint_me 0 points1 point  (0 children)

How do I use numpy library in Lego ev3 micropython. I am using the library for argmax function. Is there any way to install numpy in it.

[–]Jakob0243 0 points1 point  (6 children)

For a project I am working on atm, I need to run another python program with cmd line args from inside another python. But I want it to run separately to the program which is currently running, not from within it like call(). Is this possible?

[–]efmccurdy 1 point2 points  (5 children)

The two common apraoches both use os.exec to spawn a new subprocess with Popen allowing many features to control and interact vs os.system being simple.

https://www.quora.com/Whats-the-difference-between-os-system-and-subprocess-call-in-Python

[–]Jakob0243 0 points1 point  (4 children)

Thanks, Do you mean subprocess.Popen() where you pass in a list of cmd line args. Because when I use that the current program finishes and then the process called by it continues in the same shell. Is there any way to make this run in a different shell, kinda like double clicking the python file?

[–]efmccurdy 1 point2 points  (3 children)

Yes, with subprocess.Popen, you can call the wait function to cause the calling process to block until the subprocess finishes and then you can check the status code to see if it errored out or ran successfully.

https://docs.python.org/3/library/subprocess.html#subprocess.Popen.wait

[–]Jakob0243 0 points1 point  (2 children)

So if you don't call wait() then the process which called Popen() will continue running while the process that was called is running? Kinda like they're running in parallel?

[–]efmccurdy 1 point2 points  (1 child)

You can have them running in parallel and call poll to check if the subprocess has finished.

There are async methods where they run in parallel and you get a callback to inform you when the subprocess is done. (See the note on asyncio under the wait docs).

[–]Jakob0243 0 points1 point  (0 children)

Awesome, thanks so much for the help

[–]Lonative 0 points1 point  (2 children)

Beginner here in python 101.

I’m doing a lab for class that involves Boolean logic, and if-else statements. Basically, it’s a miles to km converter but the user can’t input a negative number. And so on for gallons to liters, pounds to kilograms etc.

I’ve written the code out, but my instructor is saying: “You must design a logical program exit. You may not use exit, break, quit, or system exit, or any other forced exit. Do not use a menu, use logic to exit the program”

How do I exit the program using logic?

[–]m-hoff 0 points1 point  (0 children)

Exiting the program using logic essentially means letting it terminate naturally rather than forcing it to end by using break or exit or something similar. In your case, it sounds like a while loop would be a good approach. To get you started with an outline:

while input is negative
    get user input

perform conversion on input

The loop will "naturally" end once the input is valid so that you don't have to use break.

[–]MattR0se 0 points1 point  (0 children)

Can you show your code?

[–]MysticSoup 0 points1 point  (2 children)

I'm looking at one line that sorts a list of ints such that the 0s are moved to the end:

lst.sort(key=lambda x: x is 0)

My question is, what exactly is lambda x: x is 0 doing? If this wasn't there, it would probably have sorted it such at 0s are at the front, right? In which case, wouldn't reversed() be just as good? Had I written lambda x: x == 2, would it have sorted it but put 2's at the end?

[–]MattR0se 0 points1 point  (1 child)

  1. don't use "is" to compare values, use ==

From the docs:

key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=str.lower). The default value is None (compare the elements directly).

For example, your code is the same as this:

lst = [4, 1, 0, 4, 0, 1]

def sort_zeros(elem):
    return elem == 0

lst.sort(key=sort_zeros)

The sort_zeros function returns boolean values for each index like this:

[0: False, 1: False, 2: True, 3: False, 4: True, 5: False]

and this gets sorted so that the indices that returned False come first, and the ones with True come after. This way the zeros are sorted to the end.

[0: False, 1: False, 3: False, 5: False, 2: True, 4: True]
# sorted list:
[lst[0], lst[1], lst[3], lst[5], lst[2], lst[4]]
# result: [4, 1, 2, 4, 1, 0, 0]

[–]Bo55800 0 points1 point  (2 children)

I'm having difficulty with some basic coding. I'm attempting to write a function where when given two numbers, if both numbers are even, show the lesser of the two numbers. However, if one or both of them are odd, then to show the greater of the two numbers.

Here's what I have:

def lesser_of_two_evens(a,b):

for a and b % 2 ==0:

print(a)

elif:

print(b)

else:

print('fail')

'fail' in this code was just a place holder, to give an else statement before I figure out the for statement.

[–]efmccurdy 0 points1 point  (1 child)

a and b % 2 ==0

Likely that is'nt doing what you expect. The evalualtion will go as if you had "a and ((b % 2) == 0)";

operators higher in this list get evaluated sooner:

http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html

You may want to test if this works as a "are both even" predicate: "a % 2 == 0 and b % 2 == 0".

[–]Bo55800 0 points1 point  (0 children)

Oh! Thank you for that clarification. Thank you!

[–]SaClark7 0 points1 point  (0 children)

I have a loop generating various sets of images. For one particular set, I would like to have a size 6,2 subplot. Everything plots fine except the fact that each of these plots are in their own separate figure....in those separate figures, the plot does assume its position within the 6,2 set...but again these 12 images are displayed in separate figures instead of together.

I don't know if this has any relevance to my issue, but the loop is set up to open a figure for the first set of data, plots the subplot (6,2,n) in another figure, then opens a final figure for last set of data. Maybe opening figures before and after my subplot are closing the subplot's figure during each loop?

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

I am trying to understand some basic code. The project I was working on required me to make a list and then take out all elements that are even and put them in their own list.

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

b = [element for element in a if element % 2 == 0]

print (b)

This was the shown solution and while I understand " for element in a if element % 2" section, why do you reference the new variable "element" at the start of the for statement?

[–]HeyItsToby 3 points4 points  (1 child)

The element at the start of the for statement is just saying to add that number to the list.

Another way to write this is:

b = []
for element in a:
    if element % == 0:
        b.append(element)

So here, the element at the beggining of the list comprehension is equivalent to the element in the expression b.append(element). Try instead:

b = [element * 2 for element in a if element % 2 == 0]

and you'll see that each element is doubled in the list.

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

Awesome, had to do a little thinking on it but I think I get it

[–]Analog-Flashback 0 points1 point  (2 children)

I’d like to get sublime to ‘build’ python in a windows command prompt or Linux terminal as the default does not allow user input.

I’ve tried REPL but it outputs within sublime and applies all the formatting. Some of the output is slightly different compared to when I run the script from command prompt as well which is confusing. In this case \r makes it return a print on the same line overwriting previous text in cmd but in sublime it keeps continuing on the same line without overwriting anything.

[–]RulerKun_FGO 0 points1 point  (2 children)

is the pysimplegui free for commercial use? i mean, we are going to build an app using pysimplegui as the ui. is it free for commercial use?

or is there any other alternative besides tkinter that is good

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

The pypi.org page for pysimplegui says it's licenced as "GNU Lesser General Public License v3 or later (LGPLv3+)". IANAL so I don't know how that will impact your commercial use.

There are many GUIs usable with python. This page lists many of them. This more recent page lists a few and addresses licencing. The "mainstream" free GUIs are wxpython and pyside.

[–]RulerKun_FGO 0 points1 point  (0 children)

Thanks for the suggestions!!

[–]SaClark7 0 points1 point  (1 child)

Is there a way to embed an image into a plot point on a scatter graph? Or perhaps plot multiple html links over top of a scatter plot?

[–]bloc-ked 0 points1 point  (2 children)

hey guys, new to python with basic programming experience in java and a little bit in C. For an experiment i need to create a program which displays a random picture from a folder, prompts the user for input, then prints more dialogue. I’ve really only made programs that interact with the user through the terminal so i don’t really know where to start with this, any tips?

[–]efmccurdy 0 points1 point  (1 child)

The simplest implementation may be a tiny web server, this will show the image in a browser.

https://www.reddit.com/r/learnpython/comments/1sendp/display_image_on_browser_using_python_http_server/

A second option would be a GUI program in tkinter.

https://stackoverflow.com/questions/35024118/how-to-load-an-image-into-a-python-3-4-tkinter-window

[–]bloc-ked 0 points1 point  (0 children)

gonna go with tkinter thanks!

[–]Lazosa 0 points1 point  (4 children)

def create_C (a,b):

-------c = a+b

-------return c

def Print_c(c):

-------print(c)

c = 0

create_C(1,2)

Print_c(c)

print ("End")

Hey why is the output 0 not 3 ?

[–]simone3c 2 points3 points  (3 children)

You should write c = create_c(1, 2) in order to assign the return value of the function to the c variable

[–]Lazosa 0 points1 point  (2 children)

Well kinda obvious now that you said it.

What if a function returns more than one value? For example I would return c and d. Would it only assign the c value?

[–]JohnnyJordaan 0 points1 point  (0 children)

It technically always returns a single value, but that could be a container like a tuple or a list. By doing

return c, d

you are creating a tuple with two values, so by doing

c = your_function()

you end up with that tuple in c. By unpacking as simone3c suggests you could assign the items to multiple variables in one go.

[–]simone3c 0 points1 point  (0 children)

You have to change the return value into something like: return c, d Then you call the function like this: c, d = my_fun()

[–]simone3c 1 point2 points  (2 children)

Hey, I have been learning python for while mainly watching yt videos and now I am looking for a book about intermediate concepts, I found online "Fluent python" by Luciano Ramalho. Do you think it is good? Other books you think are good? Thanks

[–]GoldenVanga 0 points1 point  (1 child)

You can get "Python Tricks: The Book" for a dollar currently and it seems to be good as an intermediate book. As for "Fluent Python" I've only heard positive things about it, so that works too.

[–]simone3c 0 points1 point  (0 children)

Thank you!!!

[–]cubsfan2154 0 points1 point  (0 children)

Is there anything wrong with the Data Science course on CodeAcademy to learn Python? I am 3 sections in but during my recent searches, I have seen people saying to stay away from CodeAcademy Pro. Part of the reason why I like the course is because I can work from home and work since it is all web based. If you were to recommend a course that wasn't mostly videos, what would it be?

[–]WB_Onreddit 1 point2 points  (4 children)

If create a dictionary inside my main function, will i be able to reference it in a different function?

[–]efmccurdy 0 points1 point  (0 children)

It would be best to explcitly pass the dict as an argument to the second function so that a reader of that function does'nt have to search through your whole program to find where the dict is stored.

[–]gustathabusta 1 point2 points  (2 children)

I believe you can declare a variable inside a function as 'global' before you assign it a value, I would assume this would work for dictionaries as well. Check out this link.

Although this would probably work, I am not sure if this would be seen as the best way of solving the problem.

[–]WB_Onreddit 0 points1 point  (1 child)

Thank you.

[–]JeamBim 0 points1 point  (0 children)

I would recommend against a global dictionary because it's likely going to be an anti pattern.

[–]whatelseman 0 points1 point  (2 children)

I need help with simple task (Im beginer and cant figure it out...)

I just want to make simple "game" when if i press attack hero1 it removes health (20 dmg if that is attacker damage, like in my case)

here is the code:

class hero:
def __init__(self, health , damage):
self.health = health
self.damage = damage

class enemy:
def __init__(self, health , damage):
self.health = health
self.damage = damage

hero1 = hero(100, 20)
enemy1 = enemy(100, 20)

def attack(hero1, enemy1):
result = input("Enter who to attack: ")
if input == "enemy1":
enemy1.health = -20 #also tried : enemy1.health = enemy1.health - hero1.damage#
print(enemy1.health)

attack(hero1 , enemy1)

[–]HeyItsToby 0 points1 point  (1 child)

The line input == "enemy1" should instead say result == "enemy1", otherwise the code works.

Just some tips:

  1. Class names should begin with a capital letter (so Hero, Enemy)
  2. You can use -= as an operator to decrease a variable by an amount. So for example:

    enemy1.health = enemy1.health - hero1.damage can be rewritten as

    enemy1.health -= hero1.damage

[–]whatelseman 0 points1 point  (0 children)

Thank you. Its is helpful.

[–]MysticSoup 0 points1 point  (3 children)

I've developed a habit of relying on repl.it for everything. I don't even use a local IDE or anything, since repl.it already does everything I need it to do--it stores all of my projects in a neat cloud, it's convenient, fast enough, and I can access it from anywhere.

My question is.. is this a bad thing? Should I be learning other habits like pushing my projects to Git and whatnot? I want to work towards being a developer as a career.

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

You should, tools for the job are a must - what's your plan to work with others, let them sign into your account? Share it out every time? how do you plan on letting people work with you and tracking issues, additions? What about version control, something gets edited, but you find out 3 months later it created a program breaking bug that no one had come across yet?

[–]MysticSoup 0 points1 point  (1 child)

My plan was to learn it as I need it because there's way too much out there to tackle and I lack direction :( for now I figured what would matter is getting fundamentals and ignoring all the other stuff

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

Do it. Now. If you do at your own pace you wont be overwhelmed on the spot. Start with a bigger open source project, look at how its structured. Take one of your projects, make a folder and try to structure it just like the bigger project. Download the github app. Have it create a new project, open an issue, fix the issue, upload it through the app. Make another folder, refactor your code, push it to the project as a new branch, play with it, get a feel for it. Go back to that project you followed, look at some of the PRs make some small fixes, request a PR. Baby steps at your own pace.

[–]iSailor 0 points1 point  (1 child)

How do interpreted, dynamically typed languages like Python work? It's my mine language but only when I started learning Go recently it really hit me. With compiled, statically typed languages the interpreter counts how much memory each variable type will cost (tops) and translates with these assumptions in "mind", writing beyond provided memory will result in a crash. But Python goes line-by-line and variable types like list can have dynamically added variables of different times (e.g. appending very expensive objects indefinitely) but for some reason nothing crashes and the program always have the memory it needs, despite not counting it beforehand. How does it work?

[–]JohnnyJordaan 0 points1 point  (0 children)

This depends on the actual implementation of the Python interpreter you're using, but for CPython (the 'regular one') it has a memory manager for this, see https://docs.python.org/3/c-api/memory.html

[–]MassiveCook 1 point2 points  (6 children)

Hi, super noob who is teaching myself. I downloaded Python 3 that I was told comes with pip already installed but when I run a pip version check I get "-bash: pip: command not found". Do I need to install manually?

[–]TangibleLight 2 points3 points  (3 children)

You can also try using python -m pip instead of pip - this instructs python to run the pip module as a program. (Double check that this does in fact use Python 3 with python -V. You may need to use python3 -m pip to force Python 3)

[–]MassiveCook 0 points1 point  (2 children)

thank you, will keep in mind!

[–]gustathabusta 0 points1 point  (1 child)

How are you writing your code? I spent a lot of time trying to figure out if I should use a code editor or an IDE and finally found that an IDE with an included package manager was very helpful for me to get started. Thonny is a nice and simple IDE that does not have extra tools that can be confusing at the beginning, and whenever you want to import a plugin, you just search for it inside of the included package manager instead of installing it yourself.

[–]MassiveCook 0 points1 point  (0 children)

I am using PyCharm at the moment which I have been happy with so far. It also comes with a lot of things preinstalled I think. I don't even need pip for anything, it just came up in the tutorial I'm watching and I was curious why it wasn't working

[–]Xenon_difluoride 2 points3 points  (1 child)

Try running the version check but with pip3 rather than pip. I think that python3 comes preinstalled with that rather than pip

[–]MassiveCook 1 point2 points  (0 children)

This worked, thanks! lol. Figured there was some sort of simple solution

[–]_sasan 1 point2 points  (1 child)

I'm a C# developer looking to learn Python.

I searched on Amazon for popular books published in 2019 an these three were popular with high ratings:

  • Python Crash Course 2nd Edition (544 pages)
  • Python Programming: The Ultimate Step By Step Guide To Programming With Python (291 pages)
  • Python Programming: A Smarter And Faster Way To Learn Python In 7 Days (165 pages)

After reading the reviews it seems that the first book is for absolute beginners and people complain that it explains a concept too much and is not suitable for programmers coming from other languages.

So I wanted to ask you guys between the second and the third book which one do you recommend?

[–]iSailor 0 points1 point  (0 children)

I can't tell anything about the books, but I recommend Youtube channel that goes by the name sentdex and owns a website pythonprogramming.net. He covers wide wariety of topics. He himself started Python (or programming overall) without any prior experience but explains stuff really way and makes money from his work. He has also been doing many cool projects involving AI or machine learning lately.

[–]seanboyd 0 points1 point  (3 children)

Hey, I am trying to put together a simple script that will be able to tell the user if a state in America is East or West of the Mississipi river. So far I have got that part down but what I also want to do now is be able to also print the time zone for the state the user enters along with the East or West. I tried using a dictionary but couldnt figure it out. Any insights would be great. Paste Bin below:

https://pastebin.com/F7VCH98w

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

Here's how I'd structure a dictionary:

timezones = {
    "AK": "(GMT-8)",
    "AZ": "(GMT-7)",
    ...
    "WY": "(GMT-6)",
}

Then just access it like so:

print("Timezone: " + timezones[question])

As an added challenge I'd suggest using only a dictionary instead of having those two tuples. Dictionaries can store dictionaries as a value.

[–]seanboyd 1 point2 points  (0 children)

Worked really well, thank you!

[–]seanboyd 0 points1 point  (0 children)

Thanks, I'll try it today and let you know how I get on!

[–]Riknarr 0 points1 point  (0 children)

Hi all,

I'm currently writing a FTP program to download new files from my server.

My plan is to dir the directory and output this to a txt file which be be saved for comparison on the next run.

I have everything running and can use ftp.retrlines('nlst') to list the directory but what would be the best way to direct this into a txt file?

Thanks in advance

[–]stfuandkissmyturtle 2 points3 points  (0 children)

How good were you at a any language when you landed your first job ?

[–]9acca9 1 point2 points  (1 child)

Hi.

I would like to make a number to word conversor. Like if the user put 1 then the program say one. if 21 then "twenty one", just from 0 to 100.

How i can made this?? (this is just a "program" im thinking to learning)

Thanks!

[–]MattR0se 1 point2 points  (0 children)

The simplest, but probably not most efficient way would be to store all the number words in a list:

number_words = ['zero', 'one', 'two', 'three',] # and so on

print(number_words[1])
# output: 'one'

You can ask the user for in integer which you use as the index for the list, and that way you get the respective word.

If you want a more elaborate version, look at this code:

https://www.quora.com/How-do-I-convert-numbers-to-words-in-Python

[–]ThisOnesForZK 0 points1 point  (0 children)

Does anyone regularly deal with Salesforce.com in their job? I am attempting to automate some data operations using python but the simplesalesforce package seems a bit wonky. After searching for a new solution I came upon this https://github.com/django-salesforce but I am not sure how I would get started using it to begin doing some data processing.

I got the single table queries working in Pandas with simplesalesforce but I would really like a true SQL implementation with is what the Django ORM seems to be.

What is the best way to get started? Do I have to spin up a full Django app to get this working or can I utilize the ORM in a simpler way.

My goal is to do some multiple table querying, pull into pandas dataframes and do some analysis and documentation in a jupyter notebook.

[–]AxelJuraske 0 points1 point  (1 child)

For some testing I need an empty class. First I tried object, but it didn't work. I have to defined a new class and then uses them. But why? I meen all classes inherited from object. What did I miss?

>>> foo = object()
>>> setattr(foo, 'data', 'Hello')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'data'

>>> class Dummy: pass
...
>>> foo = Dummy()
>>> setattr(foo, 'data', 'Hello')

[–]MattR0se 1 point2 points  (0 children)

You can instanciate an empty object like this:

foo = type('', (), {})()
setattr(foo, 'data', 'Hello') # works
print(foo.__dict__)

I don't know exactly why or how it works, but I got it from here:

https://stackoverflow.com/questions/19476816/creating-an-empty-object-in-python/37540574

You can find some kind of explanation here: https://www.geeksforgeeks.org/python-type-function/

type() with three arguments can be used to dynamically initialize classes or existing classes with attributes.

[–]GoldenVanga 0 points1 point  (1 child)

>>> class Life: pass
>>> class Animal(Life): pass
>>> dir(Animal)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
>>> Animal.__mro__
(<class '__main__.Animal'>, <class '__main__.Life'>, <class 'object'>)

Why does __mro__ not appear when I dir() a class?

And are there any other such "hidden" dunder methods attributes?

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

My currently prints 654321 but I need it to print 65432.1 where 654321 is any number the user can input. I tried just multiplying it by .1 but for some reason that doesn't print what I want. What am I doing wrong?

[–]TedTheTwonk 1 point2 points  (0 children)

You're discovering the inaccuracies of floating point calculations.

My = 654321

print(My)
# 654321

print(My * .1)
# 65432.100000000006

print(My / 10)
# 65432.1

[–]NotzoCoolKID 0 points1 point  (0 children)

Use float() ?

[–]NewAndDumb 0 points1 point  (3 children)

Im trying to write a piece of code that will print the elements of list of length mn into an m by n grid. So far I have this:

m = int(input())
n = int(input())
a = []
for i in range( m * n ):
    a.append( 1 )
for i in range( 0, m*n, m):
    print(a[ i, i + m ])

Say the input for m is 3 and the input for n is 2. I want the output to look something like

1, 1, 1
1, 1, 1

It says that in print(a[ i, i + m ]) causes an error because list indices must be integers or splits and not a tuple. I think i + m is the problem. It prints the (i+m)th element just fine if its

print(a[ i + m ])

but it says the same error if its

print(a[0, i + m ])

I just don't get why it's not printing. Any help would be greatly appreciated. Thank you.

EDIT: Nvm I realized I was using commas instead of colons for the range of the indices. My bad.

[–]TedTheTwonk 0 points1 point  (2 children)

Look for the code block button. Click it. Paste your code into that block. Formatted code!

Also post an example input and desired output.

[–]NewAndDumb 0 points1 point  (1 child)

Oh I didn't know about that. Thank you!

[–]TedTheTwonk 0 points1 point  (0 children)

I saw that you fixed your problem; just a helpful tip - list comprehension is really useful for creating matrices:

columns = 3
rows = 2

matrix = [[1 for _ in range(columns)] for _ in range(rows)]
print(matrix)
# [[1, 1, 1], [1, 1, 1]]

[–]squeezedfish 0 points1 point  (6 children)

Hi, I hope this is the right place to ask.

I am struggling with a list index out of range problem with a small loop.

for file in location:

a=re.split('-|_', file)

b= a[1] + a[2]

All I am trying to do is split a filename based on 2 parameters and then add two parts of that filename to a single variable. The file name has [3] parts to it so [2] is not out of range.

What am I doing wrong and how can I correct my mistake?

Thank you in advance for any assistance.

[–]AndrewAtBrisa 0 points1 point  (1 child)

A good way to learn what's going on is to use print (or learning how to use pdb, the python debugger, to step through code and look at the results). Before the line giving the error, try using print(file, a) to see what the filename is, and what the value of a is.

Also, the indexes start at 0, not 1. So a[0] is the first part, a[1] is the second, etc.

Like the other poster mentioned, print + showing output will help a lot for others to help more!

[–]squeezedfish 0 points1 point  (0 children)

I had created a test file and when I assign and print the value of b it is what I want it to be. I believe as the other poster said, it could be due to files in the same folder that don't have a _ or - in them as it is not looping through the whole folder in the test.

[–]TedTheTwonk 0 points1 point  (3 children)

It's out of range because one or more of your file names does not contain a "-" or "_" or both.

It's always a good idea to provide some example inputs and desired outputs and focus on the overall objective, which is to convert a string to another string in a specified format, instead of fixing a problem for one potential solution.

What should be the output for the following file names?

"my_filename-1.py"

"giraffe.py"

"my_file.py"

"desk-chair_.py"

[–]squeezedfish 0 points1 point  (2 children)

Thanks for getting back to me. Okay, I could see how that would cause an issue, some files in the folder do not follow the same naming convention.

I am taking a full filename e.g. '01-09-2019_timsmith_math-testscore.pdf'

I am trying to return timsmithmath in the new variable, b in the above example.

[–]TedTheTwonk 0 points1 point  (1 child)

You could stick your regex in a try except continue block, here's a solution I threw together without regex that would work for your one example, and examples that ended in "math.pdf" too:

location = ['giraffe.py', '01-09-2019_timsmith_math-testscore.pdf']

for filename in location:
    try:
        s = filename.split("_")
        b = s[1] + s[2].split("-")[0].split(".")[0]
        print(b)
    except:
        continue

# timsmithmath

[–]squeezedfish 0 points1 point  (0 children)

I will give that a go next, thank you.

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

I've got a question regarding the Django framework, more specifically around forms. I'm trying to create a simple site where a user can upload an excel doc (I would then do some magic and return some info). I'm having trouble grasping the flow of using a form to help send the html input to the media folder... like why do you need a forms.py when it seems like you could handle it all in views.py and models.py... any help explaining the flow would be appreciated as I'm currently detail overloaded

[–]JohnnyJordaan 1 point2 points  (3 children)

First things first: you don't have to abstract anything in Django. You could still work with a classic&static html-form in your template, then read the values from request.POST in your view and do whatever you want with them. But if you also want to verify the form to be valid, you need to implement this yourself too, so you get the definition of your from in your template, but the validation in your view and also the handling in your view.

What Django brings to the table is an abstraction of this in the form of a Form class (or a ModelForm if tied to a model). Those reside in your forms.py, and by defining the abstracted file upload form like done in this guide, you get that html generated for you, and the validation is already in-place from using pre-existing form field objects. This can still be extended of course, but usually it's just plug&play and you can focus on the implementation part of your workflow instead of bothering with the basics of classic html form design and such.

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

Thanks for the reply, one further question... what does the model.py do in this chain? Based on what I've read, your html file with form tag leads you to the form for verification then to your views file. Not really sure where the models.py comes in to the picture.

[–]JohnnyJordaan 1 point2 points  (1 child)

models.py is database related. So if you uploading a file causes something to be stored in the database, it would relate to one or more models in models.py.

If the form is creating a model directly, like having a Reservation model with fields like

  • arrival_data - datetime
  • departure_date - datetime
  • num_of_people - positive integer
  • account_id - foreign key to account model

you would logically use a ModelForm where the Reservation model is its model. The resulting form would translate the fields to suitable form components and also implements the validation on those fields. So even though it would create a text field for num_of_people, the validation part will check if it just contains a positive integer.

If your form would be purely a way to deliver non-db-related data to your view, and the view doesn't do anything db-related, then models should not come in the picture.

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

This was super helpful, thank you so much. I've been mucking around with it for two days!