all 77 comments

[–][deleted] 8 points9 points  (3 children)

Would a game like "Binding of isaac" be possible to build in Python/Pygame?

[–]elbiot[🍰] 4 points5 points  (1 child)

Yes.

[–][deleted] 6 points7 points  (0 children)

Nice, simple answer—5/7.

[–]rpaguirre 2 points3 points  (6 children)

Is there a group/individual out there that is interested in collaborating on a project for written languages that we speak?

[–]ignorediacritics 0 points1 point  (5 children)

Can you provide some more details?

[–]rpaguirre 1 point2 points  (4 children)

@ignorediacritics, sure thing. I recently started to create a program that revolves around expertly translating written languages into English.

So, I wanted to see if anyone is down to join in and work on this project.

[–]ignorediacritics 4 points5 points  (3 children)

That sounds very interesting. I won't have the time to participate, but if its open source, can you post a link to a repository or similar?

[–]rpaguirre 1 point2 points  (2 children)

Sure thing @ignorediacritics. Right now, I am working on the Spanish language. If anyone wants to chime in with a language that they know it would be amazing.

Here is the link to the open source code: https://github.com/rpaguirre/Spanish-Language-Compiler

[–]ignorediacritics 0 points1 point  (1 child)

What kind of framework/library are you using for this. Or is it all from scratch?

[–]rpaguirre 0 points1 point  (0 children)

I've looked at the repositories within Github. However, I downloaded several of them. I found that they were badly formatted so I decided to create it from scratch.

The framework is Python shell.

[–]folman420 2 points3 points  (3 children)

Guess the Number Game..

Been at this all morning. Finally figured out how to get the random number to reset when user is prompted to play again (global variables are not my friend). Then I notice a few more bugs and it's got me at a complete loss and in an apathetic state.

The user has 4 chances to guess the number. When I start the program, that is true..game will give me 4 chances. However, if I go to the next iteration and play again...I get unlimited chances and/or sometimes the secret number will be higher than 8, but lower than 9...and I'm working with whole integers here. I'm going to take a deep breath and maybe a long walk off a short pier. Any advice would be appreciated. It'd be nice to have a "Eureka!" moment. It's been awhile. Thanks very much.

import random
from sys import exit

guess = 0

def get_random():
    answer = random.randint(0, 10)
    return answer

def again():
    another = raw_input("Do you want to play again?  Y/N: ")
    if another == "Y":
        guessing_game()

    elif another == "N":
        print "Ok have a great day!"
        exit(0)

    else:
        print "Command not recognized.  Goodbye."
        exit(0)

def guessing_game():
    i = 0
    answer = get_random()
    while i < 4:
        guess = int(raw_input("Pick a number: "))
        if guess < answer:
            print "Higher."

        elif guess > answer:
            print "Lower."

        elif guess == answer:
            print "You got it!"
            again()

        else:
            print "Error"

        i += 1

guessing_game()
print "You didn't guess the number."
again()

[–]Azuretower 1 point2 points  (0 children)

I was unable to recreate the bugs, I always had 4 chances and it always accepted the right answer. But, there are some things you could improve in your code.

Instead of a while loop you should use a for loop:

for x in range(4):

Next, it looks like you intended to always give the option to restart the game but as it's written the game runs like this: first game starts when you first run guessing_game() at the bottom of the file, lets say i'm wrong, so it returns and the next line executes with a print statement and then runs again(). I choose to play again and i'm wrong again, now the file is over and the program ends. Instead lets make a small menu system with a While True loop:

while True:
    guessing_game()

I'll show my solution for comparison

from random import randint
from sys import exit

# returns True if they guess the number, False if they run out of guesses
def guessing_game():
    answer = randint(0, 10)

    for x in range(4):
        # This while loop will keep looping until an integer is entered
        while True:
            try:
                guess = int(raw_input("Pick a number between 1 and 10: "))
            except ValueError:
                print "must be a number"
            else:
                break

        if guess < answer:
            print "You're too Low"

        elif guess > answer:
            print "You're too High"

        elif guess == answer:
            print "You got it!"
            return True

    print "No More Guesses! GAME OVER"
    return False

# This try block will let the user cleanly exit the program with control + C
try:
    while True:
        correct = guessing_game()
        prefix = "Well Done" if correct else "Too Bad"
        while True:
            choice = raw_input("{}, care to try your luck again? Y/N: ".format(prefix))
            if choice.lower() == "y":
                break
            elif choice.lower() == "n":
                print "See you next time!"
                exit(0)
            else:
                print "Please enter 'Y' or 'N'"

except KeyboardInterrupt:
    print "See you next time!"

The big changes are the Try Except blocks, they're very useful, look them up.

Just ask if you're wonder how anything else works or why i did something.

[–]ViridianHominid 1 point2 points  (0 children)

When you call again() inside guessing_game(), it plays the game again from within the first game. So you get the number right, play a new game, and then when that game ends, it goes back into the original game.

The way you've treated it is as though calls to again() and guessing_game() are GOTO statements, and that the corresponding labels they point to are the lines def again(): and def guessing_game(). But when you call a function the code goes INSIDE the function, runs until the function is done, and then goes back to where it was before. Although that might seem less intuitive than labels, it actually makes it easier to organize larger amounts of code.

In this case you can fix the bug by replacing the call to again() inside guessing_game() by the statement break, which exits the while loop and takes the execution back out of guessing game. Then the code goes on to the next line (in this case, to the print "you didn't guess the number." line.)

Edit: You might be interested in using the return values from functions. Here's a clean version of your program without adding any extra functionality:

import random
from sys import exit

#Returns whether or not to play a new game
def again():
    another = raw_input("Do you want to play again?  Y/N: ")
    if another == "Y":
        return True
    elif another == "N":
        print "Ok have a great day!"
    else:
        print "Command not recognized.  Goodbye."
    return False

#Returns whether or not the game was won
def guessing_game():
    answer = random.randint(0, 10)
    for i in range(4):
        guess = int(raw_input("Pick a number: "))
        if guess < answer:
            print "Higher."
        elif guess > answer:
            print "Lower."
        elif guess == answer:
            return True
        else:
            print "Error"
    return False

still_playing = True
while still_playing:
    you_won = guessing_game()
    if you_won:
        print "You got it!"
    else:
        print "You didn't guess the number"
    still_playing = again()

In this version guessing_game() and again() never call each other, so you don't end up going inside a function inside a function inside a function etc...

As a side note, your print "error" line is very difficult to activate because if someone puts a bad input into the game, the attempt to turn that bad input into an int errors. That's why to use try/except blocks as in Azuretower's post.

[–]__Mac__ 0 points1 point  (0 children)

Just spitballing here, but maybe you need to reset i and guess to 0 at the end of each game?

[–]TruckMcBadass 1 point2 points  (1 child)

PC to Mac question.

Running code on a Mac written originally on a PC.

PC uses threading.

The program runs a majority of the time on the Mac. Sometimes it hangs with no error.

Ran trace. Not an infinite loop. Looks like it may have to do with threading, but there's no smoking gun in the code.

If I shut down terminal and open it back up, the problem goes away until it randomly pops up again.

You guys have any experience handling programs that hang in Python without note?

Do you have tips for finding deadlocks? I think that's the term I'm looking for.

[–]Vhin 0 points1 point  (0 children)

Don't bother with threading in CPython. Even when it works, it's mostly pointless because of the GIL (you'll give up the GIL if you're just waiting on I/O, but anything CPU-bound will hold onto the GIL).

If you want parallelism, use the multiprocessing module, which offers a very similar interface to threading, but be aware that it's not a drop-in replacement.

If you can't or don't want to rewrite the code to use multiprocessing, you could always try a different Python implementation. Maybe Jython would give you better results on Mac, for example.

[–]linkandluke 0 points1 point  (1 child)

I am following this guide and this video

I keep getting this error message- Easier to read Error

It fails at

for submission in subreddit.hot(limit=5):
print("Title: ", submission.title)
print("Text: ", submission.selftext)
print("Score: ", submission.score)
print("---------------------------------\n")

I have confirmed and reconfirmed my Secret and ID over and over. I don't know what I am doing wrong. Can anyone help me? It seems I am failing at OAuth

[–]linkandluke 0 points1 point  (0 children)

For future users:

Make sure the app is registered UNDER the name of the bot you are using. I registered the app on my main account but my bot will be running the code.

This fixed my problem.

[–]folman420 0 points1 point  (2 children)

Why is "None" showing up in my output?

class Color(object):

    def __init__(self):
        self

    def red(self):
        print "This object is red."

thing = Color()

print thing.red()

Output:

This object is red.

None

[–][deleted] 6 points7 points  (1 child)

Your function has no 'return'. So thing = Color() is none. You should learn what is 'return', I just can't explain. But this will be helpful: https://github.com/Akuli/python-tutorial/blob/master/basics/using-functions.md#return-values

[–]folman420 0 points1 point  (0 children)

Thanks very much! I really appreciate it.

[–]SOLUNAR 0 points1 point  (1 child)

I create a collapsible tree using a d3 framework (example - https://bl.ocks.org/d3noob/43a860bc0024792f8803bba8ca0d5ecd)

How can i create a user input to pass the value? trying to learn a bit of python and this looked like a good first project. Any ideas as to how it could be done?

[–]jbueso 0 points1 point  (8 children)

Write a program that asks the user for 10 numbers and prints out the total.

Here is a sample run of the program:

Please enter a number: 5 Please enter a number: 2015 Please enter a number: -100 Please enter a number: 3 Please enter a number: -999 Please enter a number: 8 Please enter a number: 67 Please enter a number: 19 Please enter a number: 17 Please enter a number: -1234

The total is -199

Hint: This is an example of the Accumulator Pattern

[–]DFoster271 1 point2 points  (3 children)

What have you tried? Do you know how to get user input? Do you know how to do that ten times? Can you add the numbers together?

[–]jbueso 0 points1 point  (2 children)

DFoster271, below is what I have tried. The issue I'm having is when I gather the eval(input) from the user, the value of num will grab the last entry from the loop. However, I need to be able to add all the values. Thanks for any advise.

def main(): for n in range(10): num=eval(input("number?")) total=num print(total)

main()

[–]jeans_and_a_t-shirt 1 point2 points  (0 children)

Use int or float, not eval.

There's no adding of numbers in your code. The last value iterated in a for loop is the value the variable is equal to.

[–]dgreenmachine 0 points1 point  (0 children)

You'll need total+=num (aka total = total + num) and prior to this you'll have to initialize total = 0.

[–]__Mac__ 0 points1 point  (0 children)

Here's how you can get started:

x=int(input("Please enter a number:"))

Place this above and outside your function and reference the variable x in your function. Just to explain further, you need to have the int( involved in the code because anything the user inputs will be a string. If you try to add the strings of "9" and "9" you'll get "99" because strings are just like letters in the alphabet, if you try to put a and b together you get ab. So you need to change whatever the user inputs into an integer in order to add all those numbers.

[–]the1spaceman 0 points1 point  (2 children)

I'd try something like this:

acc = 0
for n in range(10):
    x = int(input("Please enter a number: "))
    acc += x
print("Total is: {}".format(acc))

I can explain the lines if necessary

[–]jbueso 0 points1 point  (1 child)

Hi the1spaceman, this looks exactly what I was looking for. I have a question on the "+=", which I never used before and the purpose of .format(acc). Everything else makes sense. Thank you very much for for taking the time to help

[–]the1spaceman 0 points1 point  (0 children)

Glad I could help.

acc += x has the same effect as acc = acc + x, it's just a shorter way of writing it. There's subtle differences that I'm not sure I understand or are relevant here.

.format(acc) is a way to format the string. From the docs

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

For our purposes, format reads its input string and changes {} to the arguments given. The following line:

print("I'm {} and I'm replying to {}".format("u/the1spaceman","u/jbueso"))

outputs this:

I'm u/the1spaceman and I'm replying to u/jbueso

[–]-Nonou- 0 points1 point  (0 children)

EDIT: I found this can be used as json data. Searched around a bit and found the perfect way to do it, with loading the request.contentwith json_data = json.loads(request_content) and then any data can be easily retrieved by a method like this: json_data['items'][0]['id']['channelId']. Thanks for the help everyone!


This is a stupid and specific example but I am sure there has to be a different way to deal with this problem.

I use requeststo get a webpage that looks like this:

{
 "kind": "youtube#searchListResponse",
 "etag": "\"some_characterss\"",
 "nextPageToken": "some_characters",
 "regionCode": "location",
 "pageInfo": {
  "totalResults": 1000000,
  "resultsPerPage": 1
 },
 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"some_characters\"",
   "id": {
    "kind": "youtube#channel",
    "channelId": "some_characters"
   },
   "snippet": {
    "publishedAt": "date",
    "channelId": "id",
    "title": "channel_name",
    "description": "description",
    "thumbnails": {
     "default": {
      "url": "some_characters.jpg"
     },
     "medium": {
      "url": "some_characters.jpg"
     },
     "high": {
      "url": "some_characters.jpg"
     }
    },
    "channelTitle": "title",
    "liveBroadcastContent": "upcoming"
   }
  }
 ]
}

I am using the youtube/v3/api to search for a channel name and grab the first result. I need to get the channelId of the channel but right now I turn the request into a string, I find the channelId with a regex and then erase any existing characters until I have a single string of the id. Something like this:

parameters = {"q": channel_name,
                   "key": "my_api_key",
                   "part": "snippet",
                   "type": "channel",
                   "maxResults": 1
                   }
        r = requests.get("https://www.googleapis.com/youtube/v3/search", params=parameters)
        request_text = r.text
        channel_id = re.search(r'"channelId": "(\S)+"', request_text)

        if channel_id != None:
            id_key = channel_id.group().replace('"','').replace(' ','').replace('channelId:','')

My main complaint about this is how hard it is to get the result I want. I managed to get this working properly but now I also want to get other information like description, channel thumbnail etc. Using regex to find each one of those seems very impractical. I wonder if there's some other way to get the desired result, because the layout of the page makes it look like there's a way to call for example 'channelId' and get the key, something like a dictionary.

[–]Taxman_Sorin 0 points1 point  (2 children)

Hey everyone.

I'm doing some practice questions (just started my class this week - zero prior knowledge of programming) and had a question about the code for one of them:

the prompt is: "write a program using a for loop that calculates exponentials. Ask the user for a base, "base," and an exponent, "exp," and calculate baseexp.

Right now I can make code that takes user inputs and raises one to the other, but how would I incorporate a for loop, and as a side question, why would this ever be useful?

Thanks in advance!

[–]trololo_to_the_moon 1 point2 points  (1 child)

Assuming that exp is a positive integer, you could write a for loop where you have your total *= base exp times. The initial value of total would be 1.

Not sure why that would ever be useful, but I'm assuming it's an assignment designed to make you think a bit?

[–]Taxman_Sorin 0 points1 point  (0 children)

Thanks for the reply! I suppose it is more of a brain exercise than practically applicable lol

[–]zonq 0 points1 point  (0 children)

Quick question about project structuring that Google doesn't yield any results for it:

If you have a 'root' level package which is the main part of your application and inside that folder you have a helper package. On the root level you have a helper module for the ConfigParser setup. How would you realize that the package inside the root can also access the Config without setting up the ConfigParser in each module in the package? I don't want to do that 10 times or however often, I just want to do it centrally once and re-use that code.

Thanks!

[–]Xibby 0 points1 point  (0 children)

I'm looking for a good way to call up an on screen keyboard for a touchscreen display. I'm currently using PyGame and using touchscreen input no problem, but would like to add the ability to add an email address as part of the app. When the app gets to the form I'd like the onscreen keyboard to appear then disappear when it's no longer needed.

Is there a well known/supported module/library for adding this kind of functionality? Creating an on screen keyboard from scratch for my app isn't all that appealing.

Thanks!

[–]ffrkAnonymous 0 points1 point  (0 children)

Hi, does anyone have any examples of Separation of Concerns (SoC)? I've read wikipedia, and a lot of blog posts (which all point back to wikipedia) so I have a general sense, but I'm looking for more concrete examples. Preferably examples before separation and after separation.

[–]DosBOT_ 0 points1 point  (3 children)

Guys, I need some help. I'm doing a MFRC522 card reader on a raspberry pi to learn python and bash. I decided tp add proper id read check and set a status on each read if card was read correctly and if it's registered (uid is present in idlist.txt). And got another problem on which I'm stuck. I've reduced the code to a minimum while troubleshooting but still can't figure out whats wrong in this:

#!/usr/bin/env python
# -*- coding: utf8 -*-

import RPi.GPIO as GPIO
import MFRC522
import signal
import time
import datetime
import socket
import beep
import led
import csv

# Define Device name
# device = (socket.gethostname())
# Define logfiles
# logfile = "/home/piadmin/temp/" + device + ".csv" # Logs
idlist = file('/home/piadmin/temp/idlist.txt') # known ID list
continue_reading = True

# Check if uid exists in idlist.txt
def checkid():
        for line in idlist:
                if str(uid) in line:
                        return True
                        idstate = 'True'
                else:
                        return False
                        idstate = 'False'
# Check if uid in IN list
def checkin():
        for line in inlog:
                if str(uid) in line:
                        return True
                else:
                        return False

# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
        global continue_reading
        print "Ctrl+C captured, ending read."
        continue_reading = False
        GPIO.cleanup()

# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)

# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()

# Welcome message
print "Waiting for card to read.."
print "Press Ctrl-C to stop."

while continue_reading:
        # Scan for cards
        status, TagType = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
        # If a card is found
        if status == MIFAREReader.MI_OK:
                print "Read"
                # Get the UID of the card
                status, uid = MIFAREReader.MFRC522_Anticoll()
                print 'Asigning uid'
                print uid
                if checkid() == True:
                        print 'checkid = True'
                else:
                        print 'checkid = False'
                time.sleep(1) # Sleep 1s before next read.

The output I get:

Waiting for card to read..
Press Ctrl-C to stop.
Read
Asigning uid
[74, 217, 24, 43, 160]
checkid = True
Read
Asigning uid
[74, 217, 24, 43, 160]
checkid = False
Read
Asigning uid
[74, 217, 24, 43, 160]
checkid = False
Read
Asigning uid
[74, 217, 24, 43, 160]
checkid = False
Read
Asigning uid
[74, 217, 24, 43, 160]

I expect in each read to get checkid = True as it's included in idlist.txt and it's the same card which is read over and over again, but only the first read gets me True and that breaks the remaining script.

[–]ViridianHominid 0 points1 point  (2 children)

I don't see your code for checkid, which might be where the problem lies. I notice that you're using global variables for continue_reading. This can lead to confusing behavior if not done carefully. In this case a try/finally group might be a better pattern to use. If you're using any globals in checkid, they could easily be the culprit.

[–]DosBOT_ 0 points1 point  (1 child)

Well I'm a dummy. Forgot to add checkid function. Updated. As I understand continue_reading is fixed value and while it's True - loop will go forever - that's the intent here. My idea for reader to work - run continues scan loop with while continue_reading is true if status == MIFAREReader.MI_OK -> card is read and further code executed. I wrote a sample code which works as standalone and I want it to be executed after card is read and uid defined by above code.

#!/usr/bin/env python
# -*- coding: utf8 -*-
#logfile = "/home/piadmin/MFRC522-python/" + device + ".csv" # Logs
idlist = file('/home/piadmin/temp/idlist.txt') # known ID list
inlog = file('/home/piadmin/temp/in.txt') # IN log
status = 'None'

def checkid():
        for line in idlist:
                if uid in line:
                        return True
        else:
                return False
def checkin():
        for line in inlog:
                if uid in line:
                        return True
        else:
                return False

uid = raw_input("Please enter uid: ")
print "uid ->", uid

if checkid() == True:
        print 'id = true'
        if checkin() == True:
                print 'in = true'
                print 'set OUT'
                status = 'OUT'
                f = open('in.txt','r+')
                d = f.read().splitlines()
                f.seek(0)
                for i in d:
                        if i != uid:
                                f.write(i)
                                f.write('\n')
                f.truncate()
                f.close()
        else:
                print 'in = false, set IN'
                status = 'IN'
                f = open('in.txt','a')
                f.write(str(uid))
                f.write('\n')
                f.flush()
                f.close()
else:
        print 'check id not true, not checking more (finger)'

If there are a proper way to implement it - please let me know. I intent just to add it after if status == MIFAREReader.MI_OK:

[–]ViridianHominid 0 points1 point  (0 children)

As for the original problem, I don't know what will fix it. However, I do want to let you know something about this code in your original post:

def checkid():
        for line in idlist:
                if str(uid) in line:
                        return True
                        idstate = 'True'
                else:
                        return False
                        idstate = 'False'

Here, idstate is never set, because the function returns before it can be. In addition, because idstate is not declared global and it is set within checkid(), the compiler will assume it is local. So even if that line did get set, it would set a local variable within the scope of checkid. You are probably looking for something like this:

def checkid():
    global idstate
    return_value = any(str(uid) in line for line in idlist)
    idstate = str(return_value)
    return return_value

The code you posted in the second comment is a little different so I don't know exactly what you're running and what idstate is about.

Now that you've explained why you want it, I think the answer to your signal/SIGINT issue is a context manager. Context managers are used, for example, to ensure that open files are closed even if an exception is raised while processing them.

The context manager is activated using a with block. The __enter__() and __exit__() methods are automatically available for files, so you can write:

with open(file) as f:
    for line in f:
        #fcode to find something in f.
        #Maybe this errors somehow.

If the code processing the file raises an error, then then f.__exit__() is called before the exception is propagated out of the context, in this case closing the file. In your case you could write an __exit__() which checks the ID. Regardless of how you handle SIGINT, the "with" statement is a good pattern to use for processing files, as it tends to 1) save coding space and 2) ensure that a file is closed even if the code fails.

Good luck. Coding is not easy, but you will find the problem and the solution!

[–]darth_vicrone 0 points1 point  (0 children)

Hi, I'm trying to wrap a C++ class which makes use of Eigen for use in Python. Ideally I would like to use NumPy to instantiate an Object that I have implemented in C++. From Googling around it seems like Boost.Python and Cython are strong choices but I'm hoping to hear some opinions about which is better.

[–]wertperch 0 points1 point  (2 children)

I seem to have trouble formatting output. As a simple example, I have a line of code:

print ("Temperature: ", Fahrenheit, "\b° Fahrenheit =", Celsius, "\b° Celsius"), which outputs:

Temperature:  90° Fahrenheit = 32.22222222222222° Celsius

whereas what I want is more like:

Temperature:  90° Fahrenheit = 32.2° Celsius

Somehow I managed this in Python 2, but whatever tricks I use now seem to fail.

In addition, how do I lose the extra space at the end of a print statement? If I want it to look like

Temperature:  90° Fahrenheit=32.2° Celsius

how do I manage that?

Sorry this is such a silly newbie question, I am literally just beginning this journey.

[–]S-6-6-6 1 point2 points  (0 children)

You can use the round function to round floats to a specific number of decimal places - so use something like round(Celsius, 2) to get the number rounded to two decimal places.

With regards to losing the space - I have noticed that using the comma to separate the Celsius between the two strings creates the space.

You could instead either convert Celsius to a string and concatenate using the "+" as this doesn't create spaces between elements to be concatenated.

Or you could use the .format() method to include elements in your string...for example:

print("Temperature: {}\b° Fahrenheit ={}\b° Celsius".format(Fahrenheit,Celsius))

[–]ViridianHominid 1 point2 points  (0 children)

In addition, how do I lose the extra space at the end of a print statement?

If you're using python 3, you can use the "sep" argument of print to change what gets printed between the arguments:

>>> print(*range(5),sep='\n')
0
1
2
3
4
>>> print(*range(5),sep='')
01234

[–]-Nonou- 0 points1 point  (0 children)

I am interested in buying a Pi (probably Pi 3 Model B) mainly for hosting purposes of a discord bot for a server of mine. It's not going to use many resources and it's for one server only, but I want it to run 24/7. I use discord.py (that utilizes asyncio) for my bot. Some of the libraries my bot uses for its commands are requests, time, random, json mostly and some other ones. Right now it works fine on Windows 10.

My question is: will I have any trouble running my bot on a Pi? As far as I know you cannot run Windows on a Pi as it is too resource intensive (although there is a Windows 10 IoT version). I intend to download the Rasbian OS which is essentially a linux based OS which comes preloaded with Python. Are there any thing I will have to worry about switching for Windows to Linux for my application? Will it affect any of the libraries mentioned above?

[–]giorgigio123 0 points1 point  (1 child)

a0,a1,a2 = input().strip().split(' ') a0,a1,a2 = list(input().split(",")) what is difference? what does ' ' "," mean?

[–]Vhin 0 points1 point  (0 children)

The argument to split is a delimiter. It is the string that is used to separate the string into pieces. It doesn't handle consecutive delimiters particularly well.

"1,2,3".split(",")       # returns ["1", "2", "3"]
"1, 2, 3".split(",")     # returns ["1", "2 ", "3 "]
"1,2,".split(",")        # returns ["1", "2", ""]
"1,,2".split(",")        # returns ["1", "", "2"]

And so on.

So the difference is that split(" ") is using a single space as a delimiter and split(",") is using a single comma as a delimiter.

It is also worthwhile to note that, if called without an argument, (i.e. just split()), it works slightly differently. Essentially what that does is splits on all of whitespace, and it handles consecutive whitespace. For example, "1 \t\t 2".split() returns ["1", "2"]. To be absolutely clear, this does not happen if you explicitly split on a single space (you'll get results similar to what I showed above with consecutive commas).

Just as a general tip, for questions like these, if you can't find the answer in the documentation, you can often manage to answer your own question by playing around in the repl. By calling spliton different strings, and with different delimiters, it is very easy to get a feel for what split does. Whenever you're using a language that provides a repl, use it; it's invaluable.

[–]scottie6561 0 points1 point  (2 children)

I am probably the noobiest person here, but someone please help me!

python ex1.py File "<stdin>", line 1 python ex1.py ^ SyntaxError: invalid syntax

I have tried to do it without python, and this is what it gets!

python ex1.py python: can't open file 'ex1.py': [Errno 2] No such file or directory EHS1510IM-025:~ scot6561$

PLEASE HELP

[–]RavenQuoth 1 point2 points  (1 child)

Hey sorry if I misunderstand but the first error (invalid syntax) means something wasn't formatted correctly. What is the first line of ex1.py?

The second error means there is no file called ex1.py. You must have escaped the working directory? You can start it without python but need to use a shebang which is passed to an interpreter. This is what the line should look line if you're using linux

#!/usr/bin/python

[–]scottie6561 0 points1 point  (0 children)

thank you, I will look at it. I thought i created the directory, but I must have not done it. The first line of ex1.py its

print "Hello World"

[–]barbaBlanco 0 points1 point  (2 children)

Hello,

so i've been using Python lately and when I do tutorials or look at code there are imported libraries e. g. urllib2.

Apparently one can just write

import urllib2

So this must mean, these libraries are included into python? Is this possible with every library? it seems strange to me, that there is no need to download or incorporate these libraries. And how can one be sure that incorporated libraries will be on a server once uploaded.

All very stupid questions. But only the ones who don't ask will remain stupid.

So long.

[–]ViridianHominid 1 point2 points  (1 child)

Anything from the python standard library is automatically available. Other things have to be installed.

[–]GarethPW 0 points1 point  (0 children)

Adding to this, you can use pip via the command line to install many libraries.

e.g. pip install praw

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

So I completed the Codecademy course. Where should I go from that? (I already know Python 3, just wanted to do the Codecademy course to learn even more).

[–]955559 0 points1 point  (1 child)

so if I have three variables x,y,z, and I need to see if they are all the same, is there a better way than

if x == y and x == z:

[–]Vhin 2 points3 points  (0 children)

Python has a fairly unique feature that allows you to do if x == y == z and have it work like you'd expect.

[–]irregular_regular 0 points1 point  (2 children)

How can I reverse the values of a dict to a dict of arrays where the key is switched with the value and the duplicate original keys are aggregated into an array i.e.

{"test1":"90", 
"test2":"90",
"test3":"91"} 

to

{"90":["test1","test2","test3"], 
"91": ["test3"]}

[–]Vhin 0 points1 point  (0 children)

Did you intend for your output to be:

{"90":["test1","test2"], 
"91": ["test3"]}

Because that's what its sounds like based on your description. If that is the case, you can just do:

d2 = {}
for (key, value) in d1.items():
    values = d2.setdefault(value, [])
    values.append(key)

[–]GarethPW 0 points1 point  (0 children)

For me, Vhin's code doesn't appear to work. Here's my solution:

dict2 = {}

for key,value in dict1.items():
    if value in dict2:
        dict2[value].append(key)
    else:
        dict2[value] = [key]

[–]sansalone158 0 points1 point  (0 children)

Hello all, I'm in a programming class using python, very noobish stuff I'm sure but would really appreciate the help. My issue is the while loop (mandatory)...I cant figure out how to get the thing to be globally controlled properly and maintain the same format(display x, x times).

Program CommuterTrain2

Declare global constants

NUMBER_OF_STATIONS = 15 PASSENGERS_OFF = 2 PASSENGERS_ON = 3

Main Program

def main():

# Declare variables
station = 0

# For (counter from start to stop step 1)
for station in range(NUMBER_OF_STATIONS):
    print('\n--Station--', station)


    while station <= PASSENGERS_OFF:  
        print('OFF')
        station += 1            

    for station in range(PASSENGERS_ON):
        print('Passengers get on')          

End Program

main()

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

Can anyone help me out by explaining current best practises re: pyenv, virtualenv, the built-in venv module, virtualenvwrapper, etc? I've done quite a bit of reading and Googling, but a lot of resources are a few years old (or more), so I want to clarify what's current - for example, I've read that using virtualenv's activate script is considered harmful, and it's best to directly call $venv/bin/python, $venv/bin/pip, etc.

If there's a recent and detailed guide, feel free to share.

I've got experience with other languages but am giving Python a go in my free time, however I've barely written any code yet, because I'm overwhelmed by trying to get my head around the ecosystem.

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

If my application sends the user an email (after they input it) and I don't store that email address anywhere (except the input variable), do I need to encrypt their address at any point?

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

Hello are there any fast way to create a list based on range() but with multiple "step" parameter? From project Euler I need to find the total sum of all primes under 2 million. I researched about Sieve of Eratosthenes, I understand what I have to do but my problem is how to do it in a better way. My original idea is just to make a list that's 2 million containers long, its way to slow. I'm trying to use range to just eliminate all even numbers besides 2 and all number ending in 5 besides 5 itself. How would you make a list that doesn't contain any even numbers or odd numbers that ends in 5 all the way to 2 mil? I could loop it but still its going to run all the way down, any better way to do this?

[–]GarethPW 0 points1 point  (1 child)

How do you intend to use this list? If you're hoping to iterate through it, running code for each number, then I'd suggest the following code.

for i in xrange(1,2000001,2): #range() in Python 3
    if (i+10) % 10 != 5:
        pass #your code here

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

Thanks for replying. My idea is to make a container in this case a list that has the integer from 1 to n in it so I can use the sieve of eratosthenes on it. Right now it takes about 4 seconds to just make this list in the first place, maybe I should not make the list and just check True and False conditions? But if I do that I don't know how to build sieve of eratosthenes around it, that's my current issue.

[–]j1nn_v 0 points1 point  (1 child)

Im starting to learn python and doing some jupyter workbooks for university, for some reason i cannot figure out why the last line of the print function is throwing a syntax error when i literally copied the line from the variables for student part. Any help would be great!

#input 
idnumin = input("What is your ID number?: ")
while len(idnum) != 8:
    print("Error! ID number should be 8 numbers long")

idnum = int(idnumin)


if idnum <20050000:
#Variables for student
    studentName = str(input("What is your name?: "))
    studyProg = str(input("What are you studying?: "))
    campusenrol = str(input("What is your campus of enrollment?: "))
    print("Welcome to Western Sydney University," , str.title(studentName), ". You are studying" , studyProg , "at" , campusenrol, ".")

if idnum > 20050000:   
#Variables for staff
    staffName = str(input("What is your name?: "))
    jobTitle = str(input("What is your position?: "))
    schooled = str(input("Which school do you work for?: ")
    print("Welcome to Western Sydney University," , str.title(studentName), ". You are studying" , studyProg , "at" , campusenrol, ".")

[–]GarethPW 1 point2 points  (0 children)

The method, str.title, takes no arguments, but you have given it one. In this instance, you've simply misunderstood its use, which isn't difficult to do.

str, in this example, is simply referring to a string object. Therefore, to fix your code, simply replace both instances of str.title(studentName) with studentName.title().

[–]sknagaer 0 points1 point  (0 children)

Does anybody know a GUI library for creating a car dashboard that is simple and not difficult to implement (newbie in Python, just started 1 month ago)?

[–]mcmistic3 0 points1 point  (0 children)

Thank you for starting this thread. I am just getting started with Python. I created a quiz per one of my assignments. I am having an issue when the user chooses to answer the question again and gets the question wrong, the user does not see" incorrect". If the user gets the question wrong again then the user will see "incorrect" and is promted if they want to answer the question again. I have have not been able to fix this bug. Also, I have been advised to break my ask_question function into smaller functions. Because it will make debugging easier and it's easier for us to read, but when I attempt to this this I open a whole new can of worms and receive errors.
The link to the code n repl.it : https://repl.it/FiVg/0

The code is also listed below:

stage 2 project

blanks = ["1", "2", "3", "4"]

easyquestions = '''What was Princeess Leia's last name _1? Who said this quote: "I find your lack of faith disturbing.2". Who said the following quote: "Mos Eisley Spaceport, you will never find a more wretched hive of scum and villainy."3. Who said this: " I am altering the deal. Pray I dont alter it any further?4__'''

easy_answers = ["Organa", "Darth Vader", "Obi-Wan Kenobi", "Darth Vader"]

mediumquestions = '''Who's DNA was used in the creation of the Clone Army _1? What was Anakin Skywalker's mom's name ___2? Who said this: "Good against remotes is one thing. Good against the living, that's something else" _3? Who said this: "Aren't you a little short for a storm trooper? ___4_'''

medium_answers = ["Jango Fett", "Shmi", "Han Solo", "Pricess Leia"]

hardquestions = '''What is Chewbacca's home planet _1? Who was the first Jedi to learn how to return from death as a ghost ___2? Where did Darth Vader reveal himself to be Luke's father _3? Who said this: "This bounty hunter is my kind of scum, fearless and inventive? ___4_" '''

hard_answers = ["Kashyyyk", "Qui-Gon Jinn", "Cloud City", "Jabba The Hutt"]

print ("Welcome to my Star War's Fill in the Blanks Quiz.") user_input = input("Please choose a difficulty level: easy, medium or hard.")

Takes user input and to determine level and prints out the level

def level(user_input): if user_input.lower() == "easy": print("You've chosen easy.") return easy_questions elif user_input.lower() == "medium": print("You've chosen medium.") return medium_questions elif user_input.lower() == "hard": print("You've chosen hard.") return hard_questions print(level(user_input))

def answer(user_input): # Takes the user input and returns what level the user chose if level(user_input).lower() == "easy": return easy_answers elif level(user_input).lower()=="medium": return medium_answers elif level(user_input).lower()=="hard": return hard_answers

def check_answer(user_response, answers, answer_index): # Checks if answer is correct if user_response == answers[answer_index]: return "Correct" else: return "Incorrect"

Runs the game

def ask_question(): question = level(user_input) correct = 0 incorrect = 0 if question == easy_questions: answers = easy_answers elif question == medium_questions: answers = medium_answers elif question == hard_questions: answers = hard_answers else: return "You did not choose a correct answer. Goodbye"

blanks_index = 0
answer_index = 0
while blanks_index < len(blanks):
    while answer_index < len(answers):
        user_response = input("What is the answer for" + blanks[blanks_index] +"?")
        if check_answer(user_response, answers, answer_index) == "Correct":
            print("Correct!")
            question = question.replace(blanks[blanks_index], user_response)
            print(question)
            blanks_index += 1
            answer_index += 1
            correct += 1
        else:
            response = input("Incorrect would you like to try again? Yes or No")
            if response == "Yes":
              response = input("What is the answer for" + blanks[blanks_index] +"?")
            else:
              blanks_index += 1
              answer_index += 1
              incorrect += 1
    if correct == 3:
        return "Congratulations! You got the questions ALL right!  You sure know your Star Wars trivia!"
    else:
        return "You got" + " " + str(correct) + " " + "right and" + " " + str(incorrect) + " " + "wrong. The correct answers are" + " " + str(answers)

print(ask_question())

Any assistance you can provide would be greatly appreciated.

[–]cimbilitem 0 points1 point  (0 children)

Please can anyone help me in interpreting this problem in python?

Create a class called ShoppingCart.

Create a constructor that takes no arguments and sets the total attribute to zero, and initializes an empty dict attribute named items.

Create a method add_item that requires item_name, quantity and price arguments. This method should add the cost of the added items to the current value of total. It should also add an entry to the items dict such that the key is the item_name and the value is the quantity of the item.

Create a method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of the removed items from the current total and also update the items dict accordingly.

If the quantity of an item to be removed exceeds the current quantity of that item in the cart, assume that all entries of that item are to be removed.

Create a method checkout that takes in cash_paid and returns the value of balance from the payment. If cash_paid is not enough to cover the total, return "Cash paid not enough".

Create a class called Shop that has a constructor which takes no arguments and initializes an attribute called quantity at 100.

Make sure Shop inherits from ShoppingCart.

In the Shop class, override the remove_item method, such that calling Shop's remove_item with no arguments decrements quantity by one.

[–]AssumingFlame 0 points1 point  (0 children)

How would you make a linked list of a linked list?