Search the Community
Showing results for tags 'python 3'.
-
< import time import requests def get_random_quote(): try: response = requests.get("https://quote-garden.herokuapp.com/api/v3/quotes/random") if response.status_code == 200: json_data = response.json() data = json_data['data'] print("Tere!") time.sleep(3.5) print("Ma olen teie vrtuaalne assistent.") nimi = str(input("Mis on teie nimi?")) print(("Tere, ") + nimi) vanus = str(input("Kui vana te oled?")) print(nimi + (", teie vanus on ") + vanus + ".") hinne1 = input(nimi + (", mis on teie esimene hinne?")) hinne2 = input(nimi + (", mis on teie teine hinne?")) hinne3 = input(nimi + (", mis on teie kolmas hinne?")) vastus = ((int(hinne1) + int(hinne2) + int(hinne3))/3) print(nimi + " sinu vastatud tulemuste järgi, sinu keskmine hinne on " + str(vastus)) if vastus >= 4: time.sleep(3) print("timm") else: time.sleep(2) print("jamps") if vastus > 5: time.sleep(3) print("kuid oled häkker!") time.sleep(2) print(("Sinu andmed on: ") + nimi + (", oled ") + vanus + (" vana ja sinu hinnete keskmine on ") + str(vastus) + (".")) time.sleep(2) kas_õige = input("Kas teie sisestatud andmed on kõik õiged?") if kas_õige == str("jah"): print("Hästi, te olete sisestanud kõik teie andmed õigesti!") else: print("Kahju, kuid oli hea teiega kohuda!") tsitaat = input("Kas te tahate saada suvalist tsitaati?") if tsitaat == str("jah"): print(data[0]['quoteText']) else: print("Tuli viga tsitaadi saamisel!") except: print("Midagi läks valesti! Proovi uuesti!") else: while True: continue vastus_lõpp = None while answer not in ("jah", "ei"): answer = input("Kas te tahate vestlust lõpetada?") if answer == "jah": elif answer == "ei": break else: print("Palun sisestage, kas ei või jah.") #Programmi lõpp time.sleep(3.5) while True: print("Näeme varsti!") time.sleep(1.5) print(("Head aega, ") + nimi + ("!")) time.sleep(2) break >
- 5 replies
-
- python 3
- unexpected unindent
-
(and 1 more)
Tagged with:
-
import random random_name = random.randint(1, 3) random_question = random.randint(1, 3) # print(random_question) Used to test if random number is working. ## name = "" and name = "Alex" is being used to test if questions print without a name. name = "" name = "Alex" name = "Steve" if random_name == 1: name == 1 print(" ") elif random_name == 2: name == 2 print("Alex") elif random_name == 3: name == 3 print("Steve") else: name == ("Please provide a name") question = "" print(name, "Asks: ", question) if random_question == 1: question = 1 print("Is today Wednesday?") elif random_question == 2: question = 2 print("Is 28 an old age") elif random_question == 3: question = 3 print("did this work") else: random_question == "Error" #The above should print differer 3 Questions and an error, Below should answer 9 different Questions and give an error.# random_number = random.randint(1, 9) answer = "" print("Magic 8-Ball's answer: ", answer) if random_number == 1: answer = 1 print("Yes - definitely") elif random_number == 2: answer = 2 print("It is decidedly so.") elif random_number == 3: answer = 3 print("Without a doubt.") elif random_number == 4: answer = 4 print("Reply hazy, try again.") elif random_number == 5: answer = 5 print("Ask again later.") elif random_number == 6: answer = 6 print("Better not tell you now.") elif random_number == 7: answer = 7 print("My sources say no.") elif random_number == 8: answer = 8 print("Outlook not so good.") elif random_number == 9: answer = 9 print("Very doubtful.") else: answer = "Error" Hi, so i'm learning pythong currently and been set with the task of creating a magic 8 ball, i've managed to get it working for 1 name to output 3 different questions with 9 possible answers, now ive been tasked with printing out the questions without a name but instead its printing 2 different names with a different question and answer each time. does anybody know why my code wont ask a question with a blank name.
-
Hi all! I wish to share the discovery i made for deleting the last line in the console on python 3, I hope this can help someone, any questions please redirect to me, Thanks, Blake code: import os import sys import time #last line deletion def delete_last_line(): "Use this function to delete the last line in the STDOUT" #cursor up one line sys.stdout.write('\x1b[1A') #delete last line sys.stdout.write('\x1b[2K') ###DEMO### print("this line will delete in 5 seconds") time.sleep(5) delete_last_line() The link to the github with the code and more is : https://github.com/Blake-McCullough/LastLinePython3Delete/tree/main Attached is also the file for deleting the last line if u wish to just download it. Last line python 3 delete.py
-
I have no clue what to do for this script I need to create a module, that gives random images from URL's and prints them This is for a discord bot if that info helps
-
I am writing a program to approximate pi using different methods, I am on my first method, Basel problem which comes in the following notation: pi2/6 = 1/1 + 1/4 + 1/9 + 1/16 + 1/25 My code is a function: import math percision = float(input("Enter the percision for the calculation: ")) def basel(percision): basel_result = 0 basel_total = math.sqrt(basel_result * 6) basel_term = 0 for basel_term in range(1, basel_term): if math.sqrt(6* basel_result) < math.pi(percision): #loop keeps adding until the result is within the accuracy value of pi basel_term = basel_term + 1 basel_result = basel_result + 1/basel_term**2 return(basel_total, basel_term) print(basel(percision)) However, every time I enter the percision value (say 0.1) it returns the output (0.0, 0). What am I doing wrong?
-
Hi, I am pretty new to python (and programming in general), I am trying to create a curve fit to my data, I am loading two arrays 'Tnn_month' and 'amon_month' from .mat files, I want to create a scatter plot of these two parameters and then assign a curve fit to show the correlation between both, I tried to apply the curve_fit examples done on simple plots, but I still get this error: error: Result from function call is not a proper array of floats. Tnn_month (x) and amon_month (y) are both arrays of length 5433656 find attached the scatter plot ----------------------------------------------------- input: import numpy as np import matplotlib.pyplot as plt import scipy.io as io import pandas as pd import seaborn as sns from matplotlib.pyplot import figure MainFolder= r"/home/abeed/Documents/thesis/python/scatter/" yyyymm_str= '201005' d_or_n = 'day' colors = (0,0,0) area = np.pi*3 #load data mat = io.loadmat('Tnn_amon0.01_201005.mat') Tnn_month = mat['Tnn_index'] amon_month = mat['amon_index'] colors=np.array([0.1, 0.5, 0.5]) # scatter plot figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') plt.scatter(Tnn_month, amon_month, s=area, c=colors, alpha=0.5) plt.title('May 2010', fontsize=14) plt.ylabel('Ammonia Total Concentration (molec/cm$^{2}$)',fontsize=14) plt.xlabel('Skin Temperature (Kelvin)', fontsize=14) plt.savefig(MainFolder + yyyymm_str + '_test_' + d_or_n +'.png', format='png', dpi=700) #plt.show() # curve_fit import matplotlib.pyplot as plt from scipy.optimize import curve_fit import numpy as np Tnn_month[np.isnan(Tnn_month)]=0 #something for nans amon_month[np.isnan(amon_month)]=0 def func(X, a, b, c): return a * np.exp(-b * X) + c Y = func(Tnn_month, 2.5, 1.3, 0.5) np.random.seed(len(Tnn_month)) print(Tnn_month) popt, pcov = curve_fit(func, Tnn_month, amon_month) plt.plot(Tnn_month, func(Tnn_month, *popt), 'g--',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt)) plt.show() -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- output: [[272.64697509] [273.43998094] [272.89872854] ... [265.03563904] [264.87200613] [273.74241245]] --------------------------------------------------------------------------- ValueError Traceback (most recent call last) ValueError: object too deep for desired array --------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-2-2ed29e6832ed> in <module> 71 print(Tnn_month) 72 ---> 73 popt, pcov = curve_fit(func, Tnn_month, amon_month) 74 75 plt.plot(Tnn_month, func(Tnn_month, *popt), 'g--',label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt)) ~/anaconda3/lib/python3.7/site-packages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs) 750 # Remove full_output from kwargs, otherwise we're passing it in twice. 751 return_full = kwargs.pop('full_output', False) --> 752 res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs) 753 popt, pcov, infodict, errmsg, ier = res 754 cost = np.sum(infodict['fvec'] ** 2) ~/anaconda3/lib/python3.7/site-packages/scipy/optimize/minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag) 394 maxfev = 200*(n + 1) 395 retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol, --> 396 gtol, maxfev, epsfcn, factor, diag) 397 else: 398 if col_deriv: error: Result from function call is not a proper array of floats.
-
I'm working on my A-Level Computer Science Project part of which grabs data from the google books API. I have some working code which does this and I wrote into my program last year. Over the summer, the school updated all of the computers to windows 10 and since then, the requests module is unable to connect to the API to get the data. It shouldn't be the OS update since I run Windows 10 at home and it works just fine there. The error below indicates that it's a proxy issue which must be from the schools proxy filter for websites like youtube and facebook but they had the same filter last year and I can still view the data from the API by pasting the address into Chrome. Does anyone know a workaround or solution that means the program can still grab the data?
-
-
""" ### Program Design ### Purpose: calculate the monthly bill based on the gas consumption Input data: gas consumption Output data: montly gas bill Algorithm: - create header print "*" * 70 print title "*", " " * 10, "Welcome to Gas Bill Calculator", " " * 15, "*" print title "*", "(This program developed by student name (ID: ******))" "*" print "*" * 70 - customer name from user - previous month reading from user - current meter reading from user - compute the amount of gas comsumed gasCons = abs (currentRead - previousRead) - compute the bill gasBill = gasCons * appliedRate - print the result """ ### Program Implementation ### # create header print ("*" * 60) print ("*", " " * 9, "Welcome to Gas Bill Calculator", " " * 15, "*") print ("*", "(This program developed by student name (ID: ******) " "*") print ("*" * 60) # customer name from user custName = input ("Please enter your name: ") # previous month reading from user previousRead = int (input ("Please enter previous Gas Meter Reading: ")) if previousRead < 0000 or previousRead > 9999 : print ("ERROR IN PREVIOUS READING(OUT OF RANGE:0000-9999). TRY AGAIN!") elif previousRead != int ( ) : print ("ERROR IN THE PREVIOUS READING(USE FOUR DIGIT NUMBER(%.4d)). TRY AGAIN!" %previousRead) # current meter reading from user currentRead = int (input ("Please enter new Gas Meter Reading: ")) if currentRead < 0000 or currentRead > 9999 : print ("ERROR IN NEW READING(OUT OF RANGE:0000-9999). TRY AGAIN!") elif currentRead != int ( ) : print ("ERROR IN THE NEW READING(USE FOUR DIGIT NUMBER(%.4d)). TRY AGAIN!" %currentRead) # compute the amount of gas consumed gasCons = abs (currentRead - previousRead) # compute the bill minimumCost = 3.500 if gasCons >= 0 or gasCons <= 70 : gasBill = minimumCost elif gasCons >= 71 or gasCons <= 170 : gasBill = minimumCost + 0.0003 / gasCons elif gasCons >= 171 or gasCons <= 400 : gasBill = minimumCost + 0.0015 / gasCons else : gasBill = minimumCost + 0.0075 / gasCons # print the result print ("Dear ", custName, ", your gas comsumption bill is as follows:") print ("-" * 60) print ("Gas Consumed:", " " * 21, "%.d cubic meters" %gasCons) print ("Bill amount:", " " * 20, "%.3f Omani Rials" %gasBill) print ("-" * 60) I'm trying to create a program where you have to use 4 digits for it to continue and if you don't then you get an error message. It works well when i use 1 - 3 digits but i still get an error when I use the intended 4 digits. (previous and current readings) I also want to know how to make the program restart whenever it shows the error message, currently it will prints the error message but would still print the next input message. Anyone knows how to make this work? Any tips? *** You can ignore the computing part of this program, it's still needs tuning. ***
-
To start this off: I was given a lab assignment to draw "ASCII art". The task consisted of outputting my initials, a house, and an animal. I completed the task, it has already been turned in, and graded. Neither my teacher, TA, nor myself can find a solution to the problem that is outlined below. The goal of the program is to draw "ASCII art" to the console. I chose to use lists of lists to represent a 2 dimensional plane instead of writing a bunch of print() statements because later in the year the teacher/TA is going to break the program and make us fix it. I believe that this will be much easier to "maintain" later. Here is the code in question (sorry for no highlighting, none of the options works well with python) # Initials returns a 2 dimensional array (list of lists) with the mapping for my initials. Rows = 7, Columns = 12 def Initials(): myInitials = [[], [], [], [], [], [], [], [], [], [], [], []] # Initialize all sub arrays. for i in range(0, 7): for j in range(0, 12): myInitials[i].append(j) # Initialize first row. myInitials[0][0] = 32 myInitials[0][1] = 95 myInitials[0][2] = 95 myInitials[0][3] = 95 myInitials[0][4] = 95 myInitials[0][5] = 95 myInitials[0][6] = 32 myInitials[0][7] = 32 myInitials[0][8] = 95 myInitials[0][9] = 95 myInitials[0][10] = 95 myInitials[0][11] = 32 # Initialize second row. myInitials[1][0] = 32 myInitials[1][1] = 32 myInitials[1][2] = 32 myInitials[1][3] = 124 myInitials[1][4] = 32 myInitials[1][5] = 32 myInitials[1][6] = 32 myInitials[1][7] = 32 myInitials[1][8] = 124 myInitials[1][9] = 32 myInitials[1][10] = 124 myInitials[1][11] = 32 # Initialize third row. myInitials[2][0] = 32 myInitials[2][1] = 32 myInitials[2][2] = 32 myInitials[2][3] = 124 myInitials[2][4] = 32 myInitials[2][5] = 32 myInitials[2][6] = 32 myInitials[2][7] = 32 myInitials[2][8] = 124 myInitials[2][9] = 32 myInitials[2][10] = 124 myInitials[2][11] = 32 # Initialize fourth row. myInitials[3][0] = 32 myInitials[3][1] = 32 myInitials[3][2] = 32 myInitials[3][3] = 124 myInitials[3][4] = 32 myInitials[3][5] = 32 myInitials[3][6] = 32 myInitials[3][7] = 32 myInitials[3][8] = 124 myInitials[3][9] = 95 myInitials[3][10] = 95 myInitials[3][11] = 95 # Initialize fifth row. myInitials[4][0] = 32 myInitials[4][1] = 32 myInitials[4][2] = 32 myInitials[4][3] = 124 myInitials[4][4] = 32 myInitials[4][5] = 32 myInitials[4][6] = 32 myInitials[4][7] = 32 myInitials[4][8] = 124 myInitials[4][9] = 32 myInitials[4][10] = 32 myInitials[4][11] = 124 # Initialize sixth row. myInitials[5][0] = 32 myInitials[5][1] = 32 myInitials[5][2] = 32 myInitials[5][3] = 124 myInitials[5][4] = 32 myInitials[5][5] = 32 myInitials[5][6] = 32 myInitials[5][7] = 32 myInitials[5][8] = 124 myInitials[5][9] = 32 myInitials[5][10] = 32 myInitials[5][11] = 124 # Initialize seventh row. myInitials[6][0] = 95 myInitials[6][1] = 95 myInitials[6][2] = 95 myInitials[6][3] = 47 myInitials[6][4] = 32 myInitials[6][5] = 32 myInitials[6][6] = 32 myInitials[6][7] = 32 myInitials[6][8] = 124 myInitials[6][9] = 95 myInitials[6][10] = 95 myInitials[6][11] = 124 # Pass the jagged array back to the caller. return myInitials # DrawToScreen takes a 2 dimensional array containing decimal ASCII chars and draws them to the screen # as if it were art. All maps must be regular rectangles, with the format being myList[rows][columns] def DrawToScreen( charMap, rows, columns ): for i in range(0, rows): for j in range(0, columns): print(chr(charMap[i][j]), end="") print("") # testing how to print the picture to the screen. For some reason, writes "None" under all output. print(DrawToScreen(Initials(), 7, 12)) When run, the final print() statement that calls DrawToScreen exits after writing "None" to the console, after successfully drawing the art as intended. Come to think of it, I may have just answered my own question. Is the correct answer: By embedding the DrawToScreen function in a print statement, am I causing nested print statements, with the outer print statement having nothing to print, so prints "None"?
-
I need help sorting my list of tuples it needs to be from least to greatest. Any help would be greatly apreciated in_file = open("scores.txt")high_scores = []for line in in_file: score, name = line.split(", ") high_scores += [(score, name)]print(high_scores)high_scores = sorted(high_scores) ##NOT WORKINGprint(high_scores)for scores in high_scores: score, name = scores[0], scores[1].strip() space_to_add_to_name = 28 - len(name) name += " " * space_to_add_to_name space_to_add_to_score = 3 - len(score) score = " " * space_to_add_to_score + score print(name + score) the scores.txt 4, Jimi Hendrix3, Nuno Bettencourt12, Eric Gales5, Lincoln Brewster console output [('4', 'Jimi Hendrix'), ('3', 'Nuno Bettencourt'), ('12', 'Eric Gales'), ('5', 'Lincoln Brewster')][('12', 'Eric Gales'), ('3', 'Nuno Bettencourt'), ('4', 'Jimi Hendrix'), ('5', 'Lincoln Brewster')]Eric Gales 12Nuno Bettencourt 3Jimi Hendrix 4Lincoln Brewster 5