r/pythonhelp • • May 17 '22

SOLVED Why is my django page showing up as raw html?

3 Upvotes

Hello,

I am working displaying a form preceded by a string generated by a function. When I try to add the string, my django page shows up as raw html.

Here is my view:

def hindi(response):
    context = {}
    context['prompt'] = Conjugame_2()
       

    if response.method == "POST":
        form = NewGuess(response.POST)

        if form.is_valid():
            n = form.cleaned_data["anumaan"]
            t = GuessRecord(anumaan=n)
            t.save()
    else: 
        form = NewGuess()
    
    return render(response, 'blog/hindi.html', {'form':form}, context)

Here is my template focusing on the trouble area:

{% block content %}
    <h1>Hindi Conjugation</h1>
    <p>{{prompt}}</p>
    <form method="post" action="/hindi/">
      {% csrf_token %}
      {{form}}
      <button type="submit", name="start", value="start">Start!</button>
    </form>
{% endblock content %}

r/pythonhelp • • May 16 '22

HOMEWORK Trying to make a ticket booking system but it only calculates cost for one of the ticket inputs

3 Upvotes
print("Welcome to WLC ticket Office")#displays a welcoming message to the user 

def userBooking():#creates a function for the user to enter their info
    tickCostList=[5.00,10.00,14.50]#sets a list to store the prices of each of the ticket options
    try:
        numTicket=int(input("Please enter the number of tickets you wish to buy? :"))#ask the user how many ticket they wish to buy and stores it as a variable 
        while numTicket>2 and numTicket>5 and numTicket<2:#sets a condition on the number of tickets you can buy 
            print("ERROR1: You can only buy a minium of 2 tickets at a time and maxium of 5")#displays a message to the user 
    except ValueError:
        print("You have entered an incorrect value")
        numTicket=int(input("Please enter again the number of tickets you wish to buy:"))#asks the user to reenter the number of tickets they wish to buy
    for numTicket in range(numTicket):#loops round the number of tickets inputed and displays a input query 
        customerAge=int(input("what age is the ticket holder? :"))#asks the user to input the age of each of the ticket holder they are buying 
        while customerAge>0 and customerAge<2:#sets conditions so that input can't be less than 2
            print("You must be at least 2 years of age to qualify for a ticket")#displays a message to the user 
            customerAge=int(input("Please enter the age of ticket again:"))#asks the user to enter the age the ticket again       
    return numTicket, customerAge#returns the variables numTicket and customerAge
       

def bookingCalculation(numTicket,customerAge):#sets a function to calculate the total cost 
    childTicket=5.00#sets a variable for the price of the child ticket
    TeenTicket=10.00#sets a variable for the price of the teen ticket 
    adultTicket=14.50#set a variable of the price of the adult ticket 
    total=0#initalises the total cost to 0
    bookedList=[]
    childList=[]#sets a empty list to store how many child tickets our booked 
    teenList=[]#sets a empty list to store how many teen tickets our booked 
    adultList=[]#sets a empty list to store how many adult tickets our booked 
    if customerAge>2 and customerAge<10:#sets a if statement to check if customerAge is between 2 and 10 
        bookedList.append("Child")
        childList.append("booked")#adds an a variable to childList 
        print("You booked a childs ticket","\n","Price:","\t",childTicket)#displays a message to the user 
        total=total+childTicket#adds the total cost with childTicket
    elif customerAge>11 and customerAge<19:
        bookedList.append("Teenage")
        teenList.append("booked")
        print("You booked a Teenage ticket","\n","Price:","\t",TeenTicket)
        total=total+TeenTicket
    elif customerAge>19 or customerAge>20:
        bookedList.append("Adult")
        adultList.append("booked")
        print("You have booked a adult ticket","\n","Price","\t",adultTicket)
        total=total+adultTicket
    return bookedList, childList, teenList, adultList, childTicket, TeenTicket, adultTicket, total
    
        
        
def display(childList, teenList, adultList, childTicket, TeenTicket, adultTicket, total):
    print("Number of child:",len(childList),"at",childTicket*len(childList))
    print("Number of Teen:",len(teenList),"at",TeenTicket*len(teenList))
    print("Number of adult:",len(adultList),"at",adultTicket*len(adultList))
    print("Total cost is:","£",total)
    print("Thank You for using WLC ticket office","\n","Please collect your ticket at our local ticket office")
    
def main():
    
    numTicket, customerAge=userBooking()
    bookedList, childList, teenList, adultList,childTicket, TeenTicket, adultTicket, total=bookingCalculation(numTicket, customerAge)
    if "Adult" not in bookedList:
        print("You must have at least one Adult to qualify for a ticket","\n","Your transaction could not proceed")
    else:
         display(childList, teenList, adultList, childTicket, TeenTicket, adultTicket, total)
   
    
main()

r/pythonhelp • • May 13 '22

HOMEWORK Remove middle name and Initials

3 Upvotes

This questions says that I need to make it so remove middle will remove the middle initial and return the name back to the main procedure and will print only the first and last name, also to account for if the person puts a period or not in between the middle name and the last name. and wants to take the full name and give its Initials, also both need to be capitalized.

Edit: I added some more code but now I am getting a unsupported operand types for -: 'str' and 'int'

def Main():

fullname=input("Enter full name")

print(f'Name minus middle initial is {Remove_MiddleInitial(fullname)}')

print(f'Your initials are {Return_Initials(fullname)}')

def Remove_MiddleInitial(fullname):

space=" "

period="."

if period in fullname:

Newname=(fullname[:period-1]+fullname[period+1:])

else:

Newname=(fullname[:space+1]+fullname[space+3:])

def Return_Initials(fullname):

Main()


r/pythonhelp • • May 12 '22

The loop keep resetting a 'set' code.

3 Upvotes

from random import randint

print ("goblin(20 health)")

def attack(x):

damage = randint(1,6)

x = x - damage

print ("u did {} damage".format(damage))

if x > 0:

print ("no ded")

print("goblin has {} health left".format(x))

else:

print ("ez(u win)")

return x

def action(x):

user_answer = input("(type 'a' to attack):")

if user_answer == "a":

return attack(x)

else:

print ("bro just attack already")

def main():

goblin = 20

goblin = action(goblin)

for i in range(50):

main()

It keeps resetting the health everytime you attack. How to let the player keep attacking without setting health back to 20?


r/pythonhelp • • May 12 '22

Is it possible to add a line to a csv file on dropbox without having to download it first?

3 Upvotes

I am using pandas to download a csv file adding the new entry and then sending it back. Is there a way to just add the line to the csv file instead of having to download it first?


r/pythonhelp • • May 10 '22

HOMEWORK What am I doing wrong?

3 Upvotes
from tkinter import *

root = Tk()

root.title("Simple Calculator")

e = Entry(root, width = 35, borderwidth = 5)
e.grid(row = 0, column = 0, columnspan = 3)

def button_click(number):
    #e.delete(0, END)
    current = e.get()
    e.delete(0, END)
    e.insert(0, current + str(number))

def clear_all():
    e.delete(0, END)

def add():
    first_number = e.get
    global f_num
    f_num = first_number
    e.delete(0, END)
def equal():
    second_number = e.get()
    e.delete(0, END)
    e.insert(0, int(f_num) + int(second_number))

#button codes
button_1 = Button(root, text = 1, padx = 40, pady = 20, command = lambda: button_click(1))
button_2 = Button(root, text = 2, padx = 40, pady = 20, command = lambda: button_click(2))
button_3 = Button(root, text = 3, padx = 40, pady = 20, command = lambda: button_click(3))
button_4 = Button(root, text = 4, padx = 40, pady = 20, command = lambda: button_click(4))
button_5 = Button(root, text = 5, padx = 40, pady = 20, command = lambda: button_click(5))
button_6 = Button(root, text = 6, padx = 40, pady = 20, command = lambda: button_click(6))
button_7 = Button(root, text = 7, padx = 40, pady = 20, command = lambda: button_click(7))
button_8 = Button(root, text = 8, padx = 40, pady = 20, command = lambda: button_click(8))
button_9 = Button(root, text = 9, padx = 40, pady = 20, command = lambda: button_click(9))
button_0 = Button(root, text = 0, padx = 40, pady = 20, command = lambda: button_click(0))
button_plus = Button(root, text = "+", padx = 39, pady = 20, command = add)
button_equal = Button(root, text = "=", padx = 91, pady = 20, command = equal)
button_clear = Button(root, text = "Clear", padx = 79, pady = 20, command = clear_all)

#Put the buttons on the screens
button_1.grid(row = 3, column = 0)
button_2.grid(row = 3, column = 1)
button_3.grid(row = 3, column = 2)

button_4.grid(row = 2, column = 0)
button_5.grid(row = 2, column = 1)
button_6.grid(row = 2, column = 2)

button_7.grid(row = 1, column = 0)
button_8.grid(row = 1, column = 1)
button_9.grid(row = 1, column = 2)

button_0.grid(row = 4, column = 0)

button_plus.grid(row = 5, column = 0)
button_equal.grid(row = 5, column = 1, columnspan = 2)
button_clear.grid(row = 4, column = 1, columnspan = 2)

root.mainloop()

Error:

Exception in Tkinter callback
Traceback (most recent call last):
 File "C:\Users\Admin\AppData\Local\Mu\pkgs\tkinter__init__.py", line 1705, in __call__
   return self.func(*args)
 File "c:\users\admin\desktop\all of the tkinter\tkinter simple calculator.py", line 27, in equal
   answer = int(f_num) + int(second_number)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'method'

I'm trying to make a simple calculator program btw with THIS TYTORIAL


r/pythonhelp • • May 09 '22

Spreadsheet Row Matching in Python

3 Upvotes

Hello! I would be very grateful if someone could take a look at this question and provide help. https://stackoverflow.com/q/72153238/8387181


r/pythonhelp • • May 07 '22

HOMEWORK Loading csv into pandas

3 Upvotes

Hi there, I need help debugging this code.

I am trying to add a csv file to my pandas data frame.

import pandas as pd
df = pd.read_csv ('batting.csv')
print(df)

When I execute this code I am getting this error:

FileNotFoundError: [Errno 2] No such file or directory: 'batting.csv'

I then tried to change the directory using os and I am coming across this error:

os.getcwd()
os.chdir(r"C:\Users\crack\Downloads\excel\batting.csv")

NotADirectoryError: [WinError 267] The directory name is invalid: 'C:\\Users\\crack\\Downloads\\excel\\batting.csv'

I have been googling all day trying to fix this


r/pythonhelp • • May 06 '22

Searching Multiple Lists for 2 Things

3 Upvotes

Hey there, first time here. I'm very new to Python and don't know a whole lot, so excuse my illiteracy.
I'm trying to make a chess game. I don't need to do any visuals, it's only operational stuff. Currently, I have it set up so that it's 8 separate lists with 8 items in each list that represent the pieces or blank spaces.

I need help determining if the game has ended. My current idea was trying to figure out if both kings were on the board by searching for the numbers (151 and 251) in all 8 lists. If they're not, then it searches for which one is still there to determine the winner. How might someone go about this?


r/pythonhelp • • Apr 10 '22

Don't know the correct terminology to ask for a "loop within" function

3 Upvotes
def loopWithin(array, num):
    lenArray = len(array)
    if num >= lenArray:
        i = num - (int(num/lenArray)*lenArray)
    else:
        i = num
    return(array[i])

myArray = ['red', 'green', 'blue']    

for i in range(5):
    print(i, loopWithin(myArray, i))
"""
Output:
0 red
1 green
2 blue
3 red
4 green
"""

r/pythonhelp • • Mar 07 '22

Question about restarting loop and tracking scores on number game

3 Upvotes

So i have been working on a number game where the program picks a number and the user has to guess the number. the one problem I am having is trying to start the loop from the start. the second part I dont know where to start is how to track the users lowest guess being the best "attempt." If you guys could please help me in any way, that would be awesome lol.

https://pastebin.com/gjXp1ruU


r/pythonhelp • • Feb 22 '22

Right way to pause a script?

3 Upvotes

I'm making a script that will pull crypto prices and a few stock prices every so many minutes. Last script I wrote I had a few people saying time.sleep(60) is bad then system("pause") is bad. Wtf is the right way to pause a script? Have seen several people say this and that I just want y'all's opinion.


r/pythonhelp • • Feb 18 '22

Code below is giving me an empty list. What am I doing wrong here?

3 Upvotes

a = list(range(0,300,-2))

print(a)


r/pythonhelp • • Feb 17 '22

Problems Downloading Pygme

3 Upvotes

I've been trying to download Pygame for a while now. I've tried on three separate computers, and they've all given me the same error message, so I assume I'm doing something wrong. I have the latest version of python installed, and when I did so, I was sure to tick the little box labelled 'pip'. However, when I type 'pip install pygame' into the shell, it gives:

pip install pygame

SyntaxError: invalid syntax

The spoiler is there to indicate what's highlighted. This might be a pygame problem, rather than a python problem, but asking here can't help. So... what am I doing wrong? I've looked about, and no one seems to have the same problem as me, so it feels like I'm making some obvious mistake, but I'd appreciate any help y'alls can give

EDIT: I have since solved the problem. Thanks for all your help.


r/pythonhelp • • Feb 10 '22

how can I create a command-line program using pandas or numpy that can be ran on anyone's machine?

3 Upvotes

To run it on my machine, I need to install pandas and create an environment and all that.

This is a coding challenge from the employer and they say they should be able to run it on their machine.

I could always put the install instructions in a readme, but is there a way to have it all contained within the program?


r/pythonhelp • • Jan 28 '22

a very noob question

3 Upvotes

i wrote these two lines:

>>> numbers = "123456789"

>>> numbers[-9:-1]

than it said '12345678' instead of '123456789'

what to do?


r/pythonhelp • • Jan 22 '22

Trying to switch python verion of virtualenv.

3 Upvotes

im using the below code to change my virtualenv's python version from 3.8 to 3.7 :

virtualenv venv -p

"C:\Users\The Gem\AppData\Local\Programs\Python\Python37\python.exe"

where

the path mentioned in the above instruction has the executable python file for python 3.7 but when i run the instruction it gives an :

FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\The Gem\\AppData\\Local\\Programs\\Python\\Python37\

\Lib\\venv\\scripts\\nt\\python.exe'

i dont seem to understand why the error is coming up , cause when i go to the path i have mentioned above in instruction the python.exe is there.

and why is it going at Lib\venv\scripts........ when the python.exe is nowhere near there.


r/pythonhelp • • Jan 14 '22

Script that Automatically provides input() in terminal.

3 Upvotes

File A is designed to automate a process and has a for loop that calls file B.

File B has an input() function, and when it it called it halts the for loop until a user input is provided.

Is there a way where I can automatically fill the input within the terminal?

(Note: I am unable to alter file B)


r/pythonhelp • • Jan 07 '22

Why Is This Not Working

3 Upvotes

I'm trying to make a script that pings a Minecraft Server (using inputs) every little bit, so the server always stays online. But there are a few errors and I don't know why. I've only been using Python for a few Months.

import time
from mcstatus import MinecraftServer
print("Minecraft Server Pinger")
print("By:  ViridianTelamon.")
print("The Server Will Be Pinged Every 5 Minutes Until You Close This Script.")
Server = input("Enter Your Minecraft Java Server IP (Example:  Server.aternos.me):  ")
Port = input("Enter Your Minecraft Java Port Or Host (Example: 12345678910):  ")
Seconds = int(input("Enter The Amount Of Seconds For Intervals Between Server Pings:  "))
while True:
    time.sleep(280)
    server = MinecraftServer.lookup(Server,":",Port)
    latency = server.ping()
    print(f"The server replied in {latency} ms")


r/pythonhelp • • Jan 05 '22

SOLVED why is this piece of code not working?

3 Upvotes

need some help with a discord bot I'm making

https://paste-bin.xyz/30524

this is the code had to use paste bin since Reddit is unindenting my code when I press post. Anyway Its all worked up until the part where its responds with a bye (username) for some reason when i use to put in - bye oasis instead of the bot saying bye then the user's name says nothing. this is weird because the part that's right above it that's almost identical is working fine.

also the last part with the random number isn't working but I'm gonna fix it later I think I know how to win


r/pythonhelp • • Dec 29 '21

Simulate Opening File Inside Script

3 Upvotes

I want to be able to simulate opening a file inside a script. This avoids me from creating a physical file. I have this:

import io

fake_file = io.StringIO('''
0 2021-12-21
1 2021-12-20
2 2021-12-19
3 2021-12-18
''')

def get_final_line(filename):
    with open(fake_file) as f:
        lines = [i for i in f.read().strip().split('\n')]
        return lines[-1]

get_final_line('/tmp/test.txt')

Originally, I had a physical "/tmp/test.txt", but I am trying to avoid this. So, I saw io.StringIO and according to this, it seems like io.StringIO returns a file-like object? So, I thought it might be possible, when I run this, I get this error:

TypeError: expected str, bytes or os.PathLike object, not StringIO

Anyway, what I want is to define a fake_file variable that represents the content of the file, then, later on, have the open function read the fake file as if it is reading a real file. Is this possible?


r/pythonhelp • • Dec 17 '21

Newbie Code Question

3 Upvotes

Hi, im a Crossfitter and always want to workout the halfway point of some workouts, so im trying to make something that does this for me as practice for python, which im very new to. the code works but it only prints halfway_round as the intial value of "undefined" and doesnt redefine it with the if statement. Why is this? As said, im very very new to coding so please dont trash this too much, im just trying to learn!

##Rep Scheme Halfway Calculatorreps_a = []reps_b = []total_a = 0total_ - Pastebin.com


r/pythonhelp • • Dec 07 '21

HOMEWORK Limiting user input to a number range

3 Upvotes
b = int(input("boiling point: "))

p = (5*b-400)

if (p > 100):
    print(p)
    print(1)
elif (p == 100):
    print(p)
    print(0)
else: 
    print(p)
    print(-1)

How can I allow the user to only input an integer from 80 (including 80) to 200 (including 200). Thanks!


r/pythonhelp • • Nov 22 '21

Is there a way to be able to open and read any csv file as a dictionary?

3 Upvotes

I’m a bit new to coding, but I was just wondering if there is a way to use the input function in python and have it open and read whatever file is put in provided that file exists? Then have that file read as a dictionary?

Edit: okay so I found out how to read any file, I’m just wondering how that can be turned into a dictionary?