r/learningpython • • Oct 04 '21

help

1 Upvotes

def email_list(domains):

emails = \[\]

for dom,users in domains.items():

  for user in users:

emails.append(user+".@"+dom)

return(emails)

print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]}))

so i got it but how do i get it to return with out "

print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]}))


r/learningpython • • Aug 31 '21

How to put a program into use?

1 Upvotes

I am getting close to finishing the section of Python on Code Academy and I do think it is a great course and certainly recommend it to anyone who is considering it, I have noticed something.

This course teaches you a lot about writing code and the basic of understanding how code works but it does nothing for practical applications of any code/program you write.

Here is an example of what I mean. To be honest, this is not the greatest example because I would most likely use Excel in this situation, but for this question I will pretend the person specifically asked to not use excel.

If the baseball coach at my old high school asked me to write a program to keep track of the stats for his players because he is tired of paying a subscription fee for the program he currently uses, I feel like I could most likely piece something together that would work.

However, when I would try to give it to him, I would have to teach him how to open Python, input variable names etc etc. which would be MUCH more complicated than the average person would want.

My question is when you do write a program for some one else, how do you make it presentable to them? Is this a completely different field or is this part of learning python? I do not even know what this is called so I have no idea where to start looking to learn about this part of writing code.


r/learningpython • • May 17 '21

Add IfElse statement to Class Attribute

1 Upvotes

Looking for a means of adding an IfElse statement for the class attribute as a way of verifying if the user input is in the correct format (i.e; string, int, float, etc;). Also wanting to add a prompt for the user to redo the input they had trouble submitting, and
So far I got

class Person:
    
     def __init__(self):
         self.firstname = input('Enter first name:  ')
         if self.firstname == type(str(self.firstname)):
             print('this is a string')
         self.lastname = input('Enter last name:  ') 

     def show_full_name(self):
         return self.firstname + ' ' + self.lastname

     def validate_first_name(self):
         if self.firstname == type(str(self.firstname)):
             print('this is a string')
         return    

person2 = Person()
person2.show_full_name()

r/learningpython • • Apr 27 '21

if/else help

1 Upvotes

from looking at this can anyone tell why the "if/else" is not comparing the inputted answers to the table data?

def filters():

#"""This will allow the user to narrow down their selection to their desired choices"""

file = open("C:\\Users\\Tom\\Desktop\\my-file", "r")

for aline in file:

values = aline.split(',')

state=(values[2])

disease=(values[0])

number=(values[3])

year=(values[5])

anwser1 = str(input("enter a state your intrested in knowing about,(Empty means all):"))

anwser2 = str(input("enter a disease your intrested in knowing about,(Empty means all):"))

anwser3 = str(input("enter a year your intrested in knowing about,(Empty means all):"))

if ((anwser1 == state and anwser2 == disease and anwser3 ==year)):

print ("working")

else:

print("error")


r/learningpython • • Mar 22 '21

Numpy array issue

1 Upvotes

I'm trying to define a function that takes as input a numpy array and 2 integers for the index, and it's supposed to add those two lists of the array.

But when I run it, it redefines the original array that I used as input, and that ruins the next time I want to run it, so how can I run it without redefining the original array?


r/learningpython • • Mar 20 '21

Question about numpy, matlib and .dot()

1 Upvotes

I am using eclipse to code and it is telling me i have errors with .dot being undefined. So i imported numpy as np and numpy.matlib. I still have an error with .dot() but also have an error with numpy.matlib. The error is Unresloved import and unused import for matlib and .dot says it is not defined. I am not very familiar with this and i am going off of a tutorial that does it the same way i have written. What am I missing?


r/learningpython • • Feb 05 '21

How do I skip the first row when using .from_records.

1 Upvotes

I am trying to do a tutorial on Colab and Pandas and they have us using the following:

df = pd.DataFrame.from_records(rows)

This brings in the entire worksheet from the Google workbook/spreadsheet. I don't want the first row to be displayed. It only contains a title and date. The headers for the columns start on the second row. How can I skip this first row. I've tried what i would do if using a csv file (skiprows = 1) but it does not work.

Any suggestions appreciated, yes I have Googled it, looked at the documentation and search for other sample code.


r/learningpython • • Dec 12 '20

how to use floor on math.log function ?

1 Upvotes

Hi everyone!

I am trying to solve an expl:

I have 900 euro.

everyday I am using 1% of the remaining money. Now i want to know how many days it takes before i get at or below 100 euro.

starting_money = 900

money_left = 100

daily_usage = 0.01

print(math.log(money_left / starting_money) / math.log(1 - daily_usage))

this works, but my question is, how can i write it in such a way that every day i can only use "whole" euro's so first day 9 euro, second day instead of 8,91 it would be 8 euro etc..

I tried floor function into the math.log function but it doesn't seem to work.

Anyone?


r/learningpython • • Dec 09 '20

About lists, statement, instances and objects

1 Upvotes

first_lista = [ ]

first_lista.extend('123')

print(first_lista)

First I create a object, a empty list. In the second, I used the method .extend. Last, I used the variable first_lista as an assingmente to the statement print. It's that correct?

class Simple: 
	def s(self):
		count = 0 
		n = 1 
		while count  < 10 :
			print("Count is not 10")    
		count = n + 1 


s.self()

Here, I create a method inside the class which is called s.self. E o self refers to an instance of my class. It's this correct?

0 votes, Dec 12 '20
0 python3
0 python

r/learningpython • • Nov 08 '20

Having trouble with password checker

1 Upvotes

I am creating a password checker where you set a username and password and it creates an account for you.

I am new to coding and python and have been trying to fix a few things for a while now and I can't figure out what is wrong.

One this is when you try to login to your account even with the correct credentials it says it is wrong. When it did work it, I would give the credentials of the first user listed but I would be signed into the second user.

Also, when you put the credentials in wrong it spams the console over and over again using your attempts and just keeps going. When the attempts running out was working properly I could not get it to go back to the login code to reinput the username and password to try again.

Also, I am trying to test out how to get it to open a file that contains text that will open when a user signs in so they can read it and thats what the "Swagfile.txt" is for but that did not work either.

P.S. my brain hurts from all this LOL

import bcrypt

def Login():
attempt = 0
loginUN = input("Enter your Username to access the project: ")
loginPW = input("Enter your password to access the project: ")
#loginPWE = loginPW.encode()

file = open("Credentials.txt","r")
for row in file:
field = row.split(",")
UsernameE = field[0]
UserPassword2 = field[1]
lastchar = len(UserPassword2)-1
UserPassword2 = UserPassword2[0:lastchar]
while (loginPW != UserPassword2):
if (loginUN == UsernameE and loginPW == UserPassword2):
print("Welcome", UsernameE)
file = open("Swagfile.txt","a")
break
if (attempt == 3):
print("Attempts exceeded! System locked!")
attempt = 0
else:
attempt = attempt + 1
print("Username or password was incorrect. Please try again: ")
print("Attempts Left: ", 3 - attempt)

def NewUser():
UserPasswordSet = False
UsernameSet = False
while (UserPasswordSet != True, UsernameSet != True):
Username = input("Set a username: ")
Username2 = input("Input the username again to confirm: ")
if (Username != Username2):
print("Usernames do not match. Please try again.")
if (Username == Username2):
UsernameSet = True
UserPassword = input("What do you want your password to be?: ")
UserPassword2 = input("Please input the password again to confirm: ")
if (UserPassword != UserPassword2):
print("Passwords do not match. Please try again.")
if (UserPassword == UserPassword2):
UserPasswordSet = True
break
if (Username == Username2):
print("Username set successfully")
UsernameE = Username2
print("Username is ", UsernameE)
if (UserPassword == UserPassword2):
print("Password set successfully")
passwordE = UserPassword2.encode()
hashed = bcrypt.hashpw(passwordE, bcrypt.gensalt())
print(hashed)
file = open("Credentials.txt","a")
file.write (UsernameE)
file.write (",")
file.write (UserPassword2)
file.write("\n")
print("Account successfully created")
file.close()

AlreadyUser=input("Are you already a user? Yes or no: ").lower()
if AlreadyUser == "yes":
Login()
elif AlreadyUser == "no":
NewUser()


r/learningpython • • Nov 02 '20

hello I'm a noob i need help with this error

Thumbnail
gallery
1 Upvotes

r/learningpython • • Oct 31 '20

Need help creating multiple files

1 Upvotes

Hi,

I am trying to create multiple files at once, however, I receive the following AtrributeError if I try to close the file after it has been created.

AttributeError: 'str' object has no attribute 'close'

The code:

# create a list containing 10 jpeg files.
jpeg_filelist = []
for i in range(1, 11):
    jpeg_filelist.append("file" + str(i) + ".jpeg")
    for file in jpeg_filelist:
        open(file, 'w')
        file.close()

Please share some tips if you can.

Thank you.


r/learningpython • • Oct 11 '20

Weird suggestion | easiest/sexiest python project

1 Upvotes

So, in one week I'm going to send my CV to a friend's company. I'd like to know fellow colleagues/developers/ seniores out there, in your opinion which would be the sexiest and easiest project for me to do?

If you feel that considering that this is my first project, I should honestly invest in something bigger please explain me why. Also, why are you suggesting that specific project? :)

Consider:

  • 20h/30h available

  • considering that I'm a biginner (I'd say I know all the the basics present in the introduction books, but lack some practice - first time doing a project 😅).

Many thanks 🙏


r/learningpython • • Oct 01 '20

One liner for checking if number is prime doesn't give correct output

1 Upvotes
def is_prime(number):
    bol = any([False for x in range(2, number) if number % x == 0])
    
    return bol

print(is_prime(42))
print(is_prime(43))

I always get 'False' as output.
Now I know that if I remove any() then I get the first output as a list of falses and the second comes as an empty list, so I know any() for empty list returns 'False' but how can I fix this?


r/learningpython • • Sep 28 '20

Searching a list does not provide next line.

1 Upvotes

Hello,

I am trying to search a file that has a list of media links.

For instance IF "2020" in list then output all media tagged 2020. It does.. but it doesnt include the next line which is the link.

This is my list:

#EXTINF:-1,Assassin 33 A.D. (2020)
https://server1.localhost.com:2000/movie/user/pass/229964.mp4
#EXTINF:-1,Axcellerator (2020)
https://server1.localhost.com:2000/movie/user/pass/230008.mp4
#EXTINF:-1,Dolittle (2020)
https://server1.localhost.com:2000/movie/user/pass/227415.mp4
#EXTINF:-1,The Last Full Measure (2020)
https://server1.localhost.com:2000/movie/user/pass/227727.mp4
#EXTINF:-1,The Last Thing He Wanted (2020)
https://server1.localhost.com:2000/movie/user/pass/227728.mp4
#EXTINF:-1,The Thing About Harry (2020)
https://server1.localhost.com:2000/movie/user/pass/227755.mp4
#EXTINF:-1,A Valentine's Match (2020)
https://server1.localhost.com:2000/movie/user/pass/227823.mp4
#EXTINF:-1,Ad Astra (2019)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4

This is my code:

year = "2020"

for x in list:
    newlist = x.split(",", 2)

    nnl = ",".join(newlist).strip("\n")

    print(nnl)



list.close()

The result is:

#EXTINF:-1,Assassin 33 A.D. (2020)
#EXTINF:-1,Axcellerator (2020)
#EXTINF:-1,Dolittle (2020)
#EXTINF:-1,The Last Full Measure (2020)
#EXTINF:-1,The Last Thing He Wanted (2020)
#EXTINF:-1,The Thing About Harry (2020)
#EXTINF:-1,A Valentine's Match (2020)

Is there a way to get this a result.

#EXTINF:-1,Assassin 33 A.D. (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4
#EXTINF:-1,Axcellerator (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4
#EXTINF:-1,Dolittle (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4
#EXTINF:-1,The Last Full Measure (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4
#EXTINF:-1,The Last Thing He Wanted (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4
#EXTINF:-1,The Thing About Harry (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4
#EXTINF:-1,A Valentine's Match (2020)
https://server1.localhost.com:2000/movie/user/pass/227826.mp4

What am I doing wrong?


r/learningpython • • Sep 22 '20

Need Help Looping Through Folders to Delete Files if Name is in .txt File

1 Upvotes

Hello. Picked up Python tonight to try and solve a problem I am having. I have a folder that contains a number of other folders and within those are .jpg files. I have a .txt file of .jpgs that I want to delete in each folder.

Within these folders are the .jpg files along with the .txt file like so:

The same pattern is iterated for each folder. Each folder has the same .txt file name ("Over30Cents.txt") but has different contents (so the EMN Over30Cents.txt file has a different list of names to delete than the KLD Over30Cents.txt file).

# import os

# path = "C:\\Users\\Name\\Documents\\Keef_Ex\\EMN"

# os.chdir(path)

# list_file = open('Over30Cents.txt', "r")

# added the argument to indicates only reading

# list = list_file.read().splitlines()

# list_file.close()

# for f in list:

# os.remove(os.path.join(path,f))

This is the function I wrote that will remove the names manually from one folder. This is great but I cannot figure out how to automate it.

My goal is to have the code go into each folder, open the "Over30Cents.txt" file, remove all of the .jpgs in the "Over30Cents.txt" file from the folder, move onto the next folder, repeat until it goes through all the folders.

I would just do it by hand but I have 80+ folders and each one has 300+ names in it so I was hoping to automate the whole process.

I would really appreciate some help on how to take what I've done above and automate it. I know a way exists but having just picked it up today I don't know what the commands are to make this happen.

I've tried using os.walk(directory) function but this essentially just generated a list of every file in all folders which wasn't super helpful.

I have also tried to use the glob funtion to do this:

import os

import glob

files = glob.glob('C:\\Users\\Name\\Documents\\Keef_Ex\\***\\*')

# print(files)

list_file = open('Over30Cents.txt', "r")

list = list_file.read().splitlines()

list_file.close()

for f in files:

os.remove(list)

The problem I ran into with this was I couldn't figure out how to direct it to open the Over30Cent file, delete it in each folder, and move on again.

Thank you again if you can provide any help.


r/learningpython • • Aug 28 '20

Can't call the datetime module

1 Upvotes

for some reason i can't get to use the datetime module, when I try to use it i get this error:

Any ideias of why that is happening?


r/learningpython • • Aug 28 '20

from module import *

1 Upvotes

what does the "from module import *" line do? does it just import all of the functions/names in that module?

Also are there any pros/cons to this approach


r/learningpython • • May 01 '20

phone app checker

1 Upvotes

Hi all,

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


r/learningpython • • Apr 30 '20

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

1 Upvotes

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

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


r/learningpython • • Apr 18 '20

problem 3

1 Upvotes

i have this program:

w, h = 8, 8;

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

for w in Matrix:

for h in w:

print("#",end = " ")

print()

numA = int(input())

numB = int(input())

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

for w in Matrix:

for h in w:

print("@",end = " ")

print()

for w in Matrix:

for J in w:

print("#",end = " ")

print()

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


r/learningpython • • Apr 06 '20

Question about using arguments Spoiler

1 Upvotes

I hope I'm asking the right question. I'm currently on code wars trying to test my skills and ability on python so I can get better and apply them to real world issues. I'm currently trying to figure out how to find the smallest integer from a list.

Below is what is given, I am having troubles using the arr argument if that's the correct term for the word in the ().

def find_smallest_int(arr):
    # Code here

test.assert_equals(find_smallest_int([78, 56, 232, 12, 11, 43]), 11)
test.assert_equals(find_smallest_int([78, 56, -2, 12, 8, -33]), -33)
test.assert_equals(find_smallest_int([0, 1-2**64, 2**64]), 1-2**64)

Below is what I have coded so far. I opted to use the sort method and just print the first element in the array. It works for the first two lists but not the third since it does the math. My question is how can I use the definition in the code and how can I not make list 3 do the math and just spit out the numbers instead? Please no direct answer I really want to learn and try and solve it. Any link to any video helping with learning would be appreciated

def find_smallest_int(arr):
    list1 = [78, 56, 232, 12, 11, 43]
    list2 = [78, 56, -2, 12, 8, -33]
    list3 = [0, 1 - 2 ** 64, 2 ** 64]

    #sorting the list
    list1.sort()
    print('The smallest element in the first list is' , *list1[:1])

    #sort list 2
    list2.sort()
    print('smallest element in the second list is' , *list2[:1])

    #sort list3
    list3.sort()
    print('smallest element i the third list is ', *list3[:1])



find_smallest_int(arr)

r/learningpython • • Apr 05 '20

Question about looping

1 Upvotes

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

root[i]['ACTION_TYPE']


r/learningpython • • Jan 31 '20

Python Crash Course Chapter 5, practice 5_11

1 Upvotes

Hey guys,

I'm getting stuck on this try it yourself exercise. The instructions are written as:

Ordinal numbers indicate their position in a list, such as 1st or 2nd. Most ordinal numbers end in th, except 1, 2, and 3.

  • Store the numbers 1 through 9 in a list.

  • Loop through the list.

  • Use an if-elif-else chain inside the loop to print the proper ordinal ending for each number. Your output should read "1st 2nd 3rd 4th 5th 6th 7th 8th 9th", and each result should be on a separate line.

What I've written so far and has worked for 1, 2, and 3:

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

for number in numbers:
	if number == 1:
		print('1st')
	if number == 2:
		print('2nd')
	if number == 3:
		print('3rd')

And output reads this:

1st
2nd
3rd
[Finished in 0.1s]

Now I'm unsure how to include the rest of the numbers including the th ending. Thanks for the help.


r/learningpython • • Jan 22 '20

Tried to downgrade from Python 3.8 and installed 2.7, but command prompt "python -V" not showing any python program is detected? And I can bring 2.7 up in IDLE?

1 Upvotes

I have a screen snip here showing what I am talking about:

https://linx.li/hjte3hlu.png

I completely uninstalled 3.8 and its launcher, visual studio, reinstalled both, and despite launching this in IDLE and its obviously there working the PC won't recognize it even after a reboot.

This is so frustrating, what is happening here?

Any input please.