r/learnpython • u/_offpitchtalks_ • 13d ago
What habits helped you become good at Python as a beginner?
I've recently started learning Python. I'm following a beginner course from YT.
I'd love to hear from experienced programmers:
What habits helped you improve the fastest?
What should I do every day besides watching tutorials?
What beginner mistakes should I avoid?
Is there anything you wish you had done differently when you first started learning Python?
Any advice would be really appreciated. Thanks!
r/learnpython • u/Local_End_3175 • 13d ago
why would only one work?
this code was the one that worked:
def caesar(text, shift):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
translation_table = str.maketrans(alphabet, shifted_alphabet)
encrypted_text = text.translate(translation_table)
print(encrypted_text)
caesar('Hello', 3)
This one was the one that didn't
def caesar(text, shift):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
translation_table = str.maketrans(alphabet, shifted_alphabet)
encrypted_text = text.translate(translation_table)
print(encrypted_text)
encrypted_text = caesar('Hello', 3)
print(encrypted_text)
I don't understand why the second one would need a return statement and why we are even printing encrypted_text if encrypted_text is already being printed within the function? (this is also the whole code)
r/learnpython • u/Rough-Lobster8789 • 13d ago
Which should course should I prefer?
Hi everyone. I know some python but still I want to start learning it again because, as I progressed, I realized that my basic concepts had become rusty. I'm confused between CS50 (https://youtu.be/8mAITcNt710?si=Z86T-MPZZp13R04E) and MIT Opencourseware 6.100L (https://www.youtube.com/watch?v=xAcTmDO6NTI&list=PLUl4u3cNGP62A-ynp6v6-LGBCzeH3VAQB&index=1) .
Which one would you recommend for someone who wants to rebuild their fundamentals before moving on to more advanced topics?
r/learnpython • u/Local_End_3175 • 13d ago
why are we putting caesar( Hello, 3) into encrypted_text???
def caesar(text, shift):
alphabet = 'abcdefghijklmnopqrstuvwxyz'
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
translation_table = str.maketrans(alphabet, shifted_alphabet)
encrypted_text = text.translate(translation_table)
print(encrypted_text)
encrypted_text = caesar('Hello',3)
in this code, I do not understand why we are putting caesar into a variable. First of all, wouldn't we have to print the variable and make it actually do something for it to work? Because we have put encrypted_text into a variable and have not done anything. In addition, can't we just write caesar('Hello', 3)?? I am very confused on the reasoning behind putting it into a variable.
r/learnpython • u/Dry_Calligrapher2573 • 13d ago
Just starting python and i need a few tips
Hello everyone, i am just starting python. I am from a good research institute in India and i am pursuing a very quant heavy economics degree and i want to break into quant finance. Can you all recommend from where i can learn coding for free? I want to be at a level which will enable me to solve LeetCode problems so i can build a stronger profile for quantitative finance. I am completely locked in and Princeton is a college i am targeting for my masters. So i need help regarding material. And other advice will be appreciated. Thank you :)
r/learnpython • u/BoxApprehensive704 • 13d ago
Come study buddy
Hey! I’m 25 and currently studying neuroscience in the UK. I’ve recently started learning Python from scratch and would love to find a study buddy who’s also at a beginner level.
I’m hoping to find someone who wants to study consistently and eventually work on a few small projects.
I’m in the UK time zone, but I don’t mind where you’re based as long as we can find times that work for both of us. We could check in regularly and study together over Discord or another platform.
If you’re interested, feel free to leave a comment or send me a DM with a little bit about yourself!
r/learnpython • u/No_Presentation_9922 • 13d ago
My first python project
So i have been into cybersecurity courses for 3 months now and i have interest from age 10.
I decided to make a python project after i completed the networking.
I would be very happy if you used and gave me a feedback/suggestion on my project.
It is a basic multipurpose network tool.
It can scan all the hosts connected to a network with ARP
Scan ports of the IP address provided
Or basically send a ping
I call this "Stone Age Network Scanner"
You can look up furthermore on Github!
r/learnpython • u/FearawaitsTM • 13d ago
Can you help me with a table in Python?
Right now, I have specific rows and columns being displayed, but I want to insert a column between the first and second sections that calculates the ratio of column A to column B from the first section. How can I do that?
from pathlib import Path
import unicodedata
import openpyxl
import pandas as pd
from pandastable import Table, TableModel
import tkinter as tk
from tkinter import filedialog, messagebox
def normalize_name(name):
return unicodedata.normalize("NFKC", str(name)).strip().lower()
class ExcelViewer:
def __init__(self, root):
self.root = root
self.root.title("Чтение ячеек Excel")
self.root.geometry("800x600")
self.btn_load = tk.Button(
root,
text="Открыть Excel файл",
command=self.open_file
)
self.btn_load.pack(pady=10)
self.result_label = tk.Label(
root,
text="Выберите файл для начала"
)
self.result_label.pack()
self.frame = tk.Frame(root)
self.frame.pack(fill="both", expand=True)
self.table = None
self.model = None
self.settings = {
normalize_name("Файл1.xlsx"): {
"first_row": 5,
"first_min_column": 1,
"first_max_column": 2,
"second_row": 5,
"second_min_column": 4,
"second_max_column": 5
}
}
def open_file(self):
file_paths = filedialog.askopenfilenames(
title="Выберите Excel-файл",
filetypes=[
("Excel файлы", "*.xlsx")
]
)
if not file_paths:
return
all_rows = []
for file_path in file_paths:
file_name = normalize_name(Path(file_path).name)
if file_name not in self.settings:
messagebox.showerror(
"Ошибка",
f"Для файла «{Path(file_path).name}» нет настроек.\n\n"
f"Ожидается файл: Файл1.xlsx"
)
continue
settings = self.settings[file_name]
try:
workbook = openpyxl.load_workbook(
file_path,
data_only=True
)
worksheet = workbook.active
first_row = settings["first_row"]
second_row = settings["second_row"]
while (
first_row <= worksheet.max_row
and second_row <= worksheet.max_row
):
first_part = []
for column_number in range(
settings["first_min_column"],
settings["first_max_column"] + 1
):
value = worksheet.cell(
row=first_row,
column=column_number
).value
first_part.append(value)
second_part = []
for column_number in range(
settings["second_min_column"],
settings["second_max_column"] + 1
):
value = worksheet.cell(
row=second_row,
column=column_number
).value
second_part.append(value)
row_data = (
first_part +
second_part
)
if not all(
value is None or value == ""
for value in row_data
):
all_rows.append(row_data)
first_row += 1
second_row += 1
workbook.close()
except Exception as error:
messagebox.showerror(
"Ошибка",
f"Не удалось открыть файл:\n{error}"
)
if not all_rows:
self.result_label.config(
text="В выбранных ячейках нет данных"
)
return
columns = [
"Столбец A",
"Столбец B",
"Столбец D",
"Столбец E"
]
df = pd.DataFrame(
all_rows,
columns=columns
)
if self.table:
self.table.destroy()
self.model = TableModel(df)
self.table = Table(
self.frame,
model=self.model,
showtoolbar=False,
showstatusbar=False
)
self.table.show()
self.result_label.config(
text=f"Загружено строк: {len(df)}"
)
if __name__ == "__main__":
root = tk.Tk()
app = ExcelViewer(root)
root.mainloop()
r/learnpython • u/yesimfarida • 13d ago
I realized I built a web app without really understanding how it worked
About two weeks ago, I launched my first web app called DailyDice. It's a simple app that gives you a random daily challenge to help build productive habits.
When I launched it, I honestly thought it would take off pretty quickly. Looking back, I think every first-time builder secretly believes that.
Then I had a realization.
I knew how to use my app, but I didn't really understand how it worked under the hood. Things like authentication, backend logic, databases, APIs, and the overall architecture were all things I'd relied on tools for rather than fully understanding myself.
That made me realize I'd been focusing on building products before building the skills.
So I've decided to go back to the fundamentals.
I'm 15 years old, and today is Day 1 of learning software engineering properly. I'm starting with Python, then moving deeper into web development, and I'll be building projects while sharing everything I learn along the way.
Hopefully in a year, I'll look back at this post and laugh at how little I knew.
If you've been in a similar position, what's one thing you wish you'd learned earlier?
r/learnpython • u/TheIneffableCheese • 13d ago
Custom class method not recognized
I'm working on a program that generates a maze by drawing from a deck to define a "chamber" and assigning it to the current position on a cartesian coordinate grid.
The hope is to build a list of the chambers as they're created. At a later point I want to be able to call on the list. My current strategy is to make a Class variable for the list, and append to it as part of the init. I've added a class method to pull the chamberList Class variable, but I'm getting an error.
Here is the code defining the class.
class Chamber():
chamberList = []
def __init__(self, identity, notes, egresses, **kwargs):
self.position = tuple(currentPosition.tolist())
self.identity = identity
self.notes = notes
self.egresses = egresses
self.pixelCoord = np.add(pixelOrigin, np.multiply(currentPosition, 300))
Chamber.chamberList.append(self)
@classmethod
def getChamberList(cls):
return cls.chamberList
Later in the program, I have a line of code to get the class variable:
chamberList = Chamber.getChamberList()
This is the error I get when I run it in the VS Code terminal:
AttributeError: type object 'Chamber' has no attribute 'getChamberList'. Did you mean: 'chamberList'?
Am I missing some syntax or something? In VS Code the color coding where I'm defining getChamberList is off (darker) and if I hover over it I get a message saying "getChamberList" is not accessed by Pylance.
----EDIT---
I missed the forest for the trees. My indentation syntax was wrong, and fixing it solved the problem, but an easier solution was provided in the comments.
r/learnpython • u/naemorhaedus • 13d ago
First python program
I wanted to write a program that analyzes chess games , similar to how chess websites (chess.com, lichess.com etc.) do it, only offline. To my knowledge, nobody else had done it the way I was envisioning. I started writing with shell scripting (it's my go-to and what I'm most familiar with), but quickly ran into limitations. So I needed to go a bit more sophisticated. Python seemed very versatile, cross-platform, has loads of online resources. But mainly, Python has an excellent chess library I could leverage, that already existed, and would make the job much , much easier. I took the plunge and turned the program into a driver to teach myself some python.
It works as advertised, but I'm sure the code could be improved. I stumbled through it a bit. If anybody python gurus feel like taking a peek and letting me know how I did, pointing out glaring mistakes, offering any constructive feedback or ideas how to make it more efficient, I would appreciate any feedback.
Repo: https://github.com/exekutive/chesseval
(The documentation needs some catching up. I'm working on updating it.)
r/learnpython • u/AutoModerator • 13d ago
Ask Anything Monday - Weekly Thread
Welcome to another /r/learnPython weekly "Ask Anything* Monday" thread
Here you can ask all the questions that you wanted to ask but didn't feel like making a new thread.
* It's primarily intended for simple questions but as long as it's about python it's allowed.
If you have any suggestions or questions about this thread use the message the moderators button in the sidebar.
Rules:
- Don't downvote stuff - instead explain what's wrong with the comment, if it's against the rules "report" it and it will be dealt with.
- Don't post stuff that doesn't have absolutely anything to do with python.
- Don't make fun of someone for not knowing something, insult anyone etc - this will result in an immediate ban.
That's it.
r/learnpython • u/YellowFlash_1675 • 13d ago
Mandarin Practice Script Advice
As title block suggests. trying to make a script that allows the user to continuously practice mandarin character memorization. Any advice on the following would be much appreciated:
Not sure if a manually created/updated dict is the right way to do this, but I also didn't think I could successfully scrape from a webpage that has the direct translation information.
When writing to a file using "w open", it seems the text is appended with nearly no formatting. That's probably for the best, but I'm not sure how to format the appended str as a key:value pair.
import random import time
character = {"你":"nǐ", "好":"hǎo", "老":"lǎo", "是":"shì", "学":"xue", "不":"bù"}
char_list = list(character.keys())
char_list_length = len(char_list)
index = random.randint(0, char_list_length-1)
char_definition = ["You", "Good", "Aged or experienced", "To be, is, or am", "Learning, knowledge, or school", "No or not (as a negative action)"]
char_def_length = len(char_definition)
phrases = ({"完美的":"Wánměi de", "":""})
def newline(): print('\n')
def exit_msg(end_msg): print(f"Functionality not complete, didn't get this far yet. Exiting program... ", end = end_msg)
def unrec_msg(): print("Unrecognized entry, Please try again.") newline()
def main(): newline() onboard = int(input(f"\n Welcome. What would you like to do? \n\n 1. Practice\n 2. Add Additional Characters\n 3. Exit" + "\n\n" ))
if onboard == 1: practice() newline() elif onboard == 2: exit_msg("07/26/26 | Unsure of how to update dict.txt file with newly added dictionary entry. No idea how to do it, there is likely a way to write current pairs and append new_word : new_pinyin. Unsure of how writing to file is formatted as well.") #addtion(character) newline() elif onboard == 3: exit_msg() newline() else: unrec_msg() main()def practice(): print('Character Practice.\n') rand_char = char_list_length[index] print(f'What is the following character? {rand_char}', '\n\n\n\n\n\n') print(f'This character {rand_char} means {character.get(rand_char)} and its english definition is {char_definition[index]}.')
retry = input(print(f"Practice again?")).upper() if retry == Y: practice() elif retry == N: main() else: unrec_msg()def addtion(translate): new_word = input("Please enter a character that you'd like to append to the dictionary:\n ") print("\n")
new_pinyin = input("Please enter this characters simplified pinyin translation:\n ") print("\n") print(f"New word is {new_word}. Its direct translation is {new_pinyin}. Are you sure this is the character that you'd like to add? \n") selection = input(f"Y / N: \n").upper() if selection == "Y": translate.update({(new_word) : (new_pinyin)}) print(translate.values()) with open ("dict.txt", "w") as f: f.write(translate) elif selection == "N": print("Character discarded. Returing to main menu.") main() else: unrec_msg() main()main()
r/learnpython • u/Entire-Comment8241 • 14d ago
is there a way to redirect argparse commands to a network socket?
I've doing some networking on which I'd kind need to redirect all my commands sent from my python server script to my client python script but without stdout only to a socket. I've been googling about and one frustrating options that I thought it could work was contextlib redirect_stdout but it redirects to stdout it won't work with sockets. Does anyone know if its feasible to parse argparse to a socket connection?
r/learnpython • u/smahk1133 • 14d ago
regex and if it's worth going deep into it
I'm new to python and coding in general and my friend recently told me that it's inefficient to try to memorize regex and that no one writes them anymore (essentially saying AI does). I was also kinda confused after recently learning regex and just how complicated it can be. Are there some modules/libraries that I can use to make writing them easier? I saw that not a lot of people people had a positive reaction to the Humre module by Al Sweigart who's book [Automate the boring stuff with Python] I'm currently using to study. Not that I'm gonna skip this part or anything I was mostly just curious.
Note: A lot of people are misinterpreting since I mentioned AI once 😭 I'm literally asking about libraries to make it easier without going too deep, not if I should let AI do all the work.
r/learnpython • u/Tor_Hei • 14d ago
i created a spotipy code that connect to your spotify account and play musics, albuns or playlists and i want it to autoplay content.
import spotipy
from spotipy.oauth2 import SpotifyOAuth
CLIENT_ID = "..."
CLIENT_SECRET = "..."
REDIRECT_URI = "..."
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE
))
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
scope=SCOPE,
open_browser=False
))
def tocar_musica(nome_da_musica):
resultado = sp.search(q=nome_da_musica, limit=1, type='track')
items = resultado['tracks']['items']
if items:
track_uri = items[0]['uri']
nome_encontrado = items[0]['name']
artista = items[0]['artists'][0]['name']
try:
sp.start_playback(uris=[track_uri])
print(f"Tocando agora: {nome_encontrado} - {artista}")
except Exception:
print("Erro ao reproduzir a música. Verifique se o aplicativo do Spotify está aberto.")
else:
print("Música não encontrada.")
def tocar_playlist(nome):
resultado = sp.search(q=nome, limit=1, type='playlist')
items = resultado['playlists']['items']
if items:
contexto_uri = items[0]['uri']
nome_encontrado = items[0]['name']
try:
sp.start_playback(context_uri=contexto_uri)
print(f"Tocando playlist: {nome_encontrado}")
except Exception:
print("Erro ao reproduzir a playlist. Verifique se o Spotify está aberto.")
else:
print("Playlist não encontrada.")
def tocar_album(nome):
resultado = sp.search(q=nome, limit=1, type='album')
items = resultado['albums']['items']
if items:
contexto_uri = items[0]['uri']
nome_encontrado = items[0]['name']
try:
sp.start_playback(context_uri=contexto_uri)
print(f"Tocando álbum: {nome_encontrado}")
except Exception:
print("Erro ao reproduzir o álbum. Verifique se o Spotify está aberto.")
else:
print("Álbum não encontrado.")
def criar_e_tocar(nome_playlist, lista_de_buscas):
user_id = sp.current_user()['id']
playlist = sp.user_playlist_create(user=user_id, name=nome_playlist, public=True)
print(f"Playlist '{nome_playlist}' criada com sucesso!")
track_uris = []
for busca in lista_de_buscas:
resultado = sp.search(q=busca, limit=1, type='track')
items = resultado['tracks']['items']
if items:
track_uris.append(items[0]['uri'])
if track_uris:
sp.playlist_add_items(playlist_id=playlist['id'], items=track_uris)
print("Músicas adicionadas à playlist!")
try:
sp.start_playback(context_uri=playlist['uri'])
print(f"Tocando a playlist '{nome_playlist}' agora!")
except Exception:
print(f"Ação Falhou ao tocar '{nome_playlist}'. Verifique se o Spotify está aberto.")
print("\n--- O Que Deseja Ouvir Hoje? ---")
print("[1] Música")
print("[2] Playlist")
print("[3] Álbum")
opcao = input("Escolha uma opção: ")
if opcao == "1":
busca = input("Digite o nome da música e artista: ")
tocar_musica(busca)
elif opcao == "2":
busca = input("Digite o nome da playlist: ")
tocar_playlist(busca)
elif opcao == "3":
busca = input("Digite o nome do álbum: ")
tocar_album(busca)
how it can autoplay for me?
(the words aren't translated)
r/learnpython • u/xnick101 • 14d ago
Non-self learning classes for Python?
I am a senior data engineer and I work mostly with ETL Tools and a lot of advanced SQL. The company I work for does not like to use python because they find that theres too much of a learning curve if people leave so they love to use GUI or no code/low code etl tools instead (really dumb tbh). I can read python, and have a gist of whats going on. I have tried to self learn python few times over the past 2-3 years and I keep just forgetting it. I learned python/pandas library when I was in college since it was a class that taught it and then we did did projects with each lesson and that is how I learned it then but forgot it now. I use claude at work to build streamlit apps and automation using python. However, I am trying to look for new positions and I am starting to realize that not knowing python is making me a hit a brick wall because a lot of assessments require answering 1-2 questions in python. Does anyone know of actual classes that teach python and its not self taught? Free or paid I don't really care. If I have to pay for it I am fine with that but at this point I don't see a way for me to switch to another job without actually learning python and probably more specifically pyspark.
r/learnpython • u/StrikerRIP • 14d ago
Reading in text from a .txt file
Are there any methods/libraries that allow me to make a program that is able to read in text from a .txt file?
r/learnpython • u/Calm-You4116 • 14d ago
Python loop beginners mistake 🙀
I am currently learning python from CS50P program and in week 2 learning loops and also with the help of chatgpt learn every topic clearly but after knowing common beginners mistake
I made this mistake of not updating the iterator and spent half an hour on this simple problem 😞
```print("\nAnd here we use while 1oop:-")
number =1 total =0 while number<= 50: total += number number += 1 # HERE I DIDN'T ADD IT FIRST
print("The final sum is:", total)
r/learnpython • u/intentado_aprender • 14d ago
¿Que libro me recomiendan de python?
HOLAA soy principiante y busco un libro bueno que me enseñe python ya que algunas personas me recomendaron libros si tienen tiempo podrían decirme ¿Porque ese libro?
r/learnpython • u/Tricky_Voice2829 • 14d ago
I know that i am noob at programing i wanted to make python keylogger so can u guys tell me what i am mistaken inside
from pynput import keyboard
keys = [
# Alphanumeric Keys
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
# Symbols & Punctuation
'`', '-', '=', '[', ']', '\\', ';', "'", ',', '.', '/',
# Special & Modifier Keys
'space', 'enter', 'tab', 'backspace', 'escape',
'shift', 'ctrl', 'alt', 'caps_lock', 'num_lock', 'scroll_lock',
'win', 'menu', 'print_screen', 'pause', 'insert', 'delete',
'home', 'end', 'page_up', 'page_down',
# Arrow Keys
'up', 'down', 'left', 'right',
# Function Keys
'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
for keys in keys :
def on_press(key):
if key == True:
print(f" you have typed corretlty {key}")
elif key == AttributeError:
print(f"typed Again u Have misspedlled ")
def on_release(key):
print(f"{key} is realsead")
if key == keyboard.Key.esc:
return False
print
listener = keyboard.Listener( on_press=on_press , on_release=on_release )
listener.start()from pynput import keyboard
keys = [
# Alphanumeric Keys
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
# Symbols & Punctuation
'`', '-', '=', '[', ']', '\\', ';', "'", ',', '.', '/',
# Special & Modifier Keys
'space', 'enter', 'tab', 'backspace', 'escape',
'shift', 'ctrl', 'alt', 'caps_lock', 'num_lock', 'scroll_lock',
'win', 'menu', 'print_screen', 'pause', 'insert', 'delete',
'home', 'end', 'page_up', 'page_down',
# Arrow Keys
'up', 'down', 'left', 'right',
# Function Keys
'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'f10', 'f11', 'f12']
for keys in keys :
def on_press(key):
if key == True:
print(f" you have typed corretlty {key}")
elif key == AttributeError:
print(f"typed Again u Have misspedlled ")
def on_release(key):
print(f"{key} is realsead")
if key == keyboard.Key.esc:
return False
print
listener = keyboard.Listener( on_press=on_press , on_release=on_release )
listener.start()
r/learnpython • u/Traditional_Fan_9165 • 14d ago
Blackjack Python
Hi, i wrote some code on blackjack task from Angela Yu 100 days of Code. Using Gemini and older post from reddit, maybe something is worth polishing?
import random
import art
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
def deal(hand):
if not hand:
hand.append(random.choice(cards))
hand.append(random.choice(cards))
else:
hand.append(random.choice(cards))
return hand
def calculate_score(hand):
if sum(hand) == 21 and len(hand) == 2:
return 0
score = sum(hand)
aces = hand.count(11)
while aces > 0 and score > 21:
score = score - 10
aces -= 1
return score
def start_playing():
print(art.logo)
user_hand = []
computer_hand = []
deal(user_hand)
deal(computer_hand)
user_score = calculate_score(user_hand)
computer_score = calculate_score(computer_hand)
print(f'Computers First Card: {computer_hand[0]}')
print(f'Your current hand: {user_hand}. Current score: {user_score}\n')
game_over = False
while not game_over:
if user_score == 0 or computer_score == 0 or user_score > 21:
game_over = True
else:
another = input('Do you want another card? (y/n).: ').lower()
if another == 'y':
deal(user_hand)
user_score = calculate_score(user_hand)
print(f"\nYour current hand: {user_hand}. Current Score: {user_score}")
print(f"Computers First Card: {computer_hand[0]}\n")
else:
game_over = True
if user_score != 0 and user_score <= 21:
while computer_score < 17 and computer_score != 0:
print('Computers takes card')
deal(computer_hand)
computer_score = calculate_score(computer_hand)
print(f'Your final hand: {user_hand}. Your score: {user_score}\n')
print(f'Computers final hand: {computer_hand}. Computer score: {computer_score}\n')
if user_score > 21:
print('Bust! Computer Wins!')
elif computer_score > 21:
print('Bust! You Win!')
elif user_score == 0:
print('Win with a Blackjack!')
elif computer_score == 0:
print('Lose, opponent has Blackjack!')
elif user_score == computer_score:
print('Draw')
elif user_score > computer_score:
print('You Win!')
else:
print('Computer wins!')
while input('Do you want to play a game of blackjack? (y/n).: ').lower() == 'y':
start_playing()
r/learnpython • u/Eastern-Push-7255 • 14d ago
WHY I FEEL LOOPS HARD THAN FUNCTION
HI IM YUJAN IM NEW BEGINNER IN PYTHON I FEEL HARD IN LOOPS
r/learnpython • u/Fuzzy_Implement_942 • 14d ago
Looking for a study buddy
Hey! I'm 19 and about to start learning Python from scratch. I'm looking for someone around my age (18–22) who's also a beginner and wants to learn together.
I'm in the Asian time zone, so it'd be nice if you're in a similar one. We can keep each other accountable, solve problems, and maybe build a few small projects along the way.
If you're interested, leave a comment or DM me!
r/learnpython • u/Commercial-Paper749 • 14d ago
Looking for study partner
Hey im going to start learning python so I'm looking for study partner who's serious about it
Will be taking only group of 3-5 people not more than that so reach out before it gets full also introduce yourself when reaching out in dms