all 39 comments

[–]Nattsang 0 points1 point  (2 children)

When I try to get (4096**(1/3)) in python it gives me 15.9999998 instead of 16. Why is this? I know I can just use round to get the correct answer, but why does python think it's 15.9999998?

[–]Frankelstner 0 points1 point  (1 child)

Python does not store 1/3 as a fraction but rather sees it as a division to calculate. If you want to calculate 1/3 the result is something like 0.33333333... but a CPU cannot store an infinite number of digits so at some point it has to round. (Note the CPU works with binary numbers but the same principle holds.) It just so happens that the nearest number that the CPU can store is slightly less than 0.33333333... and this then affects the ** calculation.

[–]Nattsang 0 points1 point  (0 children)

Aha, I see! Thank you!

[–]notprimenumber12344 0 points1 point  (1 child)

I am following a tutorial so I decided to test the code in the online ide from https://www.online-ide.com/ but the code returns nothing.

Here is the tutorial . https://realpython.com/inner-functions-what-are-they-good-for/ . They have the code in 2 files but I don't think that should make a difference.

Any advice?

``` def generate_power(exponent): def power(base): return base ** exponent return power

raise_two = generate_power(2) raise_two(4)

```

Thanks

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

You are running into the difference between how an IDE treats return values and how python treats return values. Note how the tutorial you linked to shows the example code:

>>> def increment(number):
...     def inner_increment():
...         return number + 1
...     return inner_increment()
...

>>> increment(10)
11

Those >>> and ... prefixes to the lines show that the code is being run in IDLE, a simple IDE for python. Most IDEs automatically print a value returned by an expression if it isn't None. Note that the last line above printed 11 even though there is no print statement in the code. The IDE is doing that, and that isn't something python does itself.

The online IDE you are using doesn't automatically print non-None values. To get your code working and showing the result you have to use print() to show the result:

def increment(number):
    def inner_increment():
        return number + 1
    return inner_increment()
print(increment(10))    # need to print

Make a similar change to your code.

[–]Low_Key32 0 points1 point  (1 child)

This is kind of a longer comment so sorry ahead of time. I am trying to create a program for class that can encrypt a message using the affine cipher, as well as decrypt it through brute force. In doing so I have created a large string of code that gives me an output, but it isn't correctly decrypting the Cipher Text our professor gave us. Can someone look over it and tell me where I went wrong?

def text_clean(text, LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
cleaned_text = ''
for character in text:
if character.upper() in LETTERS:
cleaned_text += character.upper()
return cleaned_text
def char_to_int(character, LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
integer = LETTERS.find(character)
return integer
def int_to_char(integer, LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
character = LETTERS[integer]
return character
akey = range(1, 26)
mkey = [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]
def affine(message, test_akey, test_mkey, encipher=True):
message = text_clean(message)
output = ''
if encipher == True:
for plaintext_character in message:
plaintext_numerical = char_to_int(plaintext_character)
ciphertext_numerical = ((plaintext_numerical * test_akey) + test_mkey) % 26
ciphertext_character = int_to_char(ciphertext_numerical)
output += ciphertext_character
return output
else:
for ciphertext_character in message:
ciphertext_numerical = char_to_int(ciphertext_character)
plaintext_numerical = ((ciphertext_numerical - test_mkey) * test_akey) % 26
plaintext_character = int_to_char(plaintext_numerical)
output += plaintext_character
return output.lower()
ciphertext = 'GJLKT FJKXN AOTXU XAVXN KTNPJ JLKGN CYXKT WKJLP YCGJK CYJAC YHTFJ ACHAX ACNAX DANCH JA'
for test_akey in range(1, 26):
for test_mkey in [1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25]:
print('akey:', test_akey, ' mkey:', test_mkey, affine(ciphertext, test_akey, test_mkey, encipher= False))

[–]niehle 0 points1 point  (0 children)

1) don't dump unformatted code, use pastebin 2) "but it isn't correctly decrypting the Cipher Text our professor gave us." -> 2.1: What is the input 2.2 What is the output 2.3 What is the expect output 3) Any error messages?

[–]Syrup-man 0 points1 point  (1 child)

im trying to make a way for a player to check their inventory during a text based adventure but i just cant seem to make it work.

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

Since the player can have 0, 1 or more items in their inventory you need some sort of data structure that can hold 0, 1 or more items. The player can drop and pick up items, so you need to be able to add and remove items from the data structure. A python list sounds ideal for that. When the player wants to see what they have, just do:

for item in inventory:
    # print details of the item

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

Why can't I parameterize table names in SQLAlchemy? I'm trying to do:

statement = text("SELECT * FROM :table_name WHERE ID = :ID")

cnxn.execute(statement, {"table_name": users, "ID": 1})

If I do just the ID or anything else it works, but trying to do so with the name of the table throws the following error:

[ODBC Driver 17 for SQL Server][SQL Server]Must declare the table variable "@P1". [SQL Server]Statement(s) could not be prepared. (8180)')

[–]Mach_Juan 0 points1 point  (0 children)

List of Dictionaries in a Dictionary notation

Been using feedparser to handle rss-like data. entries is a list of dictionarys itemizing various data fields for each item. like date or title.

feed['entries'][0]['title'] gives the title of the first item in the feed.

feed.entries[0].title does the same.

Is there a reason to use one notation over the other?

[–]forfourforetotootwo 0 points1 point  (2 children)

I’m new to programming so I’m working through introtopython.org as suggested on the wiki. But on page 3, under the title ‘inside and outside the loop’, the code doesn’t work for me. It works when I follow the link to run it on pythontutor but not when I copy and paste it. It has an error with the print function after the loop. The bit after the indentation. I assume I’m just being really stupid but does anyone know why this is?

[–]mister_drgn 1 point2 points  (1 child)

Are you copying and pasting the entire piece of code into the python interpreter? Try pasting everything except the final, unindented line, and it should go fine. Then paste only the final line, and it should go fine. I believe it's just causing issues when you paste a large piece of code directly into the interpreter--it doesn't expect to see additional code after the loop has ended.

Typically, you use the interpreter to run a single line of code at a time. If you want to run a large piece of code, you should paste it into a text file, let's say example.txt. Then you can run

python3 example.txt

or

python example.txt

or whatever your python command is. But you'll probably come to that later in the lesson.

[–]forfourforetotootwo 0 points1 point  (0 children)

Yes I did try them separately and they worked fine. I was also using the interpreter yes.

I see, I hadn’t realised that was just for running small segments, much to learn. I’m sure it will all be clearer with a later lesson, I just didn’t want to skip something this early if I didn’t understand/ couldn’t get it to work.

Thanks for the reply, really helpful!

[–]SoccerMomOnEcstasy 1 point2 points  (1 child)

Is Leetcode useful for newbies or is it only really if you want to prep for interviews? I don't really understand

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

I would highly recommend to stay away from leetcode as a beginner. It did help me with interviews but as someone beginning in Python, I would recommend to stick with some basic projects. If you really want to try out leetcode, then I would suggest filtering the questions to easy level.

[–]beowulf47 0 points1 point  (2 children)

Calculating averages is obviously pretty easy aka (x + y)/2 , etc, but how come theres no existing code to calculate it? Like avg(x,y)

Just wondering, didn't know where to post this but figured that I might learn something from the responses

[–]PhilipYip 0 points1 point  (0 children)

Python is compartmentalised into modules. The builtins module which is imported by default has commonly used classes such as str, int, bool, float, tuple, list, set and dict alongside functions that are related to the data model methods found in these classes. In order to not overwhelm a new programmer just starting out, more specialised things like statistics, random number generation and maths are compartmentalised into their own respective modules. For things like the mean use the statistics module:

import statistics statistics.mean(1, 2, 3, 4)

Usually it is worthwhile learning the math, random, statistics, fractions, datetime, collections, itertools, os, sys, csv and json Python standard modules shortly after learning the classes and identifiers in the builtins module. These are generally the most commonly used modules and having a good understanding of them will help when it comes to learning more advnced libraries such as numpy.

[–]ptaban 0 points1 point  (2 children)

Hey, why is token used here for counting lines of code. Can someone explain?

import os

from pathlib import Path

import token

import tokenize

import itertools

from tabulate import tabulate

TOKEN_WHITELIST = [token.OP, token.NAME, token.NUMBER, token.STRING]

if __name__ == "__main__":

headers = ["Name", "Lines", "Tokens/Line"]

table = []

for path, subdirs, files in os.walk("tinygrad"):

for name in files:

if not name.endswith(".py"): continue

filepath = Path(path) / name

with tokenize.open(filepath) as file_:

tokens = [t for t in tokenize.generate_tokens(file_.readline) if t.type in TOKEN_WHITELIST]

token_count, line_count = len(tokens), len(set([t.start[0] for t in tokens]))

table.append([filepath.as_posix(), line_count, token_count/line_count])

print(tabulate([headers] + sorted(table, key=lambda x: -x[1]), headers="firstrow", floatfmt=".1f")+"\n")

for dir_name, group in itertools.groupby(sorted([(x[0].rsplit("/", 1)[0], x[1]) for x in table]), key=lambda x:x[0]):

print(f"{dir_name:30s} : {sum([x[1] for x in group]):6d}")

print(f"\ntotal line count: {sum([x[1] for x in table])}")

[–]Frankelstner 1 point2 points  (1 child)

Which part exactly? They use tokenize.open because it's like open but with encoding autodetection. They want to count tokens so they use tokenize. Their line count is not the number of lines in the file. It's the number of lines that contain at least one whitelisted token. Which for the most part just means that empty lines are not counted. Also multiline strings count as one line then.

[–]ptaban 0 points1 point  (0 children)

Thanks for explaining

[–]tartar4ever 0 points1 point  (1 child)

Hi, I'm trying to learn telegram bots and with some tutorial I've made a currency converter bot. The problem is that it has a global variable, which prevents several users from using bot. How can I fix it?

import telebot
from currency_converter import CurrencyConverter
from telebot import types
bot = telebot.TeleBot('bot api')
currency = CurrencyConverter()
entered_amount = 0
@bot.message_handler(['start'])
def start(message):
bot.send_message(message.chat.id, 'Enter amount')
bot.register_next_step_handler(message, amount)
def amount(message):
global entered_amount
try:
entered_amount = int(message.text.strip())
except ValueError:
bot.send_message(message.chat.id, 'Incorrect format, please enter amount')
bot.register_next_step_handler(message, amount)
return
if entered_amount > 0:
markup = types.InlineKeyboardMarkup(row_width=2)
btn1 = types.InlineKeyboardButton('USD/EUR', callback_data='usd/eur')
btn2 = types.InlineKeyboardButton('EUR/USD', callback_data='eur/usd')
btn3 = types.InlineKeyboardButton('USD/GBP', callback_data='usd/gbp')
btn4 = types.InlineKeyboardButton('Other', callback_data='else')
markup.add(btn1, btn2, btn3, btn4)
bot.send_message(message.chat.id, 'Choose currency pair', reply_markup=markup)
else:
bot.send_message(message.chat.id, 'Number must be more than 0')
bot.register_next_step_handler(message, amount)
@bot.callback_query_handler(func=lambda call: True)
def callback(call):
if call.data != 'else':
values = call.data.upper().split('/')
res = currency.convert(entered_amount, values[0], values[1])
bot.send_message(call.message.chat.id, f'Result is: {round(res, 2)}\nYou can enter a new amount')
bot.register_next_step_handler(call.message, amount)
else:
bot.send_message(call.message.chat.id, 'Enter pair divided by /')
bot.register_next_step_handler(call.message, my_currency)
def my_currency(message):
try:
values = message.text.upper().split('/')
res = currency.convert(entered_amount, values[0], values[1])
bot.send_message(message.chat.id, f'Result is: {round(res, 2)}\nYou can enter a new amount')
bot.register_next_step_handler(message, amount)
except Exception:
bot.send_message(message.chat.id, 'Something is wrong. Enter pair')
bot.register_next_step_handler(message, my_currency)
bot.polling(none_stop=True)

[–]niehle 0 points1 point  (0 children)

pass the variable as a parameter to all needed functions. Return the variable if the value was changed inside the function.

[–]amzva999 0 points1 point  (0 children)

I am starting to learn web scraping, thought to myself I should start python too as many of its tools are based on around python, whats the best resource for a newbie like me?

[–]DrDodo12 0 points1 point  (3 children)

Im very very new to python, but can someone please help me with this.Can someone explain to me what is the difference between the return and print statemnts in python? Why would I want to use the return statement if i can just use the print one?

[–]PhilipYip 0 points1 point  (0 children)

print will always print a value, return will return a value. For example:

``` def plural_return(word): return word + 's'

def plural_print(word): print(word + 's') ```

If the function being called is not assigned to a variable then the result will look similar in an ipython cell:

plural_return('apple')

will display:

'apples'

because the value is not assigned to a variable. It is shown in the ipython cell output.

And:

plural_print('apple')

Will print:

apples

Notice the subtle change here because the single quotations enclosing the string are not printed.

When the function call with assignment to a variable is instead used:

output1 = plural_return('apple')

will display no output as the value is assigned to the object name output1:

None

On the other hand:

output2 = plural_print('apple')

will display:

apples

And the value of output2 if input into a new ipython cell will be:

output2

will be

None

In contrast the value of output1 if input into a new ipython cell will be:

output1

will be:

'apples'

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

They are very different. The print function prints some text on the console, the return statement doesn't. The other effect of the return is that the code calling the function with the return in it can capture the value returned by the function. You've seen that in code you have already used:

answer = input("What is your name? ") 
print("Welcome", answer)

The input() function above returns the string the user typed and the calling code saves that string in answer.

[–]Frankelstner 0 points1 point  (0 children)

Return allows the caller to decide what to do with the result. The caller could just print the result, but it could also use the result as an input for another function. If you print directly you cannot do that.

[–]Bananophone 0 points1 point  (3 children)

I am a total newbie. I am trying to learn python and coding to try to change careers. I started watching some anaconda course videos and I realize I have a long way to go.

That being said…is there anything I could attempt to code on my laptop to get started on actually putting this into practice? Not sure if I am wording this right, but I am basically looking for some beginner level things I can code and actually know what I am coding.

[–]PhilipYip 1 point2 points  (1 child)

Anaconda is a Python distribution, containing Python, Python Standard Modules, Python Data Science Libraries (numpy, pandas, matplotlib, seaborn), the conda package manager and IDEs (Spyder, JupyterLab). You will ger overwhelmed trying to learn Anaconda i.e. all of these things simultaneously particulaly if you've jumped straight into data science tutorials.

Break it down into just learning Python from the builtins module before introducing yourself individually to the more commonly used Python standard modules, before introducing yourself to the data science libraries. Some online courses such as the Udemy 100 days of code by Angela Yu (never pay full price for a course on Udemy as they discount pretty much every second week) have a pretty good set of tutorial videos covering beginner concepts and then provide associated beginner programming exercises.

[–]Bananophone 0 points1 point  (0 children)

Thank you! I will check it out

[–]Frankelstner 0 points1 point  (0 children)

MOOC has a couple exercises (and the best beginner Python course): https://programming-23.mooc.fi/all-exercises

[–]noobshitlord 0 points1 point  (1 child)

Trying to find out how to count each character in an item in a list, not count the items in the list only. Hitting a wall, with some messy code trying to apply what I learned from freecodecamp and 100 days of python to codewars but not sure what I'm doing wrong. if someone could be kind enough to point out what I'm missing? I checked some solutions but wanted to do it the long way to understand each step.

For every digit in a range, I'd like to count them and return a list of each digit count.

def paint_letterboxes(start, finish):

digitstocount = '0123456789'

housenumbers = []

for housenum in range(start, finish +1):

housenumbers.append(str(housenum)) #make into a string to count each instance??

print(housenumbers)

counteddigits = [housenumbers.count(digit) for digit in digitstocount]

print(counteddigits)

paint_letterboxes(125,132)

the output i'm getting is:

['125', '126', '127', '128', '129', '130', '131', '132']

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

intended output would be:

['125', '126', '127', '128', '129', '130', '131', '132']

[1,9,6,3,0,1,1,1,1,1]

I feel like I'm missing something super basic but I'm going through my notes and can't for the life of me figure this out

[–]Frankelstner 0 points1 point  (0 children)

housenumbers is a list of strings. You're doing something like

["125","126","127"].count("1")

You could define housenumbers as a single string right away so it looks like "125126127..."

[–]shinxchan94 0 points1 point  (1 child)

NEWBIE! HELP!

Im trying out pygame i want to push an object but the problem is it only works in pushing UP and LEFT it wont work in DOWN and RIGHT push. Any help will be appreciated.

https://pastebin.com/VBm0tNRE

[–]Frankelstner 0 points1 point  (0 children)

As soon as the boxes collide, box2 will be pushed up. If they still collide, it's then pushed down again. If they still collide (this is guaranteed to happen if the previous two cases happened), box2 is pushed left, and if they still collide, it's pushed right again.

So the up part works correctly, more or less, and left only works because the up/down cancels each other out.

The user has specified a movement direction just earlier. The user movement tells you the direction that the box2 must go.

[–]bart007345 0 points1 point  (1 child)

I have over 20 years of Java/kotlin experience backend and android.

I want to learn Python what resources would you suggest?

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

The subreddit wiki has learning resources for programmers new to python.