r/learningpython • • Jun 27 '23

requests-oauth vs. MSAL+requests?

2 Upvotes

I'm starting work on a script that will access a SharePoint drive and looking for guidance on how best to access it. The msgraph-python libraries are not yet production ready. That leaves requests, I think. Does anybody have strong opinions on one or the other?


r/learningpython • • Jun 11 '23

Python Community: Let's Dive Into the Exciting World of Web Scraping!

Thumbnail self.coder_corner
2 Upvotes

r/learningpython • • May 21 '23

Demystifying Python Decorators: A Simple Guide

Thumbnail self.coder_corner
2 Upvotes

r/learningpython • • May 15 '23

Coding questions!

Post image
2 Upvotes

Hey all! i have a quick question, if i want to only accept numbers and not written numbers from my user input how would I do that? For example, if the user input four i want to ask them to enter that as a number instead, 4. Also, if they misspell a input, i want to ask them to retype that in to get the correct input. Any suggestions or reading on this is appreciated! Heres my code: Thanks!!


r/learningpython • • May 07 '23

Why is chr() putting out different characters for the same number?

2 Upvotes

The directions are: "Extend to convert the integer to a character by using the 'chr()' function, and output that character"

On my end it seems to work. But zybooks tests it with it will throw out a different character for the same number? See below:

I don't understand whats going on?

Here is my code:

print('Enter integer (32 - 126):')

user_int = int(input())

print('Enter float:')

user_float = float(input())

print('Enter character:')

user_character = input()

print("Enter string:")

user_string = input()

print(user_int , user_float , user_character , user_string )

# FIXME (2): Output the four values in reverse

print(user_string , user_character , user_float , user_int)

# FIXME (3): Convert the integer to a character, and output that character

user_integer_converted = chr(99)

print(user_int , 'converted to a character is' , user_integer_converted )


r/learningpython • • Apr 27 '23

New Python programmer - I would like someone to review my code

2 Upvotes

Could someone review my code for best practices and Python idiom? I write normally in C, so this could look like C written in Python.

#! /usr/bin/python3
import random
# mouse - Mousetraps Demo
"""
There was a comercial for the SyFy channel (a cable channel) in which
a person is standing in a field of mousetraps. Each mousetrap has a ball
resting on top of it. The person drops a ball and it lands on a mousetrap,
this launches the resting ball and the dropped ball off to two new mousetraps
which then trigger and send off their balls to yet more mousetraps.

The mousetraps do not reset.

This causes a chain reaction - all the balls are flying everywhere.

mouse is my attempt to simulate this situation.
"""

traps = 100
tripped = 0
flying = 1
intrap = 3
step = 0

while flying > 0:
    # count the step
    step = step + 1
    
    # The ball lands...
    flying = flying - 1

    # on a random trap
    this = random.randrange(1,traps)

    # was the trap tripped?
    if this > tripped:
        # The balls in that trap are launched and one more trap is tripped
        flying = flying + intrap
        tripped = tripped + 1

    # print the state of the simulation now
    print(f'Step:{step:8d} Flying:{flying:6d} Tripped:{tripped:8d} ')

print("done")

r/learningpython • • Apr 19 '23

i don't know what i did wrong

2 Upvotes

hi if anyone can help me with this im trying to make a text adventure and this is stumping me i ran it and it won't let me out of the room here the code

import json
# Define the player class
class Player:
def __init__(self, name, player_class):
self.name = name
self.player_class = player_class
self.inventory = []
self.location = "starting_room"

def add_to_inventory(self, item):
self.inventory.append(item)

def remove_from_inventory(self, item):
self.inventory.remove(item)
# Define the game rooms and their descriptions
rooms = {
"starting_room": "You are in a small room with a door to the north and a window to the east.",
"north_room": "You are in a dark room with a chest in the center.",
"east_room": "You are in a room with a desk and a bookshelf.",
"winning_room": "Congratulations! You have won the game."
}
# Define the game items and their descriptions
items = {
"key": "A small rusty key.",
"book": "A dusty old book.",
"coin": "A shiny gold coin."
}
# Define the game puzzles
puzzles = {
"north_room": {
"description": "The chest is locked. You need a key to open it.",
"solution": "key"
    }
}
# Define the game classes and their attributes
classes = {
"warrior": {
"health": 100,
"attack": 10
    },
"mage": {
"health": 50,
"attack": 20
    }
}
# Load the saved game state if it exists
try:
with open("saved_game.json", "r") as f:
saved_data = json.load(f)
player = Player(saved_data["name"], saved_data["player_class"])
player.inventory = saved_data["inventory"]
player.location = saved_data["location"]
except:
# If the saved game state doesn't exist, create a new player object
name = input("What is your name? ")
player_class = input("What class would you like to play as? (warrior/mage) ")
while player_class not in classes.keys():
player_class = input("Invalid class. Please enter a valid class. (warrior/mage) ")
player = Player(name, player_class)
# Game loop
while True:
# Print the current room description
print(rooms[player.location])

# Check if the player has won the game
if player.location == "winning_room":
print("Game over.")
break

# Print the items in the current room
items_in_room = [item for item in items.keys() if item in player.location]
if items_in_room:
print("You see the following items:")
for item in items_in_room:
print(f"{item}: {items[item]}")

# Check if there is a puzzle in the current room
if player.location in puzzles.keys():
puzzle = puzzles[player.location]
print(puzzle["description"])
solution = puzzle["solution"]
if solution in player.inventory:
print("You solved the puzzle!")
else:
print("You don't have the item needed to solve the puzzle.")

# Get the user's input
command = input("What would you like to do? ")

# Handle the user's input
if command == "quit":
# Quit the game and save the current state
with open("saved_game.json", "w") as f:
data = {
"name": player.name,
"player_class": player.player_class,
"inventory": player.inventory,
"location": player.location
            }
json.dump(data, f)
print("Game saved. Goodbye!")
break
elif command == "inventory":
# Print the items in the player's inventory
if player.inventory:
print("You have the following items:")
for item in player.inventory:
print(f"{item}: {items[item]}")
else:
print("Your inventory is empty.")
elif command == "help":
# Print the help message
print("Commands:\nquit - Quit the game and save your progress.\ninventory - View the items in your inventory.\nhelp - View this help message.")
elif command.startswith("go "):
# Move the player to a different room
direction = command.split()[1]
if direction in ["north", "east", "south", "west"]:
new_location = player.location + "_" + direction
if new_location in rooms.keys():
player.location = new_location
print(f"You move to the {direction}.")
else:
print("You can't go that way.")
else:
print("Invalid direction.")
elif command.startswith("take "):
# Add an item to the player's inventory
item = command.split()[1]
if item in items.keys() and item in player.location:
player.add_to_inventory(item)
print(f"You take the {item}.")
else:
print("You can't take that.")
else:
# Handle invalid commands
print("Invalid command. Type 'help' for a list of commands.")


r/learningpython • • Apr 19 '23

Python Tips & Tricks: Boost Your Productivity and Code Elegance

Thumbnail self.coder_corner
2 Upvotes

r/learningpython • • Apr 12 '23

Make SIP Call Using Python With IP Authentication

2 Upvotes

Hey everyone,

I'm currently working on a Python script and I need to make a simple SIP/VOIP call without having to register a device. I've tried using PyVoip, but it doesn't seem to fit my requirements. What I'm trying to do is make a call to my SBC (Session Border Controller) based on IP authentication.

Does anyone have any suggestions or recommendations on how to achieve this? I'd really appreciate any help or guidance on this matter. Thanks in advance!


r/learningpython • • Apr 08 '23

Top 10 Common Mistakes Python Programmers Make and How to Avoid Them

Thumbnail self.coder_corner
2 Upvotes

r/learningpython • • Mar 24 '23

How do you feel about using google/forums while learning

2 Upvotes

I’m currently in a class and I’m trying to learn new things at a nice steady pace. Whenever I get stuck I tend to look up problems similar to mine with accessible code and back track for my sake. Is this going to mess up my coding knowledge development. I hear that the pro are often on these forums as well but will this stunt my growth in the early stages?


r/learningpython • • Mar 17 '23

Question about input number

2 Upvotes

How do u check how many times user has made input?


r/learningpython • • Feb 27 '23

Python tutorial by topics

2 Upvotes

Hey Guys, I have created a series of Python tutorials (and am adding to them). Would be happy to be helpful to anyone :)

  1. Python Quick Start: Variables, Operators, Comments

https://www.youtube.com/watch?v=tpDtFTIkojU

2. Python data types, built-in functions: quick start tutorial for beginners

https://www.youtube.com/watch?v=ODg4qQ_YSOQ

3. Python if else condition, for and while loop: quick start tutorial for beginners

https://www.youtube.com/watch?v=FV9EO-3aaU0

4. Python functions and modules: quick start tutorial for beginners

https://www.youtube.com/watch?v=WVbj_4X8JyQ

5. Python list, tuple tutorial

https://www.youtube.com/watch?v=85jnkXL58IA

6. Python set, dictionary beginner start fast

https://www.youtube.com/watch?v=UX6eOSY8BzY


r/learningpython • • Feb 17 '23

need help with this for home work I'm just not understanding i've been to every class

2 Upvotes

Write a program that does the following:

  •  Asks the user for an integer number.

  •  If the number is divisible by 5 then divide it by 5 and print the result.  

  •  If the number is divisible by 3 then divide it by 3 and print the result.  

  •  But if the number is divisible by 3  and by 5 print "DIVISIBLE BY 3  AND 5!". 

  • In all other cases the program should print "Not divisible by 3 or 5".


r/learningpython • • Feb 16 '23

How do I get a list of the line numbers of a python script that were actually processed by python?

2 Upvotes

I have a python program with functions and function calls.

I need to get all the line numbers that were executed (and not skipped) when python was running this program.

I don't want to use breakpoints at all (if possible). I just want a file with all the line numbers.

What tools can you recommend me for this task?


r/learningpython • • Feb 03 '23

Class variables declared in _init_ ... good practice ?

2 Upvotes

Topic for discussion... coming from a C/C++ background, this bothers me:

class Student:
    # Class variable
    school_name = 'ABC School '
    
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

Because name and roll_no end up being class variables. But it isn't really clear when done like that. You have to go through _init_ to see what the class vars are.

Why isn't it written as this ?

class Student:
    # Class variables
    school_name = 'ABC School '
    name = ''
    roll_no = 0
    
    def __init__(self, name, roll_no):
        self.name = name
        self.roll_no = roll_no

r/learningpython • • Jan 24 '23

Retrieve a variable within a function

2 Upvotes

Im trying to alter the feedback so that once a function is executed it automatically updates 'feedback' to print a statement that is returned by one of the menu functions but Im not sure if Im doing it correctly.

How should one properly retrieve a variable from a function nested within a while loop

    def play(self):
        feedback = ''
        while True:
            if len(self.mypets) >= 1:
                for dapet in self.mypets:
                    print(dapet)
            print(18*'\n')
            print(feedback)
            print(f"""
                ...WELCOME TO THE PET SHOP...
            
                How may I help you {self.name}?
                1) Adopt Pet 2)Feed Pet 3)Release Pet 4) Go Back
            """)
            dresponse = inputchecker()
            if dresponse == 1:
                self.adopt()
            elif dresponse == 2:
                self.feed()
            elif dresponse ==3:
                self.release()
            else:
                break

r/learningpython • • Nov 15 '22

I get "module 'pandas' has no attribute 'core'" error when trying to import pandas (or any module) into CoLab

2 Upvotes

I use Google CoLab exclusively for Python. I'm just learning--not doing anything crazy. I tried to import my standard set of modules into my script and got the above error. If I remove the import, the error just switches to whatever module is next in the code (import seaborns as sns, for example). It was working yesterday. Does anyone have any idea on what to do?


r/learningpython • • Nov 09 '22

Error when i try to install pip/panda

2 Upvotes

How can i install pip and after, install panda?

When i try, ocurr this error:


r/learningpython • • Nov 01 '22

In PySside2. How I show the thumbnail for an item in QtextBrowser. When the user hovers it?

2 Upvotes

Now I have a plan that it is drag files to QttextBrowser

When mouse hovers the path URL. The thumbnail will display at QttextBrowser right sight.

But I reference to two articles. I can't achieve it.

In PyQt5's QListWidget, how can I only show the tooltip for an item when the user chooses it?

Qt: display tooltip on LineEdit widget that is mapped to AbstractListModel

How I implement the plan? Is the keywords  tooltip  ?

Here is my code and ui profile. https://github.com/cj044/file-preview-plan

But stackflows is solution below:

In PySside2 how can I show the thumbnail for an item in QtextBrowser. When the user hovers it?

def dropEvent(self, event):

cursor = self.textBrowser.textCursor()

for url in event.mimeData().urls():

pos = cursor.position()

path = url.toLocalFile()

cursor.insertText(path)

cursor.setPosition(pos, cursor.KeepAnchor)

fmt = cursor.charFormat()

fmt.setToolTip('<img src="{}">'.format(path))

cursor.setCharFormat(fmt)

cursor.movePosition(cursor.End)

cursor.insertText('\n')

It just shows little icon.

Thanks!


r/learningpython • • Oct 28 '22

at what point do you install your local package into pip?

2 Upvotes

Hi,

I have a codebase that has grown the last couple years and I'm now at the point where I want to consolidate some commonly used things and break out different scripts/projects into their own local folders and their own git repos.

currently all the scripts are either in the same folder, and in some cases where they are not, I use sys.path.append('/my/dir')

All the scripts are used only by me, but some are deployed on a server (which I maintain) and run as scheduled tasks. I would like to be able to make updates locally, copy up a zip and install via pip on the server, but not sure if that is a best practice or not.

How big/complex/sophisticated do you feel a project needs to be before installing into pip. (I was thinking of the instructions here and structuring the package like so.

btw...I posted this in r/python and it was removed immediately. Was that a karma thing? How much karma do you need to post?


r/learningpython • • Oct 23 '22

Currently passing 2/3 checks Mode is not ouputting correctly

2 Upvotes

A group of statisticians at a local college has asked you to create a set of functions that compute the median and mode of a set of numbers. Define these functions, median and mode, in a module named stats.py. Also include a function named mean, which computes the average of a set of numbers. Each function should expect a list of numbers as an argument and return a single number. Each function should return 0 if the list is empty. Include a main function that tests the three statistical functions using the following list defined in main:
lyst = [3, 1, 7, 1, 4, 10]
An example of the program output is shown below:
List: [3, 1, 7, 1, 4, 10]
Mode: 1
Median: 3.5
Mean: 4.33333333333333

My code so far: (outputs 10 for mode instead of 1)

def mean(list):
    l = len(list)
    i = 0
sum = 0
while i < l:
sum += list[i]
        i += 1
return sum / l
def median(list):
    l = len(list)
list = sorted(list)
    mid = l // 2
if l%2 == 0:
return(list[mid] + list[mid - 1]) / 2
else:
return(list[mid])
def mode(list):
    d = dict()
    mode = False
    modeValue = 0
    result = 0
for x in list:
if(not d.get(x)):
            d[x] = 1
else:
        d[x]+=1
        mode = True
if(d[x] > modeValue):
        modeValue = d[x]
        result = x
if(mode):
return result
else:
return "No mode"
def main():
list = [3,1,7,1,4,10]
print("List: ", list)
print("Mode: ", mode(list))
print("Median: ", median(list))
print("Mean: ", mean(list))
main()


r/learningpython • • Sep 27 '22

Why do some facebook endpoints have this for(;;):{ ?

Post image
2 Upvotes

r/learningpython • • Sep 22 '22

Organizing Files

2 Upvotes

I am trying to move files based on their first four characters in the file name. Later on I will want to sort the files based on their 43-43 characters in the file name. I’m working on just moving the files based on the first four characters, but I can’t get it to work. The “WV02” are the first few characters I want to identify.

import shutil import os

source_dir = 'E:\SatelliteImagery\Cloud_Cover_less_than_50'

target_dir = 'E:\SatelliteImagery\GE01_less_than_50'

file_names = os.listdir(source_dir)

for file_name in source_dir:       if file_name(file_name, "WV02")       shutil.move(os.path.join(source_dir, file_name), target_dir)


r/learningpython • • Sep 14 '22

Any idea how do I print each character from string as a separate gif file with different coordinates for each character ?

2 Upvotes

Hi

I have a list like this:

MyLines = [
"This is Line Number 1",
"Line number two and a half",
"and last line 3 ",
]

What would be the best approach to print every character as a gif file so at the end I can consolidate it in to one animated gif ?

"," is line break

I have the bit of code which splits the strings :

for MyLines in MyLines:
for c in MyLines:
print (c, end='')
sys.stdout.flush()
sleep(0.1)
print('')

and not sure what to do next , I know the pillow will be the solution to draw the output with font setup but...

How do I actually convert above into dictionary where each character got own coordinates which I can map to initial gif file 1375x1375 pix.

Printed text will be always not more than 30 characters by 3 lines so max 90 frames per final gif.

Do I need to create some how coordination matrix which maps current position of character to the destination coordinates on the file ?

Any suggestions or keywords I should google will be appreciated as well as code sample if someone is wiling to help that way :)

Thank you !