From edwinconnell at gmail.com Mon May 1 10:41:15 2023 From: edwinconnell at gmail.com (Ed Connell) Date: Mon, 1 May 2023 09:41:15 -0500 Subject: [Tutor] What's going on? In-Reply-To: References: Message-ID: Thanks to all. You have given me some new ideas about things to try. Of course On Sun, Apr 30, 2023 at 9:44?PM ThreeBlindQuarks wrote: > > > I looked at your message again Ed and I see you ran the program several > ways including just running the .py file on windows. > > So my suggestion is to use whatever command line program you have, > including those that let you redirect output to a file like the bash we > bashed a few days ago. I tested the default shell on Windows of CMD like so: > > C:\Users\xyz>echo "hi" > "hi" > > C:\Users\xyz>echo "hi" >temp.txt > > C:\Users\xyz>more temp.txt > "hi" > > So it allows redirection and if you run python as in: > > python file >temp.txt > > Or something similar, and view it with a pager like I did that shows only > a screen at a time, or you can use a text editor. Ideally, all the output > will get captured as file I/O may not be as delicate as whatever comes to > your screen. I have never had such a problem when I run python with output > in RSTUDIO, idle, Jupyter Notebook and so on. > > If that works, great. > > And, of course, with a bit of work, you can change the internals of your > code to slow down the output, redirect file descriptors for stdout, or just > have it pause and ask what to do next. > > Your program seems to work and is logically sound. > > > Sent with Proton Mail secure email. > > ------- Original Message ------- > On Sunday, April 30th, 2023 at 10:32 PM, ThreeBlindQuarks < > threesomequarks at proton.me> wrote: > > > > Ed, > > > > Thank you for supplying code that works and is brief enough to try. > > > > My only glitch was one of your comments lines that became two lines > which resulted in an error easy to fix so it did not try to "trip". > > > > I got lots of output but as I understand it, you simply wanted to do > something N==10 times. You could have encapsulated all the calculations in > a function which would cleanly have avoided some issues of your reusing > variables. > > > > So you initialize these each time: > > > > res = [] > > nums = [] > > ct = [] > > > > Your next code segment seems to re-populate some of these variables > > > > > > I get this when I examine variables at the end: > > > > ct: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] > > nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > > > which makes me wonder if this method is one that could be done > differently in perhaps a more Pythonic way. You do this: > > > > for i in range(10): > > ct.append(0) > > nums.append(i) > > > > No error here but consider you are asking for a group of N zeros in a > row for the first and a sequence from 0 to N-1 for the second. > > > > I personally might have combined all the beginning code into these three > lines: > > > > N = 10 > > res = [] > > nums = list(range(N)) > > ct = [0] * N > > > > Again, nothing wrong with your code so far. Just an alternate viewpoint > and note I set a parameter called N to make the code flexible if changed at > a single point. > > > > This removes an explicit loop and replaces it with two hidden implicit > loops, albeit perhaps implemented faster internally. > > > > I am not clear on why you have commented out code about sleeping. It is > hinting at something. Is there some concern you did not share? I am not > aware any pause is needed unless you want results not to flow off the > screen. > > > > Again, just to show an alternative perspective, you can insert a line of > code like this: > > > > _ = input("Press RETURN to see next results:") > > > > This stops processing after displaying a prompt and waits for the user > to hit any keys and a return (and effectively ignores that) before > continuing. Again, not really needed as you can often just scroll up in the > output and see quite a bit. > > > > Now I recall the earlier request was to pick random numbers and never > use any one more than four times. I am not sure if your code plans on > anything like variations of that. Your next section hard-codes in precisely > thirty times in a loop that you shuffle the numbers (initially from 0 to 9) > in place and then you pick just the first and append that to res for an > eventual result. > > > > random.shuffle(nums) > > res.append(nums[0]) > > print(res) > > > > That seems like a bit of extra work to shuffle the whole thing over and > over just to get one at random. What is the advantage over just picking a > random number from 0 to 9 each time rather than picking lots of them to > re-arrange the deck chairs on the Titanic? But, FWIW, it does get you a > random number to add to the growing collection. > > > > The next section explains this odd choice as the list to choose from > changes dynamically: > > > > if ct[nums[0]] == 4: > > print( 'Removing', nums[0],nums ) > > nums = nums[1:] > > print('leaving', nums ) > > > > This may have been your problem so I checked. The logic is that once you > have used a number four times, remove it and shrink the pool of available > to choose from to 9 then later 8 and so on. Is that carried out carefully? > You are removing the zeroth item by making a copy of the rest of the list. > I would consider an alternate of: > > > > nums.pop(0) > > > > Which throws away the first and changes the list in place. Note it can > also be used to just remove the nth. So if you just picked a random number > from zero to the current length of the list, I am guessing it might be > easier to just remove any that reached 4 and never scramble an entire list. > > > > The rest of the loop is just print statements. > > > > So logically, what should happen in the inner loop? Thirty numbers > should be chosen first from 10 possibilities so res should keep growing and > stop at 30 entries. The ct variable always remains at length 10 with > entries rising from 0 towards 4 and never exceeding it. The nums list > should shrink and above 40 should disappear and perhaps cause problems > beyond that as there is nothing to scramble and use. At 30, it should be > safe. But ideally, your algorithm should break out of a loop if everything > has hit 4, or alternately if the number of items to choose from reaches > zero. > > > > So I ran the code and I am embarrassed to say I did not see anything > wrong. It seems to do exactly what it is designed to do. My guess is you > are using something that cannot keep up with the I/O and produces glitches > on your screen. The fact that it happens after the first run may be a clue > that some buffer is being over-run or something. > > > > So, yes, your sleep attempts make some sense but you may also consider > redirecting the output to a file in one of many ways and then viewing the > file with something like a text editor and seeing if that looks like you > expect. > > > > If so, there is nothing wrong with your program but something not quite > great about some aspect of your environment. > > > > Anyone else try to run this and get an odd output? > > > > Q > > > > > > > > > > > > > > Sent with Proton Mail secure email. > > > > > > ------- Original Message ------- > > On Sunday, April 30th, 2023 at 5:31 PM, Ed Connell > edwinconnell at gmail.com wrote: > > > > > > > > > Greetings, > > > > > > I got interested in one of your earlier problems, but THAT PROBLEM is > not > > > what I am asking about. It was to generate a random sequence, each > taken > > > from a predefined pool. However, nothing is to be used more than four > > > times. Moderately interesting. > > > > > > What I am asking about is this. The first time it runs perfectly. > However > > > subsequent runs, sooner or later, foul up. > > > ############################### > > > import random > > > import time > > > > > > for run in range(10): #usually 1 but trying multiple runs through in > one > > > trip. > > > > > > # build result, number choices, and choice count lists > > > res = [] > > > nums = [] > > > ct = [] > > > > > > for i in range(10): > > > ct.append(0) > > > nums.append(i) > > > > > > print('\n\n', run, ' start\n') > > > > > > #time.sleep(0.016) # seems to work for 0.016 or more uncommented > > > > > > for _ in range( 30 ): # tried 10 - 40 > > > random.shuffle(nums) > > > res.append(nums[0]) > > > print(res) > > > ct[nums[0]] += 1 > > > if ct[nums[0]] == 4: > > > print( 'Removing', nums[0],nums ) > > > nums = nums[1:] > > > print('leaving', nums ) > > > > > > print() > > > print('numbers left',sorted(nums)) > > > print('result',res) > > > print('number used of each',ct) > > > #################################### > > > The problem seems to be a difference between printing and calculation > speed > > > but maybe not. > > > > > > I tried mostly using Geany, but also just ran the .py file. > > > > > > The bad output has incomplete lines as well as missing sections. > > > > > > I will appreciate your ideas. > > > > > > Oh, I am running on Windows 11, an hp with AMD 7. > > > > > > Ed Connll > > > -- > > > I have a right and a left brain, but there is nothing right in the > left one > > > and there is nothing left in the right one! > > > _______________________________________________ > > > Tutor maillist - Tutor at python.org > > > To unsubscribe or change subscription options: > > > https://mail.python.org/mailman/listinfo/tutor > -- I have a right and a left brain, but there is nothing right in the left one and there is nothing left in the right one! From edwinconnell at gmail.com Mon May 1 10:55:06 2023 From: edwinconnell at gmail.com (Ed Connell) Date: Mon, 1 May 2023 09:55:06 -0500 Subject: [Tutor] What's going on? In-Reply-To: References: Message-ID: Thanks to all. I'll try your suggestions. Ed Connell On Mon, May 1, 2023 at 9:41?AM Ed Connell wrote: > Thanks to all. You have given me some new ideas about things to try. > Of course > > On Sun, Apr 30, 2023 at 9:44?PM ThreeBlindQuarks < > threesomequarks at proton.me> wrote: > >> >> >> I looked at your message again Ed and I see you ran the program several >> ways including just running the .py file on windows. >> >> So my suggestion is to use whatever command line program you have, >> including those that let you redirect output to a file like the bash we >> bashed a few days ago. I tested the default shell on Windows of CMD like so: >> >> C:\Users\xyz>echo "hi" >> "hi" >> >> C:\Users\xyz>echo "hi" >temp.txt >> >> C:\Users\xyz>more temp.txt >> "hi" >> >> So it allows redirection and if you run python as in: >> >> python file >temp.txt >> >> Or something similar, and view it with a pager like I did that shows only >> a screen at a time, or you can use a text editor. Ideally, all the output >> will get captured as file I/O may not be as delicate as whatever comes to >> your screen. I have never had such a problem when I run python with output >> in RSTUDIO, idle, Jupyter Notebook and so on. >> >> If that works, great. >> >> And, of course, with a bit of work, you can change the internals of your >> code to slow down the output, redirect file descriptors for stdout, or just >> have it pause and ask what to do next. >> >> Your program seems to work and is logically sound. >> >> >> Sent with Proton Mail secure email. >> >> ------- Original Message ------- >> On Sunday, April 30th, 2023 at 10:32 PM, ThreeBlindQuarks < >> threesomequarks at proton.me> wrote: >> >> >> > Ed, >> > >> > Thank you for supplying code that works and is brief enough to try. >> > >> > My only glitch was one of your comments lines that became two lines >> which resulted in an error easy to fix so it did not try to "trip". >> > >> > I got lots of output but as I understand it, you simply wanted to do >> something N==10 times. You could have encapsulated all the calculations in >> a function which would cleanly have avoided some issues of your reusing >> variables. >> > >> > So you initialize these each time: >> > >> > res = [] >> > nums = [] >> > ct = [] >> > >> > Your next code segment seems to re-populate some of these variables >> > >> > >> > I get this when I examine variables at the end: >> > >> > ct: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] >> > nums: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> > >> > which makes me wonder if this method is one that could be done >> differently in perhaps a more Pythonic way. You do this: >> > >> > for i in range(10): >> > ct.append(0) >> > nums.append(i) >> > >> > No error here but consider you are asking for a group of N zeros in a >> row for the first and a sequence from 0 to N-1 for the second. >> > >> > I personally might have combined all the beginning code into these >> three lines: >> > >> > N = 10 >> > res = [] >> > nums = list(range(N)) >> > ct = [0] * N >> > >> > Again, nothing wrong with your code so far. Just an alternate viewpoint >> and note I set a parameter called N to make the code flexible if changed at >> a single point. >> > >> > This removes an explicit loop and replaces it with two hidden implicit >> loops, albeit perhaps implemented faster internally. >> > >> > I am not clear on why you have commented out code about sleeping. It is >> hinting at something. Is there some concern you did not share? I am not >> aware any pause is needed unless you want results not to flow off the >> screen. >> > >> > Again, just to show an alternative perspective, you can insert a line >> of code like this: >> > >> > _ = input("Press RETURN to see next results:") >> > >> > This stops processing after displaying a prompt and waits for the user >> to hit any keys and a return (and effectively ignores that) before >> continuing. Again, not really needed as you can often just scroll up in the >> output and see quite a bit. >> > >> > Now I recall the earlier request was to pick random numbers and never >> use any one more than four times. I am not sure if your code plans on >> anything like variations of that. Your next section hard-codes in precisely >> thirty times in a loop that you shuffle the numbers (initially from 0 to 9) >> in place and then you pick just the first and append that to res for an >> eventual result. >> > >> > random.shuffle(nums) >> > res.append(nums[0]) >> > print(res) >> > >> > That seems like a bit of extra work to shuffle the whole thing over and >> over just to get one at random. What is the advantage over just picking a >> random number from 0 to 9 each time rather than picking lots of them to >> re-arrange the deck chairs on the Titanic? But, FWIW, it does get you a >> random number to add to the growing collection. >> > >> > The next section explains this odd choice as the list to choose from >> changes dynamically: >> > >> > if ct[nums[0]] == 4: >> > print( 'Removing', nums[0],nums ) >> > nums = nums[1:] >> > print('leaving', nums ) >> > >> > This may have been your problem so I checked. The logic is that once >> you have used a number four times, remove it and shrink the pool of >> available to choose from to 9 then later 8 and so on. Is that carried out >> carefully? You are removing the zeroth item by making a copy of the rest of >> the list. I would consider an alternate of: >> > >> > nums.pop(0) >> > >> > Which throws away the first and changes the list in place. Note it can >> also be used to just remove the nth. So if you just picked a random number >> from zero to the current length of the list, I am guessing it might be >> easier to just remove any that reached 4 and never scramble an entire list. >> > >> > The rest of the loop is just print statements. >> > >> > So logically, what should happen in the inner loop? Thirty numbers >> should be chosen first from 10 possibilities so res should keep growing and >> stop at 30 entries. The ct variable always remains at length 10 with >> entries rising from 0 towards 4 and never exceeding it. The nums list >> should shrink and above 40 should disappear and perhaps cause problems >> beyond that as there is nothing to scramble and use. At 30, it should be >> safe. But ideally, your algorithm should break out of a loop if everything >> has hit 4, or alternately if the number of items to choose from reaches >> zero. >> > >> > So I ran the code and I am embarrassed to say I did not see anything >> wrong. It seems to do exactly what it is designed to do. My guess is you >> are using something that cannot keep up with the I/O and produces glitches >> on your screen. The fact that it happens after the first run may be a clue >> that some buffer is being over-run or something. >> > >> > So, yes, your sleep attempts make some sense but you may also consider >> redirecting the output to a file in one of many ways and then viewing the >> file with something like a text editor and seeing if that looks like you >> expect. >> > >> > If so, there is nothing wrong with your program but something not quite >> great about some aspect of your environment. >> > >> > Anyone else try to run this and get an odd output? >> > >> > Q >> > >> > >> > >> > >> > >> > >> > Sent with Proton Mail secure email. >> > >> > >> > ------- Original Message ------- >> > On Sunday, April 30th, 2023 at 5:31 PM, Ed Connell >> edwinconnell at gmail.com wrote: >> > >> > >> > >> > > Greetings, >> > > >> > > I got interested in one of your earlier problems, but THAT PROBLEM is >> not >> > > what I am asking about. It was to generate a random sequence, each >> taken >> > > from a predefined pool. However, nothing is to be used more than four >> > > times. Moderately interesting. >> > > >> > > What I am asking about is this. The first time it runs perfectly. >> However >> > > subsequent runs, sooner or later, foul up. >> > > ############################### >> > > import random >> > > import time >> > > >> > > for run in range(10): #usually 1 but trying multiple runs through in >> one >> > > trip. >> > > >> > > # build result, number choices, and choice count lists >> > > res = [] >> > > nums = [] >> > > ct = [] >> > > >> > > for i in range(10): >> > > ct.append(0) >> > > nums.append(i) >> > > >> > > print('\n\n', run, ' start\n') >> > > >> > > #time.sleep(0.016) # seems to work for 0.016 or more uncommented >> > > >> > > for _ in range( 30 ): # tried 10 - 40 >> > > random.shuffle(nums) >> > > res.append(nums[0]) >> > > print(res) >> > > ct[nums[0]] += 1 >> > > if ct[nums[0]] == 4: >> > > print( 'Removing', nums[0],nums ) >> > > nums = nums[1:] >> > > print('leaving', nums ) >> > > >> > > print() >> > > print('numbers left',sorted(nums)) >> > > print('result',res) >> > > print('number used of each',ct) >> > > #################################### >> > > The problem seems to be a difference between printing and calculation >> speed >> > > but maybe not. >> > > >> > > I tried mostly using Geany, but also just ran the .py file. >> > > >> > > The bad output has incomplete lines as well as missing sections. >> > > >> > > I will appreciate your ideas. >> > > >> > > Oh, I am running on Windows 11, an hp with AMD 7. >> > > >> > > Ed Connll >> > > -- >> > > I have a right and a left brain, but there is nothing right in the >> left one >> > > and there is nothing left in the right one! >> > > _______________________________________________ >> > > Tutor maillist - Tutor at python.org >> > > To unsubscribe or change subscription options: >> > > https://mail.python.org/mailman/listinfo/tutor >> > > > -- > I have a right and a left brain, but there is nothing right in the left > one and there is nothing left in the right one! > > -- I have a right and a left brain, but there is nothing right in the left one and there is nothing left in the right one! From edwinconnell at gmail.com Tue May 2 11:18:58 2023 From: edwinconnell at gmail.com (Ed Connell) Date: Tue, 2 May 2023 10:18:58 -0500 Subject: [Tutor] My response. Not expecting a reply. Message-ID: Thank you for your response and particularly for your suggestions. This is my attempt to implement them. My real question was the malfunctions. I have concluded that my system shows the results while it is still bringing up the standard output window. I should have said, "attempts to write before..." Oh well! Ed import random import time for run in range(1): #usually 1 but trying multiple runs through in one pass. # build result, number choices, and choice count lists result = [] nums = list(range(10)) choice_count = 10*[0] print(f'\n\nrun {run+1}, number choices {nums}\n') time.sleep(0.5) # seems to work for 0.5 or more uncommented for _ in range( 36 ): # tried 10 - 40 choice = random.choice( nums ) result.append(choice) print(result) choice_count[choice] += 1 if choice_count[choice] == 4: nums.remove(choice) print( 'Removing', choice,'leaving', sorted(nums) ) numavailable = [] for i in range(10): numavailable.append(4-choice_count[i]) print() print('numbers left',sorted(nums)) print('result',result) print('number of each used',choice_count) print('number left of each',numavailable) -- I have a right and a left brain, but there is nothing right in the left one and there is nothing left in the right one! From jamesian.r.solima at gmail.com Wed May 3 12:47:48 2023 From: jamesian.r.solima at gmail.com (James Ian Solima) Date: Wed, 3 May 2023 09:47:48 -0700 Subject: [Tutor] Help to understand tree intersections using hash tables as a collision checker Message-ID: Hello tutors, I thought that I understood how hash tables worked. I was solving this algorithm the other day and in that algorithm I am using a hashtable's collision check to track if a value occurs twice in two different binary trees. input: tree1 = 1(2)(3) tree2 = 4(2(3)(1))(6(5)) expected result: [1,2,3] My code to solve this was, assume that my Hashtable class has working hash(), get(), set(), keys(), has(). And I have a working BinaryTree class with working pre_order(), in_order(), and post_order() methods. from data_structures.hashtable import Hashtable from data_structures.binary_tree.binary_tree import BinaryTree def tree_intersection(tree1, tree2): # Use hashmap implementation hash_table = Hashtable(1024) duplicates = set() if tree1.root: values1 = tree1.pre_order() for value in values1: hash_table.set(value, value) if tree2.root: values2 = tree2.pre_order() for value in values2: if hash_table.has(value) and value not in duplicates: duplicates.add(value) return list(duplicates) In theory, I expected this to work. My test code: import pytest from code_challenges.tree_intersection.tree_intersection import tree_intersection from data_structures.binary_tree.binary_tree import BinaryTree, Node from data_structures.queue.queue import Queue def test_exists(): assert tree_intersection # @pytest.mark.skip("TODO") def test_tree_intersection(): tree_a = BinaryTree() values = [150, 100, 250, 75, 160, 200, 350, 125, 175, 300, 500] add_values_to_empty_tree(tree_a, values) tree_b = BinaryTree() values = [42, 100, 100, 15, 160, 200, 350, 125, 175, 4, 500] add_values_to_empty_tree(tree_b, values) actual = tree_intersection(tree_a, tree_b) expected = [125, 175, 100, 160, 500, 200, 350] print(actual) assert sorted(actual) == sorted(expected) def add_values_to_empty_tree(tree, values): """ Helper function to add given values to BinaryTree """ tree.root = Node(values.pop()) q = Queue() q.enqueue(tree.root) while values: node = q.dequeue() node.left = Node(values.pop()) node.right = Node(values.pop()) if values else None q.enqueue(node.left) q.enqueue(node.right) This is the actual result that I get when I test the code. [160, 100, 200, 75, 300, 175, 500, 150, 250, 125, 350] What I am expecting: [125, 175, 100, 160, 500, 200, 350] How and why am I getting the value 75, 250, 150, and all the other numbers that don't exist in both test trees. -- -James Solima c. (562) 546-2011 p. (808) 781-9756 Jamesian.R.Solima at gmail.com From sharj.ahmed.91 at gmail.com Wed May 3 18:09:46 2023 From: sharj.ahmed.91 at gmail.com (Sharj Ahmed) Date: Wed, 3 May 2023 23:09:46 +0100 Subject: [Tutor] Battleships - Error with blank input Message-ID: Hi all, Need some help with my code. I've written the below code, but need to add some validation in for when the user inputs nothing. The blank input for rows and columns causes the application to crash. Any help would be greatly appreciated! Here is my code: """ *Import random to generate random integers in game"""from random import randint* *HIDDEN_BOARD = [["?"] * 8 for x in range(8)]GUESS_BOARD = [["?"] * 8 for x in range(8)]letters_to_numbers = {"A": 0,"B": 1,"C": 2,"D": 3,"E": 4,"F": 5,"G": 6,"H": 7,}board = []* *def print_board(board):"""Create board for player to guess where to hit"""print(" A B C D E F G H")row_number = 1for row in board:print("%d | %s | " % (row_number, " | ".join(row)))row_number += 1* *print("\n? WELCOME TO BATTLESHIPS ?\n")print("YOU HAVE 25 GUESSES TO SINK 5 BATTLESHIPS\n")print("Game Legend:")print("? - blank space")print("? - missed shot")print("? - hit ship\n")print_board(board)* *def create_ships(board):"""Place ships randomly"""for ship in range(5):(ship_row, ship_column) = (randint(0, 7), randint(0, 7))while board[ship_row][ship_column] == "?":(ship_row, ship_column) = (randint(0, 7), randint(0, 7))board[ship_row][ship_column] = "?"* *def fire_shot():"""Asking player what row and column to fire their shot"""row = input("\nEnter ship row 1-8: ")while row not in "12345678":print("\nPlease enter a valid row")row = input("\nEnter ship row 1-8: \n")column = input("\nEnter ship column A-H: ").upper()while column not in "ABCDEFGH":print("\nPlease enter a valid column")column = input("\nEnter ship column A-H: ").upper()return (int(row) - 1, letters_to_numbers[column])* *def count_hit_ships(board):"""Count every time the player hits a shipGame is over when all 5 ships are hit"""count = 0for row in board:for column in row:if column == "?":count += 1return count* *create_ships(HIDDEN_BOARD)turns = 25while turns > 0:print_board(GUESS_BOARD)(row, column) = fire_shot()if GUESS_BOARD[row][column] == "?":print("\n------------------------------------------------")print("You've already guessed that! Please guess again")print("------------------------------------------------\n")elif HIDDEN_BOARD[row][column] == "?":print("\n---------------------------------------")print("GREAT SHOT! you sunk a battleship!")print("---------------------------------------\n")GUESS_BOARD[row][column] = "?"turns -= 1else:print("\n------------------------")print("Ah unlucky, you missed!")print("------------------------\n")GUESS_BOARD[row][column] = "?"turns -= 1if count_hit_ships(GUESS_BOARD) == 5:print("\n------------------------------------------------------")print("\n CONGRATULATIONS! You've sunk all 5 battleships! \n")print("------------------------------------------------------\n")breakprint("You have " + str(turns) + " turns remaining \n")if turns == 0:print("\n--------------------------------------------")print("\n GAME OVER! you have 0 turns remaining \n")print("--------------------------------------------\n")break* The error message that appears is: [image: image.png] Any help would be greatly appreciated! Thanks! Sharj From PythonList at DancesWithMice.info Wed May 3 20:13:16 2023 From: PythonList at DancesWithMice.info (dn) Date: Thu, 4 May 2023 12:13:16 +1200 Subject: [Tutor] Battleships - Error with blank input In-Reply-To: References: Message-ID: On 04/05/2023 10.09, Sharj Ahmed wrote: > Hi all, > > Need some help with my code. > > I've written the below code, but need to add some validation in for when > the user inputs nothing. > > The blank input for rows and columns causes the application to crash. Try: "" in "123" Does that help? There is a feature of Python known as 'truthiness', so if row: # check if valid row else: # problem > Any help would be greatly appreciated! > > Here is my code: Sadly, the email formatting was difficult to read, and because newlines and indentation were affected, there may be errors we can't detect... > The error message that appears is: > [image: image.png] Attachments do not come through. Please copy-paste the text. -- Regards, =dn From threesomequarks at proton.me Wed May 3 20:46:58 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 04 May 2023 00:46:58 +0000 Subject: [Tutor] Battleships - Error with blank input In-Reply-To: References: Message-ID: <1yd2Q9E5ETLF9RsWLegf8e8sGK--l9HXo9plTiq3jNV_ULGR0NDpPLwYUOVew_iQDuXZRBUGadJimM0l0MEmSn5tEDTR6MSQUXoiwSll_oU=@proton.me> As Alan mentioned, the code as displayed is not only hard to read but will not pass as valid python with proper indentation. Where exactly in that code do you want to test for blanks and what do you want to do if they are detected? Generally, a blank line is matched by "" and if you want to consider anything with nothing but whitespace, that can also easily be matched in various ways depending on what you consider valid input. So could you just show us a few lines of code where you accept a value and are deciding if the value is valid. Show us what you tried and see why maybe it failed. Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, May 3rd, 2023 at 8:13 PM, dn via Tutor wrote: > On 04/05/2023 10.09, Sharj Ahmed wrote: > > > Hi all, > > > > Need some help with my code. > > > > I've written the below code, but need to add some validation in for when > > the user inputs nothing. > > > > The blank input for rows and columns causes the application to crash. > > > Try: > > "" in "123" > > Does that help? > > There is a feature of Python known as 'truthiness', so > > if row: > # check if valid row > else: > # problem > > > Any help would be greatly appreciated! > > > > Here is my code: > > > Sadly, the email formatting was difficult to read, and because newlines > and indentation were affected, there may be errors we can't detect... > > > The error message that appears is: > > [image: image.png] > > > Attachments do not come through. > > Please copy-paste the text. > > -- > Regards, > =dn > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From PythonList at DancesWithMice.info Wed May 3 21:53:27 2023 From: PythonList at DancesWithMice.info (dn) Date: Thu, 4 May 2023 13:53:27 +1200 Subject: [Tutor] Battleships - Error with blank input In-Reply-To: <1yd2Q9E5ETLF9RsWLegf8e8sGK--l9HXo9plTiq3jNV_ULGR0NDpPLwYUOVew_iQDuXZRBUGadJimM0l0MEmSn5tEDTR6MSQUXoiwSll_oU=@proton.me> References: <1yd2Q9E5ETLF9RsWLegf8e8sGK--l9HXo9plTiq3jNV_ULGR0NDpPLwYUOVew_iQDuXZRBUGadJimM0l0MEmSn5tEDTR6MSQUXoiwSll_oU=@proton.me> Message-ID: <8bdaef44-8b1a-e945-8131-76418dae5f5f@DancesWithMice.info> On 04/05/2023 12.46, ThreeBlindQuarks wrote: > > As Alan mentioned, the code as displayed is not only hard to read but will not pass as valid python with proper indentation. Not @Alan - 'twas I (he's the better-looking one of us) -- Regards, =dn From alan.gauld at yahoo.co.uk Thu May 4 05:33:47 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 4 May 2023 10:33:47 +0100 Subject: [Tutor] Battleships - Error with blank input In-Reply-To: References: Message-ID: On 03/05/2023 23:09, Sharj Ahmed wrote: > I've written the below code, but need to add some validation in for when > the user inputs nothing. Your code has lost all indentation which is of course critical in Python. You need to resend the message using *plain text* format not HTML. > The blank input for rows and columns causes the application to crash. Please always include the error messages - I'm assuming you get an error message?! You should do. I'll try to find the input statements... > *def fire_shot():"""Asking player what row and column to fire their > shot""" row = input("\nEnter ship row 1-8: ")while row not in "12345678": If row is an empty string this will pass because the empty string is in every string. >>> "" in "123" True >>> "" in "" True You will need to explicitly check for an empty string: while row and row not in "12345678": > The error message that appears is: > [image: image.png] You need to cut 'n paste the text. The server strips binary attachments as security hazards. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Thu May 4 05:42:11 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 4 May 2023 10:42:11 +0100 Subject: [Tutor] Help to understand tree intersections using hash tables as a collision checker In-Reply-To: References: Message-ID: On 03/05/2023 17:47, James Ian Solima wrote: > I thought that I understood how hash tables worked. I was solving this > algorithm the other day and in that algorithm I am using a hashtable's > collision check to track if a value occurs twice in two different binary > trees. The only hash table type in standard Python is the dictionary(and maybe set?). But it does not expose methods like collision check to the user. But I see you are importing a module called data_structures, which is not part of the standard library. This list is focused on the language and standard library so you may not find anyone who knows about that module. As a minimum tell us where you found it. PyPI? Github? Part of SciPy? Or is it a module you have created? In which case we'd need to see some code. > input: > tree1 = 1(2)(3) > tree2 = 4(2(3)(1))(6(5)) > > expected result: [1,2,3] > > My code to solve this was, assume that my Hashtable class has working > hash(), get(), set(), keys(), has(). And I have a working BinaryTree class > with working pre_order(), in_order(), and post_order() methods. > > from data_structures.hashtable import Hashtable > from data_structures.binary_tree.binary_tree import BinaryTree > def tree_intersection(tree1, tree2): > # Use hashmap implementation > hash_table = Hashtable(1024) > duplicates = set() > if tree1.root: > values1 = tree1.pre_order() > for value in values1: > hash_table.set(value, value) > if tree2.root: > values2 = tree2.pre_order() > for value in values2: > if hash_table.has(value) and value not in duplicates: > duplicates.add(value) > return list(duplicates) Without indentation it's almost impossible to be sure what's going on. Please resend the message using *plain text* rather than HTML to preserve the layout. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From musa420lol at gmail.com Wed May 10 17:23:42 2023 From: musa420lol at gmail.com (fernando ramirez) Date: Wed, 10 May 2023 14:23:42 -0700 Subject: [Tutor] a zipapp question Message-ID: My question is simple, zipapp creates executables, I know it works but what if I want my app to have images in its buttons, I can't make my app run with double click, it only runs from the command line, how can I fix this? ? Thank you The same but in spanish : Mi duda es simple, zipapp crea ejecutables, se que funciona pero que pasa si quiero que mi app tenga imagenes en sus botones, no puedo hacer que mi app se ejecute con doble click solo se ejecuta desde la linea de comandos, como puedo solucionar esto ? Gracias From alan.gauld at yahoo.co.uk Wed May 10 20:30:23 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Thu, 11 May 2023 01:30:23 +0100 Subject: [Tutor] a zipapp question In-Reply-To: References: Message-ID: On 10/05/2023 22:23, fernando ramirez wrote: > My question is simple, zipapp creates executables, I know it works but > what if I want my app to have images in its buttons, I can't make my > app run with double click, it only runs from the command line, how can > I fix this? ? First, thanks for mentioning zipapp, this is the first I've heard of zip apps in Python. So a new learning experience for me. But that in turn means I have no real experience of using the tool(yet). However, from my brief readings it seems like it just zips all your python files together and adds a main.py to start the app running. You mention your app having buttons with images? Is this in a GUI? If so the solution will depend on which GUI you are using. Can you run your application with images without zipapp? If so it should work in zipapp provided the images are included in the pyz file. But as I say, I have not used zipapp in anger, so cannot be certain. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From johnf at jfcomputer.com Thu May 11 15:29:01 2023 From: johnf at jfcomputer.com (john fabiani) Date: Thu, 11 May 2023 12:29:01 -0700 Subject: [Tutor] the use of the COLON Message-ID: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> Hi, I have never seen the following syntax. ? But it works!? Can someone explain how it works or provide a link that have me understand what is happening? Thanks Johnf dummy_user_list: list=[["johnf", "jfabiani1947"]] From mats at wichmann.us Thu May 11 15:40:43 2023 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 11 May 2023 13:40:43 -0600 Subject: [Tutor] the use of the COLON In-Reply-To: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> Message-ID: <82df1739-ad9b-7da3-7a5e-14c9065f7b9b@wichmann.us> On 5/11/23 13:29, john fabiani wrote: > Hi, > I have never seen the following syntax. ? But it works!? Can someone > explain how it works or provide a link that have me understand what is > happening? > Thanks > Johnf > dummy_user_list: list=[["johnf", "jfabiani1947"]] https://docs.python.org/3/library/typing.html From johnf at jfcomputer.com Thu May 11 18:00:44 2023 From: johnf at jfcomputer.com (john fabiani) Date: Thu, 11 May 2023 15:00:44 -0700 Subject: [Tutor] the use of the COLON In-Reply-To: <82df1739-ad9b-7da3-7a5e-14c9065f7b9b@wichmann.us> References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> <82df1739-ad9b-7da3-7a5e-14c9065f7b9b@wichmann.us> Message-ID: This is going to take a lot of study! Thanks, Johnf On 5/11/23 12:40 PM, Mats Wichmann wrote: > On 5/11/23 13:29, john fabiani wrote: >> Hi, >> I have never seen the following syntax. ? But it works!? Can someone >> explain how it works or provide a link that have me understand what >> is happening? >> Thanks >> Johnf >> dummy_user_list: list=[["johnf", "jfabiani1947"]] > > https://docs.python.org/3/library/typing.html > > _______________________________________________ > Tutor maillist? - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From threesomequarks at proton.me Thu May 11 19:08:45 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 11 May 2023 23:08:45 +0000 Subject: [Tutor] the use of the COLON In-Reply-To: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> Message-ID: When you say something WORKS, what do you mean? Do you mean no error message? Do you mean later code indicates it did what was expected? This may sound like a dumb question but there seem to be a few anomalies in the code: dummy_user_list: list=[["johnf", "jfabiani1947"]] The first is this: dummy_user_list: Python does have a concept of starting an indented scope with a colon but not so much a concept of naming a region as in languages that have a GOTO or the ability to break out to a specific location: On my machine, code like: hello: gets an error method about syntax. Second, the word "list" is the name of a function and at best it can be very poor form to use it as a variable name. In the code you shared that does not generate an error for me either, it is NOT setting a variable called list to a value: >>> dummy_user_list: list=[["johnf", "jfabiani1947"]] >>> list >>> print(list) But if I leave out the meaningles colon part, it does overwrite: >>> list=[["johnf", "jfabiani1947"]] >>> list [['johnf', 'jfabiani1947']] >>> list[0] ['johnf', 'jfabiani1947'] And yes, I cannot make a list anymore with something like list(...) as the name is re-assigned. Finally, what was the purpose of [["johnf", "jfabiani1947"]] versus just ["johnf", "jfabiani1947"] in Python? There are languages like R that have a [[ operator with somewhat different meaning but in Python, you asked for a list that contains a single other list which inside it has three items. Back to your question, on MY SETUP, the code you mentioned only works in the sense of no error but does nothing useful. Anything after the : may as as well be a comment but not exactly. Here is simpler code: >>> hello: a=5 NameError: name 'a' is not defined >>> a=1 >>> hello: a=5 >>> The first command was run when no variable called "a" had ever been used in the session. It fails complaining about it so it obviously read the line. The next lines instantiate "a" to 1 and then it runs silently but does not change the value of a! But it gets weirder when I wonder if "hello" is seen as a variable. I chose new undefined names: >>> print(myname) NameError: name 'myname' is not defined >>> who="me" >>> myname: who="Quark" >>> print(who) me >>> print(myname) Quark So the above shows that at the start, there was no variable called "myname" and there was one of 'who' and yet the assignment to who was NOT done and yet passed along to 'myname'!!! You could experiment more, but this behavior does not look like it was planned to be used by us! It almost looks like "who" is a local variable in the context of a region and the final value is passed to the name of the region! I now tried a multi-line variation: >>> x=1 >>> y=2 >>> z=3 >>> >>> mytown: z="three" >>> x="one" >>> y="two" >>> >>> mytown 'three' >>> x 'one' >>> y 'two' >>> z 3 It looks like the interpreter allowed multiple indented lines that altered x,y but that z on the same line as the colon behaved as before. Another experiment shows only the first assignment is copied and all are in a sense ignored: >>> myneighborhood: x=11;y=12;z=13 >>> myneighborhood 11 >>> x 'one' >>> y 12 >>> z 13 But another egg sperm meant indicates the scope is LOCAL and changes last to local variables: >>> myneighborhood: x=11;y=12;z=13; print(x,y,z) one 12 13 But this test indicates it uses a global variable on the RHS. >>> neighburrhood: x=x*3 >>> neighburrhood 'oneoneone' >>> x 'one' So, without doing more such experiments, I have no idea why this is allowed let alone what it does. I find it best to avoid using anything I do not understand! Hopefully, someone else here can enlighten us. Or, maybe it is an unfound bug! Sent with Proton Mail secure email. ------- Original Message ------- On Thursday, May 11th, 2023 at 3:29 PM, john fabiani wrote: > Hi, > I have never seen the following syntax. But it works! Can someone > explain how it works or provide a link that have me understand what is > happening? > Thanks > Johnf > dummy_user_list: list=[["johnf", "jfabiani1947"]] > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From mats at wichmann.us Thu May 11 19:18:03 2023 From: mats at wichmann.us (Mats Wichmann) Date: Thu, 11 May 2023 17:18:03 -0600 Subject: [Tutor] the use of the COLON In-Reply-To: References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> <82df1739-ad9b-7da3-7a5e-14c9065f7b9b@wichmann.us> Message-ID: On 5/11/23 16:00, john fabiani wrote: > This is going to take a lot of study! > Thanks, > Johnf That reference probably isn't the most helpful - it's "canonical", but not that descriptive. Python has support for (static) typing, but it's optional: the language itself doesn't deal with it(*), it's intended for 3rd party tools. As a result, the typing annotations which have gradually crept in over several Python releases since 3.5 are "ignored", so if you use that syntax, it still "works". There are many more gentle introductions to typing in Python, worth taking a look on the internet. (*) kind of a small lie... Python does process the typing syntax, but puts it somewhere and doesn't do anything with it beyond that. > On 5/11/23 12:40 PM, Mats Wichmann wrote: >> On 5/11/23 13:29, john fabiani wrote: >>> Hi, >>> I have never seen the following syntax. ? But it works!? Can someone >>> explain how it works or provide a link that have me understand what >>> is happening? >>> Thanks >>> Johnf >>> dummy_user_list: list=[["johnf", "jfabiani1947"]] >> >> https://docs.python.org/3/library/typing.html From alan.gauld at yahoo.co.uk Thu May 11 19:58:01 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 12 May 2023 00:58:01 +0100 Subject: [Tutor] the use of the COLON In-Reply-To: References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> Message-ID: On 12/05/2023 00:08, ThreeBlindQuarks via Tutor wrote: > When you say something WORKS, what do you mean? In this case it means the variable dummy_user_list is assigned the value in the statement, ie [[...]] > Do you mean later code indicates it did what was expected? No, the later code ignores the type definition completely, it's intended for third party tools to pick up on - I guess linters etc? > This may sound like a dumb question but there seem to be a few anomalies in the code: > > dummy_user_list: list=[["johnf", "jfabiani1947"]] > > The first is this: > > dummy_user_list: > > Python does have a concept of starting an indented scope with a colon This is not an indented code type colon but a type definition. I admit I'm not a fan of the type hinting stuff in Python but it is what it is, and this is it... So the colon in this case is saying that the thing that follows is a type (and optional assignment) > On my machine, code like: > > hello: > > gets an error method about syntax. Yes because ther is no type provided hello: str would work and tell Python/linter that the variable hello should be a string. > Second, the word "list" is the name of a function and at best Technically its the name of a type and the type constructor. Which is treated a little differently from regular functions. > it can be very poor form to use it as a variable name. Despite being on the left of an assignment it is actually being used as a type name in this statement. The variable name is dummy_user_list > In the code you shared that does not generate an error for me > either, it is NOT setting a variable called list to a value: Thats true it is setting the variable dummy_user_list to the value in the assignment which corresponds with the type hint, namely a list. (a list of lists in this case but Python doesn't care, it's still a list!) >>>> dummy_user_list: list=[["johnf", "jfabiani1947"]] >>>> list > >>>> print(list) > Try >>>> dummy_user_list > [['johnf', 'jfabiani1947']] > But if I leave out the meaningles colon part, it does overwrite: Not meaningless, it is a type declaration. >>>> list=[["johnf", "jfabiani1947"]] But this is just a regular assignment so you override the name list. > Finally, what was the purpose of [["johnf", "jfabiani1947"]] > versus just ["johnf", "jfabiani1947"] in Python? Its a list of lists. The first element is ["johnf", "jfabiani1947"] but others could be added: >>> dummy_user_list.append(['another', 'value']) >>> dummy_user_list [['johnf', 'jfabiani1947'], ['another', 'value']] > Back to your question, on MY SETUP, the code you mentioned only > works in the sense of no error but does nothing useful. That's correct for vanilla Python. I believe there are tools that will spit out type warnings etc based on earlier hints. > Anything after the : may as as well be a comment but not exactly. Not exactly, the assignment part of the statement is still valid and does assign a value to the variable. > But it gets weirder when I wonder if "hello" is seen as a variable. > I chose new undefined names: > >>>> print(myname) > NameError: name 'myname' is not defined >>>> who="me" >>>> myname: who="Quark" Because vanilla Python doesn't do anything with the type declaration it accepts any recognised name as a type. An unrecognised name gives an error: >>> y:blippidy=6 Traceback (most recent call last): File "", line 1, in NameError: name 'blippidy' is not defined >>> y:dummy_user_list=666 >>> y 666 So although 666 is not a list(the type of dummy_user_list) Python silently accepts the name then assigns an integer to the variable! >>>> print(who) > me >>>> print(myname) > Quark So the assignment to myname works as expected without any error. > So the above shows that at the start, there was no variable > called "myname" and there was one of 'who' and yet the assignment > to who was NOT done and yet passed along to 'myname'!!! Nope, 'who' was recognised as a potential type name and the assignment was made directly to myname. > You could experiment more, but this behavior does not look > like it was planned to be used by us! It was planned to be read by tools and written by programmers who get very uptight about static typing! >>>> mytown: z="three" >>>> x="one" >>>> y="two" >>>> I get an indentation error when I try that... > But another egg sperm meant indicates the scope is LOCAL Nope, nothing to do with scopes here. Just a slightly confusing type declaration syntax. One which does nothing much of any use in the real world! (But might do someday...) -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From johnf at jfcomputer.com Thu May 11 21:24:09 2023 From: johnf at jfcomputer.com (john fabiani) Date: Thu, 11 May 2023 18:24:09 -0700 Subject: [Tutor] the use of the COLON In-Reply-To: References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> Message-ID: Thanks very helpful Johnf On 5/11/23 4:58 PM, Alan Gauld via Tutor wrote: > hello: str From threesomequarks at proton.me Thu May 11 22:16:45 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Fri, 12 May 2023 02:16:45 +0000 Subject: [Tutor] the use of the COLON In-Reply-To: References: <13e1e9c4-36b7-1fa4-5564-c91f793c2322@jfcomputer.com> Message-ID: Thank you Alan, yes that makes much sense as optional extensions to python that I have never felt any urgency to try. It is a bit like people used to ask me about C code that included pre-processor directives like $DEFINE or #IF which do not end up in the code being compiled except indirectly by filling out parameters or choosing which snippets are included to compile for a specific target. They are not part of the C language definition in the sense that a working compiler need not deal with them unless it feels like doing all the work. It is a tad annoying that a language re-uses the same symbols in so many ways that my first impression of what a colon might mean was off in left field. then again, this uses colons too and clearly in another way: >>> text = "Sxyeabccdrfgehit" >>> text[0::3] 'Secret' Sent with Proton Mail secure email. ------- Original Message ------- On Thursday, May 11th, 2023 at 7:58 PM, Alan Gauld via Tutor wrote: > On 12/05/2023 00:08, ThreeBlindQuarks via Tutor wrote: > > > When you say something WORKS, what do you mean? > > > In this case it means the variable dummy_user_list is assigned the value > in the statement, ie [[...]] > > > Do you mean later code indicates it did what was expected? > > > No, the later code ignores the type definition completely, it's > intended for third party tools to pick up on - I guess linters etc? > > > This may sound like a dumb question but there seem to be a few anomalies in the code: > > > > dummy_user_list: list=[["johnf", "jfabiani1947"]] > > > > The first is this: > > > > dummy_user_list: > > > > Python does have a concept of starting an indented scope with a colon > > > This is not an indented code type colon but a type definition. > I admit I'm not a fan of the type hinting stuff in Python but > it is what it is, and this is it... > > So the colon in this case is saying that the thing that follows > is a type (and optional assignment) > > > On my machine, code like: > > > > hello: > > > > gets an error method about syntax. > > > Yes because ther is no type provided > > hello: str > > would work and tell Python/linter that the variable hello should > be a string. > > > Second, the word "list" is the name of a function and at best > > > Technically its the name of a type and the type constructor. > Which is treated a little differently from regular functions. > > > it can be very poor form to use it as a variable name. > > > Despite being on the left of an assignment it is actually being used as > a type name in this statement. The variable name is dummy_user_list > > > In the code you shared that does not generate an error for me > > either, it is NOT setting a variable called list to a value: > > > Thats true it is setting the variable dummy_user_list to the > value in the assignment which corresponds with the type hint, > namely a list. (a list of lists in this case but Python doesn't > care, it's still a list!) > > > > > > dummy_user_list: list=[["johnf", "jfabiani1947"]] > > > > > list > > > > > > > > > > print(list) > > > > > > > > Try > > > > > > dummy_user_list > > > > > [['johnf', 'jfabiani1947']] > > > But if I leave out the meaningles colon part, it does overwrite: > > > Not meaningless, it is a type declaration. > > > > > > list=[["johnf", "jfabiani1947"]] > > > But this is just a regular assignment so you override the name list. > > > Finally, what was the purpose of [["johnf", "jfabiani1947"]] > > versus just ["johnf", "jfabiani1947"] in Python? > > > Its a list of lists. The first element is ["johnf", "jfabiani1947"] > but others could be added: > > > > > dummy_user_list.append(['another', 'value']) > > > > dummy_user_list > > [['johnf', 'jfabiani1947'], ['another', 'value']] > > > Back to your question, on MY SETUP, the code you mentioned only > > works in the sense of no error but does nothing useful. > > > That's correct for vanilla Python. I believe there are tools that > will spit out type warnings etc based on earlier hints. > > > Anything after the : may as as well be a comment but not exactly. > > > Not exactly, the assignment part of the statement is still valid > and does assign a value to the variable. > > > But it gets weirder when I wonder if "hello" is seen as a variable. > > I chose new undefined names: > > > > > > > print(myname) > > > > > NameError: name 'myname' is not defined > > > > > who="me" > > > > > myname: who="Quark" > > > Because vanilla Python doesn't do anything with the type declaration it > accepts any recognised name as a type. An unrecognised name gives an error: > > > > > y:blippidy=6 > > Traceback (most recent call last): > File "", line 1, in > > NameError: name 'blippidy' is not defined > > > > > y:dummy_user_list=666 > > > > y > > 666 > > So although 666 is not a list(the type of dummy_user_list) Python > silently accepts the name then assigns an integer to the variable! > > > > > > print(who) > > > > > me > > > > > print(myname) > > > > > Quark > > > So the assignment to myname works as expected without any error. > > > So the above shows that at the start, there was no variable > > called "myname" and there was one of 'who' and yet the assignment > > to who was NOT done and yet passed along to 'myname'!!! > > > Nope, 'who' was recognised as a potential type name and the assignment > was made directly to myname. > > > You could experiment more, but this behavior does not look > > like it was planned to be used by us! > > > It was planned to be read by tools and written by programmers > who get very uptight about static typing! > > > > > > mytown: z="three" > > > > > x="one" > > > > > y="two" > > > I get an indentation error when I try that... > > > But another egg sperm meant indicates the scope is LOCAL > > > Nope, nothing to do with scopes here. Just a slightly > confusing type declaration syntax. One which does nothing > much of any use in the real world! (But might do someday...) > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From phillor9 at gmail.com Sat May 13 00:12:20 2023 From: phillor9 at gmail.com (Phil) Date: Sat, 13 May 2023 14:12:20 +1000 Subject: [Tutor] Running an app from a virtual environment Message-ID: <760adc4a-afb8-3d18-0901-6eb32b9b1817@gmail.com> This how I currently have my virtual environments set up: myproject/ |myapp.py |.venv |?? |bin |?? |include |?? |lib Originally I had myapp.py stored under /bin where I could run it like this: ./python3 myapp.py. However, I discovered recently that I should have myapp.py stored under the root directory as shown above. VS code still finds the app and I can continue working on it and running it from VS code but I can no longer run the same app from the virtual environment because a module that is stored in the .venv/lib cannot be found by myapp.py. My AI friend has not been very helpful with this problem and an Internet search has offered a couple of suggestions that involve adding an extra line or two to myapp.py. Shouldn't myapp.py be able to be run from a virtual environment without modification and how do I run my creations after development has been completed? I solved this problem by using pipx to install the missing module which results in it being stored at ~/.local/bin. I'm not sure if this is the correct procedure. I'm still inclined to think that myapp.py should be able to be run from the virtual environment and find the module in the lib directory. -- Regards, Phil From phillor9 at gmail.com Sat May 13 01:09:53 2023 From: phillor9 at gmail.com (Phil) Date: Sat, 13 May 2023 15:09:53 +1000 Subject: [Tutor] Re my question about virtual environments Message-ID: Problem solved. I'd copied one virtual environment to create another which I shouldn't have done. -- Regards, Phil From goranikac65 at gmail.com Tue May 16 01:39:57 2023 From: goranikac65 at gmail.com (Goran Ikac) Date: Tue, 16 May 2023 07:39:57 +0200 Subject: [Tutor] How to manipulate a user's input twice in one statement Message-ID: If a value is assigned to the string some_string, this works: >>> some_string = 'avion' >>> some_string.removesuffix(input()[1:]) ton 'avi' But the next statement doesn't work as I've expected (it waits for another user's input): >>> input().removesuffix(input()[1:]) avion ton 'avi' Now, is there a way to manipulate the input from a user so to remove a slice from it, other than to assign that slice to a variable name and then to manipulate that variable? (The next snippet is *NOT *what I'm looking for: >>> input()[0] avion 'a' ) I'd like to be able to put the user's input as an argument for a method that manipulates that same user's input. The method .removesuffix() is only an example. I hope I don't make you angry with me :) Goran from Croatia From alan.gauld at yahoo.co.uk Tue May 16 04:38:55 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 16 May 2023 09:38:55 +0100 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: On 16/05/2023 06:39, Goran Ikac wrote: > If a value is assigned to the string some_string, this works: >>>> some_string = 'avion' >>>> some_string.removesuffix(input()[1:]) > ton > 'avi' It would help us understand what you are trying to do if you added prompts to your input statements: some_string = 'avion' some_string.removesuffix( input("provide suffix with extra character at the front")[1:]) > But the next statement doesn't work as I've expected (it waits for another > user's input): Because you have two input statements. It will execute both of them. >>>> input().removesuffix(input()[1:]) > avion > ton > 'avi' Why do you want it all on one line? Normally you'd capture the two things then process them: some_string = input("String to process: ") suffix = input("enter a suffix with an extra letter: ") print(some_string.remove_suffix(suffix[1:]) Which is easier to read and debug and helps your user. > Now, is there a way to manipulate the input from a user so to remove a > slice from it, other than to assign that slice to a variable name and then > to manipulate that variable? You are not assigning a slice you are *applying* a slice to the string. It's not clear why you are using a slice but that is not relevant. The real question is why you want to do it all on one line? There is no advantage and several disadvantages. Remember the >>> prompt is not where your real programs will run, that's just for experimenting and testing. The real code will run using print statements etc. And you can place the input/output exactly where you want it. > I'd like to be able to put the user's input as an argument for a method > that manipulates that same user's input. The method .removesuffix() is only > an example. Sorry, I'm still not clear what you really want to do. Can you give us an example of a user session (without code for now) Just show us the inputs and expected outputs? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From threesomequarks at proton.me Tue May 16 12:35:22 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Tue, 16 May 2023 16:35:22 +0000 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: I agree with Alan that we may not yet understand what is wanted. For now, the request may fit into a class of posts that boil down to wanting the language to be designed differently to do things in a way they would like. Often that is done without a full understanding of what that might entail. In this case, again, I am not understanding what is being asked as a fairly simple method is available unless there is some great reason for wanting a one-liner. But Pythos has been augmented to allow many such one-liners. Some languages have an inline operator allowing you to set the value of a variable in middle of an expression and reuse it. Python did add the walrus operator ":=" that MAYBE is what the user wants as in: >>> x = (y := 10) + y + y**2 >>> x 120 So it can be as simple as assigning your input using the walrus operator in a sort of inline way to save the input and use it later. With a slight change for clarity, the code below works in the example, albeit I have no idea what is wanted: >>> input("enter text: ").removesuffix(input("enter suffix: ")[1:]) enter text: hello.avi enter suffix: avi 'hello.a' If you wanted the value of either the text or the suffix retained for a second use you can do something like this to save just the text: >>> (text := input("enter text: ")).removesuffix(input("enter suffix: ")[1:]) enter text: hello.avi enter suffix: avi 'hello.a' >>> text 'hello.avi' Or to save both (and note the extra parentheses): >>> (text := input("enter text: ")).removesuffix((suffix := input("enter suffix: "))[1:]) enter text: hello.avi enter suffix: avi 'hello.a' >>> text 'hello.avi' >>> suffix 'avi' Nobody will tell you this is code particularly elegant or easy to read versus a multi-line version and my thoughts may not be helpful if your plans are not as I guessed. Another guess maybe a bit further off the wall as if you ask the user for input once and they supply it and at a later time you ask the user for input and the default should be to keep the old one unless they want to change. That can easily be done for example by writing a function like this: def default_input(prompt, default=""): if default != "": prompt = prompt + "[" + default + "] " got = input(prompt) if got == "": got = default return(got) The above lets you keep asking the user questions and remembers their last choice so future questions can be easier as they are shown the current default and can accept it or replace it. >>> result = default_input("What? ") What? this >>> result 'this' >>> result = default_input("What? ", result) What? [this] >>> result 'this' >>> result = default_input("What? ", result) What? [this] that >>> result 'that' Again, probably not what you want but I encourage you to figure out how to ask a more focused question that we can understand and answer properly. Q Sent with Proton Mail secure email. ------- Original Message ------- On Tuesday, May 16th, 2023 at 4:38 AM, Alan Gauld via Tutor wrote: > On 16/05/2023 06:39, Goran Ikac wrote: > > > If a value is assigned to the string some_string, this works: > > > > > > > some_string = 'avion' > > > > > some_string.removesuffix(input()[1:]) > > > > > ton > > > > > 'avi' > > > It would help us understand what you are trying to do if you added > prompts to your input statements: > > some_string = 'avion' > some_string.removesuffix( > input("provide suffix with extra character at the front")[1:]) > > > But the next statement doesn't work as I've expected (it waits for another > > user's input): > > > Because you have two input statements. It will execute both of them. > > > > > > input().removesuffix(input()[1:]) > > > > > avion > > > > > ton > > > > > 'avi' > > > Why do you want it all on one line? Normally you'd capture the two > things then process them: > > some_string = input("String to process: ") > suffix = input("enter a suffix with an extra letter: ") > print(some_string.remove_suffix(suffix[1:]) > > Which is easier to read and debug and helps your user. > > > Now, is there a way to manipulate the input from a user so to remove a > > slice from it, other than to assign that slice to a variable name and then > > to manipulate that variable? > > > You are not assigning a slice you are applying a slice to the string. > It's not clear why you are using a slice but that is not relevant. > The real question is why you want to do it all on one line? > There is no advantage and several disadvantages. > > Remember the >>> prompt is not where your real programs will run, > > that's just for experimenting and testing. The real code will run > using print statements etc. And you can place the input/output > exactly where you want it. > > > I'd like to be able to put the user's input as an argument for a method > > that manipulates that same user's input. The method .removesuffix() is only > > an example. > > > Sorry, I'm still not clear what you really want to do. > Can you give us an example of a user session (without code for now) > Just show us the inputs and expected outputs? > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From mats at wichmann.us Tue May 16 13:27:07 2023 From: mats at wichmann.us (Mats Wichmann) Date: Tue, 16 May 2023 11:27:07 -0600 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: On 5/16/23 10:35, ThreeBlindQuarks via Tutor wrote: > > I agree with Alan that we may not yet understand what is wanted. > > For now, the request may fit into a class of posts that boil down to wanting the language to be designed differently to do things in a way they would like. Often that is done without a full understanding of what that might entail. > > In this case, again, I am not understanding what is being asked as a fairly simple method is available unless there is some great reason for wanting a one-liner. But Pythos has been augmented to allow many such one-liners. > > Some languages have an inline operator allowing you to set the value of a variable in middle of an expression and reuse it. Python did add the walrus operator ":=" that MAYBE is what the user wants as in: > >>>> x = (y := 10) + y + y**2 >>>> x > 120 > > So it can be as simple as assigning your input using the walrus operator in a sort of inline way to save the input and use it later. > > With a slight change for clarity, the code below works in the example, albeit I have no idea what is wanted: > >>>> input("enter text: ").removesuffix(input("enter suffix: ")[1:]) > enter text: hello.avi > enter suffix: avi > 'hello.a' > > If you wanted the value of either the text or the suffix retained for a second use you can do something like this to save just the text: > >>>> (text := input("enter text: ")).removesuffix(input("enter suffix: ")[1:]) > enter text: hello.avi > enter suffix: avi > 'hello.a' >>>> text > 'hello.avi' > > Or to save both (and note the extra parentheses): > >>>> (text := input("enter text: ")).removesuffix((suffix := input("enter suffix: "))[1:]) > enter text: hello.avi > enter suffix: avi > 'hello.a' >>>> text > 'hello.avi' >>>> suffix > 'avi' > > Nobody will tell you this is code particularly elegant or easy to read versus a multi-line version and my thoughts may not be helpful if your plans are not as I guessed. > > Another guess maybe a bit further off the wall as if you ask the user for input once and they supply it and at a later time you ask the user for input and the default should be to keep the old one unless they want to change. That can easily be done for example by writing a function like this: > > def default_input(prompt, default=""): > if default != "": > prompt = prompt + "[" + default + "] " > got = input(prompt) > if got == "": > got = default > return(got) > > The above lets you keep asking the user questions and remembers their last choice so future questions can be easier as they are shown the current default and can accept it or replace it. > >>>> result = default_input("What? ") > What? this >>>> result > 'this' >>>> result = default_input("What? ", result) > What? [this] >>>> result > 'this' >>>> result = default_input("What? ", result) > What? [this] that >>>> result > 'that' > > Again, probably not what you want but I encourage you to figure out how to ask a more focused question that we can understand and answer properly. > > Q > > > > > Sent with Proton Mail secure email. > > ------- Original Message ------- > On Tuesday, May 16th, 2023 at 4:38 AM, Alan Gauld via Tutor wrote: > > >> On 16/05/2023 06:39, Goran Ikac wrote: >> >>> If a value is assigned to the string some_string, this works: >>> >>>>>> some_string = 'avion' >>>>>> some_string.removesuffix(input()[1:]) >>>>>> ton >>>>>> 'avi' >> >> >> It would help us understand what you are trying to do if you added >> prompts to your input statements: >> >> some_string = 'avion' >> some_string.removesuffix( >> input("provide suffix with extra character at the front")[1:]) >> >>> But the next statement doesn't work as I've expected (it waits for another >>> user's input): >> >> >> Because you have two input statements. It will execute both of them. >> >>>>>> input().removesuffix(input()[1:]) >>>>>> avion >>>>>> ton >>>>>> 'avi' >> >> >> Why do you want it all on one line? Normally you'd capture the two >> things then process them: >> >> some_string = input("String to process: ") >> suffix = input("enter a suffix with an extra letter: ") >> print(some_string.remove_suffix(suffix[1:]) >> >> Which is easier to read and debug and helps your user. >> >>> Now, is there a way to manipulate the input from a user so to remove a >>> slice from it, other than to assign that slice to a variable name and then >>> to manipulate that variable? >> >> >> You are not assigning a slice you are applying a slice to the string. >> It's not clear why you are using a slice but that is not relevant. >> The real question is why you want to do it all on one line? >> There is no advantage and several disadvantages. >> >> Remember the >>> prompt is not where your real programs will run, >> >> that's just for experimenting and testing. The real code will run >> using print statements etc. And you can place the input/output >> exactly where you want it. >> >>> I'd like to be able to put the user's input as an argument for a method >>> that manipulates that same user's input. The method .removesuffix() is only >>> an example. >> >> >> Sorry, I'm still not clear what you really want to do. >> Can you give us an example of a user session (without code for now) >> Just show us the inputs and expected outputs? I'll just add a general comment to the "you probably don't want to pile it all in one line" thead: Once you get used to programming in Python, you won't use the input() function very much. Programs tend to operate on larger sources of data - reading data files, pulling in a csv from somewhere, connecting to a database, etc. and very little of the inputs coming to the program will be command-line interactive. Even a GUI-oriented program will use higher-level abstractions to get back keypresses, mouse clicks, etc. When you *do* use it, you'll want to validate the data, because all data coming from such an unpredictable source as a human typing at a prompt should be assumed to be untrusted. So your flow will usually be more like: stuff = input(prompt) validate(stuff) # this is an abstract concept, not a Python language function!!! result = do_something(stuff) That's really messy to do if you're trying to jam it on one line. From goranikac65 at gmail.com Wed May 17 02:25:30 2023 From: goranikac65 at gmail.com (Goran Ikac) Date: Wed, 17 May 2023 08:25:30 +0200 Subject: [Tutor] How to manipulate a user's input twice in one statement Message-ID: I'd like to manipulate an user's input using a method. The argument for that method depends on the value of the user's input. In my previous question, I used a slice of the input as an example of a value that depends on the value of the input. I'm aware that I can get the result this way: >>> user_input = input('Please, type a word: ') >>> to_remove = user_input[1:] # The value of the slice depends of the value of the input. >>> result = user_input.removesuffix(to_remove) # The result depends on both the value of the input, and the value of the slice that was applied to the input. Or this way: >>> user_input = input('Please, type a word: ') >>> result = user_input.removesuffix(user_input[1:]) I was curious if I could get the result (that depends on both the value of the input, and the value of the slice that was applied to the input) without assigning the input to a variable first. Perhaps I could ask the same question this way: >>> user_input = int(input('Please, type a number: ')) >>> value_to_use = 2 + user_input # This value depends of the value of the input. >>> result = 3 * value_to_use # The result depends on both the input, and the output of the expression that used the input as an operand. Or this way: >>> user_input = int(input('Please, type a number: ')) >>> result = 3 * (2 + user_input) That could be written: >>> result = 3 * (2 + int(input('Please, type a number: ')) But, if I need to manipulate the value (that depends on the value of the input) by a method, not by an operand or by a function, can I do it without assigning that value or/and the value of the input to a variable? Perhaps not? People, I'm learning, not trying to write a useful program, yet. Last time when I asked a "pointless" question (NoneType List), I learned an important concept from your answers, a concept that I failed to understand properly from the textbooks. I appreciate your time very much. Love Goran from Croatia From alan.gauld at yahoo.co.uk Wed May 17 05:49:30 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 17 May 2023 10:49:30 +0100 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: On 17/05/2023 07:25, Goran Ikac wrote: > I'd like to manipulate an user's input using a method. A method is a technical term that means an operation of an object defined in a class. It is more or less the same as a function except that its part of a class. Is that what you mean by a method? If not can you expand on what you mean, with examples? > I'm aware that I can get the result this way: > >>>> user_input = input('Please, type a word: ') >>>> to_remove = user_input[1:] # The value of the slice depends >>>> result = user_input.removesuffix(to_remove) That would be the preferred way to do it. Easy to read, easy to debug and easy to maintain. >>>> user_input = input('Please, type a word: ') >>>> result = user_input.removesuffix(user_input[1:]) That's OK too, if you never need the slice again. > I was curious if I could get the result (that depends on both the value of > the input, and the value of the slice that was applied to the input) > without assigning the input to a variable first. I don't think so, that's what variables are for: to store results that you need to use more than once. >>>> user_input = int(input('Please, type a number: ')) >>>> result = 3 * (2 + user_input) > > That could be written: > >>>> result = 3 * (2 + int(input('Please, type a number: ')) It could, but it starts to get more difficult to read and much harder to debug. > But, if I need to manipulate the value (that depends on the value of the > input) by a method, not by an operand or by a function, This is where I'm confused. There is no difference between a method or a function in this regard. If you can use a function you can use a method? Can you give an example of what you tried that didn't work? > ...can I do it without > assigning that value or/and the value of the input to a variable? > Perhaps not? I suspect not. If you want to use an input value more than once you need to assign it to a variable. There is a special nameless variable (_) that might help in this case, but frankly giving a name helps readers(including future you) understand why it's there (even if the name is just 'x' or 'dummy' or 'tmp'). > People, I'm learning, not trying to write a useful program, yet. That's OK and we are happy to answer questions. But in this case I think you are trying to find a way to make your future life more difficult for yourself. Putting too much on a single line is usually a mistake that you live to regret! -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From threesomequarks at proton.me Wed May 17 11:33:10 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Wed, 17 May 2023 15:33:10 +0000 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: <4jYbPFUGjLxOTxNZPwVSzyh1FMWrCgFaBDqg6a6B2NpkHPVDqx9Ya2wD8o-AQq2F0Mwyy3E9okiMa4ER7WTIxHNZbFzsvcUCGFT55zGvkAY=@proton.me> I see Alan already supplied what I was going to add. A question that we seem to have is WHY avoiding using an explicit variable is important to you. Yes, variables with names can persist even when not needed and use a little space but you can remove a variable or contents anytime you want. There is a small chance that the name may be collide with another name or cover it, but that rarely is a problem if you make the name a tad odd. Alan mentioned that in some cases, the variable called _ is automatically set but use that with care as it gets re-set every time. It is meant to be transient. but this oddball code does work: input("number: ") print( _ * int(_), list(range(int(_),0, -1)) ) If I answer 5, I get two outputs where the _ is reused several times and the same for 15: >>> input("number: ") number: 5 '5' >>> print( _ * int(_), list(range(int(_),0, -1)) ) 55555 [5, 4, 3, 2, 1] >>> input("number: ") number: 15 '15' >>> print( _ * int(_), list(range(int(_),0, -1)) ) 151515151515151515151515151515 [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1] In my earlier letter, I offered you ways to use the := operator to instantiate a variable in mid-stream but that would not appeal to you if your goal was to never have a variable. There are, of course, oddball ways to get several views on a single variable such as a character string. But why bother? Just as an example, you could make a regular expression that matches something like this in pseudo-english. Match everything as \1 and then match the last few characters as \2 and then in your output, return what was matched in some form that lets you get them independently. So you would feed the output of input() to the regular expression function of your choice and out would come two (or more) things you want with no name that can presumably be swallowed by something else that uses both. I am not a fan of the above, and will not supply details, just making a point. What many people might do is to hide lots of details inside a function. Local variables inside go away when done and probably have no namespace collisions if the function is not looking for any outside variables with the same names. Some may even use anonymous functions albeit it can be hard to write them for multi-line constructs. I think you need to consider that calling input() returns a variable without a name. You have a pointer of sorts in the program that lets you access the contents at that memory location. It has no name so it can only be used in the current context. As soon as you move beyond the currently executing expression, it can be eligible for garbage collection. Using it again elsewhere in your program can normally be done only in one of several ways. One is if you implicitly pass a pointer along and now something else is using it. an example might be the following where no variables were harmed in the creation: >>> input("TEXT: ").upper().lstrip().rstrip() + " Thank You!" TEXT: Why am I doing THIS today? 'WHY AM I DOING THIS TODAY? Thank You!' But the use you contemplate is not as linear but a bit more like remembering what you MEANT without asking it be remembered. Python has all kinds of ways to do things and in your case, it is possible you could use objects or functional programming that encapsulate your variables in ways you might not consider as creating variables. Imagine an object that has methods to get input and save them internally as well as methods that use the saved objects to generate deeper results using them. What if each method returns the object (or a copy of it)? Could you make a new object like this and say something like: myobject.getinput1().getinput2().calculate() and have that return something like you want. No names are visible. Using functions you can wrap inaccessible names in odd ways but again, why? I bet the people here can keep coming up with ideas including some complex Rube Goldberg ones but I have not seen you supply a motivation of a real need other than some aesthetics. So I ask if you have experience with any other programming language that has a simple way to do what you want? For example, a stack-based implementation can keep pushing and popping things without explicit names but how easy is it to keep copies of multiple things around just when you need them? Why would anyone expect Python to trivially support such things? If you do find a solution that meets your expectations, please post it here for the curious. Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, May 17th, 2023 at 2:25 AM, Goran Ikac wrote: > I'd like to manipulate an user's input using a method. The argument for > that method depends on the value of the user's input. In my previous > question, I used a slice of the input as an example of a value that depends > on the value of the input. > I'm aware that I can get the result this way: > > > > > user_input = input('Please, type a word: ') > > > > to_remove = user_input[1:] # The value of the slice depends > > of the value of the input. > > > > > result = user_input.removesuffix(to_remove) > > # The result depends on both the value of the input, and the value of the > slice that was applied to the input. > > Or this way: > > > > > user_input = input('Please, type a word: ') > > > > result = user_input.removesuffix(user_input[1:]) > > > I was curious if I could get the result (that depends on both the value of > the input, and the value of the slice that was applied to the input) > without assigning the input to a variable first. Perhaps I could ask the > same question this way: > > > > > user_input = int(input('Please, type a number: ')) > > > > value_to_use = 2 + user_input # This value depends of the value > > of the input. > > > > > result = 3 * value_to_use > > # The result depends on both the input, and the output of the expression > that used the input as an operand. > > Or this way: > > > > > user_input = int(input('Please, type a number: ')) > > > > result = 3 * (2 + user_input) > > > That could be written: > > > > > result = 3 * (2 + int(input('Please, type a number: ')) > > > But, if I need to manipulate the value (that depends on the value of the > input) by a method, not by an operand or by a function, can I do it without > assigning that value or/and the value of the input to a variable? > Perhaps not? > > People, I'm learning, not trying to write a useful program, yet. Last time > when I asked a "pointless" question (NoneType List), I learned an important > concept from your answers, a concept that I failed to understand properly > from the textbooks. I appreciate your time very much. > Love > Goran from Croatia > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From abelardo.salazar.orozco at gmail.com Wed May 17 13:45:28 2023 From: abelardo.salazar.orozco at gmail.com (Abelardo Salazar Orozco) Date: Wed, 17 May 2023 11:45:28 -0600 Subject: [Tutor] =?utf-8?q?Can=E2=80=99t_find_the_=2Eenv_file?= Message-ID: Hi everyone! I am trying to install Auto-GPT through Python, but I'm stocked in step 5 since I can't find . files. I would appreciate your help very much. Have a great day! From goranikac65 at gmail.com Wed May 17 10:24:47 2023 From: goranikac65 at gmail.com (Goran Ikac) Date: Wed, 17 May 2023 16:24:47 +0200 Subject: [Tutor] How to manipulate a user's input twice in one statement Message-ID: Here we go: the concept! But first: thank you, people, I've already learned a lot from your answers and comments. Now I know, among other things (inline operator existence, for example) that the problem cannot be solved the way I wanted, and - even if it could - it wouldn't be a good, pythonic way. Mr. Gauld, I'm not competent to question the work of the genius - the language itself. I'm far, far from that (as obvious). Now, the concept: Mr. Gauld: "A method is a technical term that means an operation of an object defined in a class. It is more or less the same as a function ..." I thought so, but I did not take "... except that it's part of a class" into account. That's how I started all this mess: >>> removesuffix(some_string, some_string[1:]) Traceback (most . . . ) NameError: name 'removesuffix' is not defined >>> help(removesuffix) Traceback (most . . . ) NameError: name 'removesuffix' is not defined >>> help(str.removesuffix) Help on method_descriptor: removesuffix(self, suffix, /) Return a str . . . Aha! So, "removesuffix" can be used as a method applied to an object (the instance of ), but not as a function with a string as the first argument. The first argument must be "self". OK. Then I tried: >>> input().removesuffix(input()[1:]) ... and it didn't work as I expected. That's where I decided to ask for help. But >>> result = 3 * (2 + int(input('Please, type a number: ')) # one "input" ... worked, and I guessed if I can make the method work like a function or an operator would. Obviously, I need to learn better about classes and methods. Thank you, people, very much for your time and effort! Love from Croatia Goran From umutcaglark88 at gmail.com Wed May 17 10:15:46 2023 From: umutcaglark88 at gmail.com (=?UTF-8?B?VW11dCDDh2HEn2xhciBHw7xubMO8?=) Date: Wed, 17 May 2023 16:15:46 +0200 Subject: [Tutor] Python Message-ID: // UNFORTUNATELY, THE CODE DOESN'T COMPILE WHAT I REQUEST. // I AM THINKING THAT THE PROBLEM IS IN THE COMPILER OF // PYCHARM. WHAT SHOULD I DO? def hint_username(username): if len(username) < 3: print("Invalid username. Must be at least 3 characters long.") elif len(username) > 15: print("Invalid username. Must be at most 15 characters long.") else: print("Valid username.") hint_username("umutcaglargunsimafatehian") ----------------------------------------------------------------- /Users/umutcaglargunlu/PycharmProjects/pythonProject6/venv/bin/python /Users/umutcaglargunlu/PycharmProjects/pythonProject6/main.py Invalid username. Must be at least 3 characters long. Process finished with exit code 0 From umutcaglark88 at gmail.com Wed May 17 10:20:59 2023 From: umutcaglark88 at gmail.com (=?UTF-8?B?VW11dCDDh2HEn2xhciBHw7xubMO8?=) Date: Wed, 17 May 2023 16:20:59 +0200 Subject: [Tutor] Fwd: Python In-Reply-To: References: Message-ID: ---------- Forwarded message --------- G?nderen: Umut ?a?lar G?nl? Date: 17 May 2023 ?ar, 16:15 Subject: Python To: // UNFORTUNATELY, THE CODE DOESN'T COMPILE WHAT I REQUEST. // I AM THINKING THAT THE PROBLEM IS IN THE COMPILER OF // PYCHARM. WHAT SHOULD I DO? def hint_username(username): if len(username) < 3: print("Invalid username. Must be at least 3 characters long.") elif len(username) > 15: print("Invalid username. Must be at most 15 characters long.") else: print("Valid username.") hint_username("umutcaglargunsimafatehian") ----------------------------------------------------------------- /Users/umutcaglargunlu/PycharmProjects/pythonProject6/venv/bin/python /Users/umutcaglargunlu/PycharmProjects/pythonProject6/main.py Invalid username. Must be at least 3 characters long. Process finished with exit code 0 From mats at wichmann.us Wed May 17 15:48:15 2023 From: mats at wichmann.us (Mats Wichmann) Date: Wed, 17 May 2023 13:48:15 -0600 Subject: [Tutor] =?utf-8?q?Can=E2=80=99t_find_the_=2Eenv_file?= In-Reply-To: References: Message-ID: <912801f5-71a6-e5a6-fd14-0b92d16e3a78@wichmann.us> On 5/17/23 11:45, Abelardo Salazar Orozco wrote: > Hi everyone! > > I am trying to install Auto-GPT through Python, but I'm stocked in step 5 > since I can't find . files. > > I would appreciate your help very much. No clue at all what you're asking. What is "step 5"? None of us know. For that matter, what is auto-gpt? (although one can make a partial guess). Maybe if you describe what you did and how it didn't work? From alan.gauld at yahoo.co.uk Wed May 17 16:29:48 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 17 May 2023 21:29:48 +0100 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: On 17/05/2023 15:24, Goran Ikac wrote: > Aha! So, "removesuffix" can be used as a method applied to an object (the > instance of ), but not as a function with a string as the > first argument. The first argument must be "self". Correct. self is the string instance in the method definition but when you use it the string instance is the prefix object. The difference between a function and a method is that Pyhthon automatically converts object.method(args) to method(object, args) behind the scenes. (It does a bit more than that but from a users perspective it's close enough) >>>> input().removesuffix(input()[1:]) > > ... and it didn't work as I expected. I guess that's what I'm confused about. input() is a function like any other. It returns a string obtained from stdin(usually the user but it could be from another program or file) And you call input() twice here, so lets unpick how Python sees this. First it sees the first input and recognizes that it must return a string, so it calls it and grabs the string returned. It then calls the removesuffix() method of that string object. But removesuffix() takes a string as an argument and to get that string Python must call the second input() function invocation. That returns another string object which Python then passes to removesuffix. After removing the suffix Python gets handed yet another string object as a result which it then displays. So Python converts your code into: print( first_string.removesuffix(second_string) ) I'm not sure what you expected it to do? >>>> result = 3 * (2 + int(input('Please, type a number: ')) This is the same but you only call input() once. But Python processes it in the same way. It sees result = 3 * (2 + int(some_string)) and some_string is obtained by calling input() The only difference is that you had two calls to input() in the first case but only one in the second example. There is nothing magic about input() that would make Python remember its previous result any more than it remembers the earlier result from, say pow() So if you type: hyp = pow(pow(x,2) + pow(y,2), 0.5) pow() is called three times each completely independent of the others. It's the same with input(), it is just a function like any other. > ... worked, and I guessed if I can make the method work like a function or > an operator would. > Obviously, I need to learn better about classes and methods. I'm not sure that's the problem here. Apart from the fact that removesuffix() is a method of a string rather than a stand-alone function it doesn't change how it interacts with input() In fact you could create a function that would do the same job and it would have the same effect: def remove_suffix(aString, aSuffix): return aString.removesuffix(aSuffix) now you could try calling it with input(): remove_suffix(input(),input()) You would still get the same double call to input() If you wanted to use the same result(and slice it you could use the walrus operator: remove_suffix(s := input(), s[1:]) but that still requires a variable it just keeps it inside the line(but it is still available afterwards too!). I hope that makes sense. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed May 17 16:37:52 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 17 May 2023 21:37:52 +0100 Subject: [Tutor] Python In-Reply-To: References: Message-ID: First, you only need to post once. It will sit in the moderation queue until accepted but it will get here eventually (usually within a few hours). On 17/05/2023 15:15, Umut ?a?lar G?nl? wrote: > // UNFORTUNATELY, THE CODE DOESN'T COMPILE WHAT I REQUEST. > // I AM THINKING THAT THE PROBLEM IS IN THE COMPILER OF > // PYCHARM. WHAT SHOULD I DO? A compile error would produce an error - usually a syntax errror. It looks like your code is compiling fine. The error is that the result is not what you expected. Unfortunately your code has lost indentation (you must post in plain text to retain indentation) so it is hard to know what might be wrong. > def hint_username(username): > if len(username) < 3: > print("Invalid username. Must be at least 3 characters long.") > elif len(username) > 15: > print("Invalid username. Must be at most 15 characters long.") > else: > print("Valid username.") > > hint_username("umutcaglargunsimafatehian") > > ----------------------------------------------------------------- > > /Users/umutcaglargunlu/PycharmProjects/pythonProject6/venv/bin/python > /Users/umutcaglargunlu/PycharmProjects/pythonProject6/main.py > Invalid username. Must be at least 3 characters long. > > Process finished with exit code 0 At first glance I don't see any code errors(assuming the indentation is sane). What happens if you save the file and run it from the Python interpreter at the command line? -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From alan.gauld at yahoo.co.uk Wed May 17 16:44:18 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Wed, 17 May 2023 21:44:18 +0100 Subject: [Tutor] =?utf-8?q?Can=E2=80=99t_find_the_=2Eenv_file?= In-Reply-To: References: Message-ID: On 17/05/2023 18:45, Abelardo Salazar Orozco wrote: > I am trying to install Auto-GPT through Python, but I'm stocked in step 5 > since I can't find . files. You need to give us a lot more information for us to help. First, what python version and OS are you using? Where did you find Auto-GPT (are you sure that's the right spelling, it's kind of unusual) How are you trying to install it? From an app store? Building from source? Using an OS package manager? Using git or pip? Exactly what command do you type? Exactly what error do you get(cut n paste please)? What are . files? Which . files specifically are you looking for? Where have you looked? Most of us will not have heard of your package let alone installed it. We almost certainly are not using the same computer setup as you. The more detail you can provide the more we are likely able to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From learn2program at gmail.com Wed May 17 19:45:54 2023 From: learn2program at gmail.com (Alan Gauld) Date: Thu, 18 May 2023 00:45:54 +0100 Subject: [Tutor] =?utf-8?q?Fwd=3A__Can=E2=80=99t_find_the_=2Eenv_file?= In-Reply-To: References: Message-ID: Forwarding to list. Please use reply-All or reply-List when responding to tutor poss. Also note that the list is text only so attachments are stripped by the server for security reasons. I've pasted the content for the list to read.... Having read the instructions in step 5 it seems you should use Textedit (or any other editor) to edit the .env file. ############################################## Cloning into 'Auto-GPT* remote: Enumerating objects: 12414, done. remote: Counting objects: 100% (306/306), done. remote: Compressing objects: 100% (189/189), done. remote: Total 12414 (delta 146), reused 246 (delta 114), pack-reused 12108 Receiving objects: 100% (12414/12414), 7.03 MiB 5.77 MiB/s, done. Resolving deltas: 100% (8295/8295), done. (base) " cd Auto-GPT (base) ?Auto-GPT Ipip install -r requirements. txt Collecting en-core-web-sm@ https://github.com/explosion/spacy-models/releases/download/en core_web_sm-3.5.0/en core web sm-3.5.0-py3-none-any.whl Downloading https://github.com/explosion/spacy-models/releases/download/en core web sm-3.5.0/en core web sm-3.5.0-py3-none-any.whl (12.8 MB) 12.8/12.8 MB 7.0 MB/s eta 0:00:00 Requirement already satisfied: beautifulsoup4>m4.12.2 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 1)) (4.12.2) Requirement already satisfied: colorama0.4.6 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 2)) (0.4.6) Requirement already satisfied: distrow1.8.0 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 3)) (1.8.0) Requirement already satisfied: openais0.27.2 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 4)) (0.27.2) Requirement already satisfied: playsound =1.2.2 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 5)) (1.2.2) Requirement already satisfied: python-dotenvam1.0.0 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 6)) (1.0.0) Requirement already satisfied: pyyamlas6.0 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 7)) (6.0) Requirement already satisfied: readability-Ixmlwm0.8.1 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 8)) (0.8.1) Requirement already satisfied: requests in /opt/anaconda3/lib/python3.9/site-packages from -r requirements.txt (line 9)) (2.30.0) Requirement already satisfied: tiktoken-0.3.3 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 10)) (0.3.3) Requirement already satisfied: gTTS?2.3.1 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 11)) (2.3.1) Requirement already satisfied: docker in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 12)) (6.1.2) Requirement already satisfied: duckduckgo-search> 2.9.5 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 13)) (2.9.5) Requirement already satisfied: google-api-python-client in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 14)) (2.86.0) Requirement already satisfied: pinecone-client==2.2.1 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 15)) (2.2.1) Requirement already satisfied: redis in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 16)) (4.5.5) Requirement already satisfied: orjson-3.8.10 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 17)) (3.8.10) Requirement already satisfied: Pillow in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 18)) (9.2.0) Requirement already satisfied: selenium==4.1.4 in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 19)) (4.1.4) Requirement already satisfied: webdriver-manager in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 20)) (3.8.6) Requirement already satisfied: jsonschema in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 21)) (4.16.0) Requirement already satisfied: tweepy in /opt/anaconda3/lib/python3.9/site-packages (from -r requirements.txt (line 22)) (4.14.0) Requirement already satisfied: distlib<1,> 0.3.6 in /opt/anaconda3/lib/python3.9/site-packages (from virtualenv> 20.10.0-?pre-commit->-r requirements.txt (line 32) ) (0.3.6) Requirement already satisfied: filelock<4,>=3.11 in /opt/anaconda3/lib/python3.9/site-packages (from virtualenv> 20.10.0->pre-commit->-r requirements.txt (line 32) ) (3.12.0) Requirement already satisfied: aiosignal>=1.1.2 in /opt/anaconda3/lib/python3.9/site-packages (from aichttp->openai==0.27.2->-r requirements.txt (line 4)) (1.3.1) Requirement already satisfied: multidict<7.0,> 4.5 in /opt/anaconda3/lib/python3.9/site-packages (from aiohttp->openai0.27.2->-r requirements.txt (line 4)) (6.0. 4) Requirement already satisfied: frozenlist>mi.1.1 in /opt/anaconda3/lib/python3.9/site-packages (from aiohttp->openai0.27.2->-r requirements.txt (line 4)) (1.3.3) Requirement already satisfied: cffi>1.12 in /opt/anaconda3/lib/python3.9/site-packages (from cryptography> 1.3.4-?urllib3> 1.21.1->pinecone-client 2.2.1->-r requ irements.txt (line 15)) (1.15.1) Requirement already satisfied: h11<0.15,> 0.13 in /opt/anaconda3/lib/python3.9/site-packages (from httpcore<0.18.0,> 0.15.0->httpx<0.25.0,>=0.15.4->openapi-python-client==0.13.4->-r requirements.txt (line 42)) (0.14.0) Requirement already satisfied: anyio<5.0,> 3.0 in /opt/anaconda3/lib/python3.9/site-packages (from httpcore<0.18.0,> 0.15.0->httpx<0.25.0,>=0.15.4->openapi-python-client 0.13.4->-r requirements.txt (line 42)) (3.5.0) Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /opt/anaconda3/lib/python3.9/site-packages (from pyasnI-modules>=0.2.1->google-auth<3.0.0dev,>=1.19.0->googl e-api-python-client->-r requirements.txt (line 14)) (0.4.8) Requirement already satisfied: pycparser in /opt/anaconda3/lib/python3.9/site-packages (from cffi>=1.12->cryptography>=1.3.4-?urllib3>=1.21.1->pinecone-client==2.2 ?1->-r requirements.txt (line 15)) (2.21) Installing collected packages: mypy-extensions, my Attempting uninstall: mypy-extensions Found existing installation: mypy-extensions 0.4.3 Uninstalling mypy-extensions-0.4.3: Successfully uninstalled mypy-extensions-0.4.3 Successfully installed mpy-1.3.0 mypy-extensions-1.0.0 (base) FAuto-GPT Pcp . env. template env (base) _: Auto-GPT Ils .flake8 BULLETIN.md ?git CODE_OF_CONDUCT.md ?coveragerc .devcontainer .dockerignore ?env ?env. template ?envrc .gitattributes CONTRIBUTING. md .github Dockerfile .gitignore LICENSE .isort.cfg README. md .pre-commit-config. yaml autogpt .sourcery.yaml azure.yaml. template benchmark codecov. yml data data ingestion.py docker-compose. ym1 docs main.py mkdocs. ym1 mypy.ini plugin.png plugins prompt settings.yaml pyproject. toml requirements.txt run.bat run. sh run_continuous.bat run_continuous.sh scripts tests tests.py -------- Forwarded Message -------- Subject: Re: [Tutor] Can?t find the .env file To: Alan Gauld Content-Type: multipart/mixed; boundary="000000000000215ce205fbebbc79" Content-Length: 1614562 Yes, I believe that is what it's called, it is an experimental autonomous AI assistant using GPT-4 (GitHub - Significant-Gravitas/Auto-GPT: An experimental open-source attempt to make GPT-4 fully autonomous. ) and I'm trying to install it using pip as in the instructions attached below. But I keep stuck at finding the .env file where I'm supposed to enter my OpenAI API key. I kind of highlighted where the problem is and that the?file I'm looking for is indeed in the folder. I'm not an expert?in Python so I appreciate your patience. I am using a macOS version?10.15.7 and Python 3. El mi?, 17 may 2023 a las 14:45, Alan Gauld via Tutor (>) escribi?: On 17/05/2023 18:45, Abelardo Salazar Orozco wrote: > I am trying to install Auto-GPT through Python, but I'm stocked in step 5 > since I can't find . files. You need to give us a lot more information for us to help. First, what python version and OS are you using? Where did you find Auto-GPT (are you sure that's the right spelling, it's kind of unusual) How are you trying to install it? From an app store? Building from source? Using an OS package manager? Using git or pip? Exactly what command do you type? Exactly what error do you get(cut n paste please)? What are . files? Which . files specifically are you looking for? Where have you looked? Most of us will not have heard of your package let alone installed it. We almost certainly are not using the same computer setup as you. The more detail you can provide the more we are likely able to help. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos _______________________________________________ Tutor maillist? -? Tutor at python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor From threesomequarks at proton.me Wed May 17 20:24:14 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 18 May 2023 00:24:14 +0000 Subject: [Tutor] How to manipulate a user's input twice in one statement In-Reply-To: References: Message-ID: Goran, As you learn, you have to make distinctions. A function defined with def is not associated with a class and indeed there is no concept of a self. A class you created yourself can have instance methods that are given a copy of the self when invoked properly on an instance of that object. Just to be confusing, you can make methods associated with the class that pretty much act like a regular function in a sort of namespace of the class like math.sin() ... But the class holding str objects is not created by you and has only the methods you can get by typing: >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] So it does seem to be there. And the following works fine for me: >>> input("text ").removesuffix(".avi") text xyz.avi 'xyz' What I am wondering is if what you want is not to remove a fixed suffix but anything starting with a period near the end. In the old days, a suffix was up to three characters but no longer. So the way to do it is NOT necessarily to ask for a suffix, or to look at the last few letters but perhaps other ways. One way is to search back from the end of the string till you find a period and then just copy everything before it. Lots of modules can be used, such as this one: >>> import os.path >>> os.path.splitext("abc.defg") ('abc', '.defg') >>> os.path.splitext("abc.defg")[0] 'abc' And of course there are regular expressions where you ask to greedily match everything and save it as \1 followed by a period and anything and then replace it with just \1. If you have an assignment that asks you to use a particular tool, fine. If not, your method is only helpful if you are sure of the length of the suffix and in that case, you can use a subset at the end of the string to remove the end. Still, it is perhaps easier to use just the subset BEFORE and throw away the rest. Sent with Proton Mail secure email. ------- Original Message ------- On Wednesday, May 17th, 2023 at 4:29 PM, Alan Gauld via Tutor wrote: > On 17/05/2023 15:24, Goran Ikac wrote: > > > Aha! So, "removesuffix" can be used as a method applied to an object (the > > instance of ), but not as a function with a string as the > > first argument. The first argument must be "self". > > > Correct. self is the string instance in the method definition but when > you use it the string instance is the prefix object. The difference > between a function and a method is that Pyhthon automatically converts > > object.method(args) > to > method(object, args) > > behind the scenes. (It does a bit more than that but from > a users perspective it's close enough) > > > > > > input().removesuffix(input()[1:]) > > > > ... and it didn't work as I expected. > > > I guess that's what I'm confused about. > input() is a function like any other. It returns a string obtained from > stdin(usually the user but it could be from another program or file) > > And you call input() twice here, so lets unpick how Python sees this. > > First it sees the first input and recognizes that it must return > a string, so it calls it and grabs the string returned. It then > calls the removesuffix() method of that string object. > > But removesuffix() takes a string as an argument and to get that > string Python must call the second input() function invocation. > That returns another string object which Python then passes > to removesuffix. > > After removing the suffix Python gets handed yet another > string object as a result which it then displays. > > So Python converts your code into: > > print( first_string.removesuffix(second_string) ) > > I'm not sure what you expected it to do? > > > > > > result = 3 * (2 + int(input('Please, type a number: ')) > > > This is the same but you only call input() once. > But Python processes it in the same way. > > It sees result = 3 * (2 + int(some_string)) > > and some_string is obtained by calling input() > > The only difference is that you had two calls to input() in > the first case but only one in the second example. > > There is nothing magic about input() that would make > Python remember its previous result any more than it > remembers the earlier result from, say pow() > > So if you type: > > hyp = pow(pow(x,2) + pow(y,2), 0.5) > > pow() is called three times each completely independent > of the others. It's the same with input(), it is just a > function like any other. > > > ... worked, and I guessed if I can make the method work like a function or > > an operator would. > > Obviously, I need to learn better about classes and methods. > > > I'm not sure that's the problem here. Apart from the fact > that removesuffix() is a method of a string rather than a > stand-alone function it doesn't change how it interacts > with input() > > In fact you could create a function that would do the > same job and it would have the same effect: > > def remove_suffix(aString, aSuffix): > return aString.removesuffix(aSuffix) > > now you could try calling it with input(): > > remove_suffix(input(),input()) > > You would still get the same double call to input() > If you wanted to use the same result(and slice it you > could use the walrus operator: > > remove_suffix(s := input(), s[1:]) > > but that still requires a variable it just keeps it > inside the line(but it is still available afterwards too!). > > I hope that makes sense. > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From wlfraed at ix.netcom.com Thu May 18 17:48:30 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Thu, 18 May 2023 17:48:30 -0400 Subject: [Tutor] =?utf-8?q?Can=E2=80=99t_find_the_=2Eenv_file?= References: Message-ID: On Wed, 17 May 2023 11:45:28 -0600, Abelardo Salazar Orozco declaimed the following: >Hi everyone! > >I am trying to install Auto-GPT through Python, but I'm stocked in step 5 >since I can't find . files. > >I would appreciate your help very much. > You've already seen requests for OS, etc. but based upon some follow-up responses I'm going to make a wild guess. I suspect you are running a Linux/UNIX distribution. By default any file that begins with a "." is a HIDDEN file when looking at directory contents. COMPARE: debian at beaglebone:~$ ls -l total 68 -rwxr-xr-x 1 debian debian 531 Apr 16 2021 autotest.py drwxr-xr-x 2 debian debian 4096 May 12 2021 BBB_IO drwxr-xr-x 2 debian debian 4096 Aug 19 2020 bin -rw-r--r-- 1 debian debian 105 Dec 11 2020 bno055.py drwxr-xr-x 2 debian debian 4096 Sep 8 2020 exploring -rw-r--r-- 1 debian debian 1637 May 22 2021 hutdown drwxr-xr-x 2 debian debian 4096 Apr 16 2021 logs -rwxr-xr-x 1 debian debian 28816 May 11 2021 main drwxr-xr-x 2 debian debian 4096 Aug 22 2020 OS-setup -rw-r--r-- 1 debian debian 672 Dec 6 2021 ugly_test.py debian at beaglebone:~$ ls -la total 140 drwxr-xr-x 11 debian debian 4096 Feb 20 2022 . drwxr-xr-x 3 root root 4096 Aug 19 2020 .. -rwxr-xr-x 1 debian debian 531 Apr 16 2021 autotest.py -rw-r--r-- 1 debian debian 118 Aug 22 2020 .bash_aliases -rw------- 1 debian debian 5423 Nov 2 2022 .bash_history -rw-r--r-- 1 debian debian 220 Aug 22 2020 .bash_logout -rw-r--r-- 1 debian debian 3516 Aug 22 2020 .bashrc drwxr-xr-x 2 debian debian 4096 May 12 2021 BBB_IO drwxr-xr-x 2 debian debian 4096 Aug 19 2020 bin -rw-r--r-- 1 debian debian 105 Dec 11 2020 bno055.py lrwxrwxrwx 1 debian debian 16 Apr 30 2021 .c9 -> /opt/cloud9/.c9/ drwxr-xr-x 3 debian debian 4096 Dec 11 2020 .cache drwx------ 3 debian debian 4096 Jan 5 2021 .config drwxr-xr-x 2 debian debian 4096 Sep 8 2020 exploring -rw-r--r-- 1 debian debian 0 Aug 19 2020 .gitconfig drwx------ 3 debian debian 4096 Aug 22 2020 .gnupg -rw-r--r-- 1 debian debian 1637 May 22 2021 hutdown drwx------ 4 debian debian 4096 Mar 2 2021 .local drwxr-xr-x 2 debian debian 4096 Apr 16 2021 logs -rwxr-xr-x 1 debian debian 28816 May 11 2021 main drwxr-xr-x 2 debian debian 4096 Aug 22 2020 OS-setup -rw-r--r-- 1 debian debian 675 Aug 22 2020 .profile -rw------- 1 debian debian 691 Feb 20 2022 .python_history -rw-r--r-- 1 debian debian 75 Apr 16 2021 .selected_editor -rw-r--r-- 1 debian debian 672 Dec 6 2021 ugly_test.py -rw------- 1 debian debian 10432 May 12 2021 .viminfo -rw-r--r-- 1 debian debian 64 Aug 19 2020 .xsessionrc If you are using an X-window/desktop environment, you'll have to find out how to get it to display hidden files. From threesomequarks at proton.me Thu May 18 19:17:53 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Thu, 18 May 2023 23:17:53 +0000 Subject: [Tutor] What's in a name. Message-ID: I was thinking about a recent question that is now better understood. Part of it may boil down to a choice of names. Sometimes a name may make some people feel like a function or variable may be doing something else than it does. The word I am talking about now is "suffix" and in some sense it means something appended to the end of something else. That has more specifix meanings in areas of computer science where it may mean a part of a filename at the end after some market like a period. Actually, I have seen multiple suffixes of sorts in a row such as in an old operating system, a file.c;3 is the third version/copy of an edited file containing part or all of a program written in the C language. Many human languages let you pile one suffix after another to extend a words to have many additional layers of meaning including gender and plurality and possessiveness and quite a few more in some languages. So the OP had a task to do where they read in a string that perhaps was meant to be a filename and remove a suffix perhaps looking like .xyz and they noticed a method called removesuffix() which sounded right. But is it? Nope. Not in general as what the function is designed to do is remove an exact suffix you supply. It can be used this way as in "proportional".removesuffix("al") with no periods in sight. So it looks like the OP thought about perhaps asking the person who typed in the text a second questions asking what suffix to omit. This strikes me as odd in several ways as they could have typed it in a shorter version in the first request from the user and also because the user might provide ".xyz" or just "xyz" or anything else and then removing that may fail or leave part behind such as the period. It does not look like a great one-liner to me. So the OP seems to have found removesuffix as a plan and then rather than go for a different plan, wanted to fix it by calculating the suffix without creating a variable name and passing that to removesuffix. It could be an ingenious solution if it worked but again, stepping back, is it? As I see it, if the intent has to strip a suffix for a filename and especially one that uses a period and may have more than one, as in modern operating systems, it can be better to hunt for a module that someone has written carefully and is well tested. Consider a case where the user has chosen a file called hello.exe and you want to find a file called hello.c that corresponds to it. Using normal string-manipulation methods, you can do quite a bit, even if not inline. You can for example split the text of the name on a period and ignore the last component but how well will you handle a name like xyz.c.tar.gz in which you have multiple suffixes that can be peeled away by uncompressing and then removing an item from within an archive file? Finally, you need to back away from the C suffix if you really want what some might call a basename. So you can do this yourself and cover mainly the cases that matter to you. Or you can find functions that more easily match your need. The OP was supplied with some suggestions including one that sort of fits part of what maybe they need by careful use of the walrus operator (or just multiple lines of code) to extract the suffix while retaining the original name. But I am guessing that in some ways it was not really a good thing to answer what was asked versus suggesting a reconsideration and doing anything else. I offered suggestions that can be explored without lots of details but each has plusses and minuses and often the names of the parts may not be meaningful. A function with a name like basename() may not be meaningful. But even the concept or removing an ending is flawed. The goal is not about removing but not having the suffix. A straightforward alternate approach might be a way to identify what part of the name is before the first (or maybe last) period and keep that. It can be as simple as making a new empty string or list of characters and looping on the original while copying one character at a time until you hit a period and stopping copying. It can be moving from the back until you hit a period and noting what position you are at and taking a view of the original between the beginning and the spot before a period as in text[1:(N-1)] or something like that. There are all kinds of functions that simply search for you and return the index at which something is found. And more generally you can use fairly simple but powerful regular expressions to match various parts and keep what parts you want in what order. Some may even focus in and only recognize specific sets of suffixes like .c and .h as your needs dictate. Bottom line is the python object we talk about as being of type str has NOTHING to do with filenames. It has more broad uses. You cannot expect it to remove suffixes in filenames except in the same way it will remove suffixes in general text. But other places and objects may be a better choice. If there is an object I will call "filename" then it might have a method that does what you want and maybe you can write code like: base = filename(input("Type a filename in full: ")).desuffixize() Python people have made a truly stupid statement years ago suggesting that the language generally has one obvious way to do things. In my experience, it pretty much NEVER has only one way and you have too many ways to choose from. Reading code written by others (especially without comments) can be almost painful as you try to figure out what exactly they are trying to do which often is not on your short list of ways you might have done it. So choosing names in your program can be a challenge as it is the first part of you communicating with anyone reading your code or using your function. Had the people named removesuffix as remove_end_characters_as_specified_if_they_exist() it would be a pain to use but might not make you think it was the best choice for what the OP seems to want. Sent with [Proton Mail](https://proton.me/) secure email. From cs at cskk.id.au Thu May 18 19:38:54 2023 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 19 May 2023 09:38:54 +1000 Subject: [Tutor] What's in a name. In-Reply-To: References: Message-ID: On 18May2023 23:17, ThreeBlindQuarks wrote: >Python people have made a truly stupid statement years ago suggesting >that the language generally has one obvious way to do things. That's not what the Zen says: There should be one-- and preferably only one --obvious way to do it. That's a design objective: for common tasks, there should be an obvious thing to do for it, and not a plethora of similar features requiring a careful choice. From alan.gauld at yahoo.co.uk Thu May 18 20:28:55 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Fri, 19 May 2023 01:28:55 +0100 Subject: [Tutor] What's in a name. In-Reply-To: References: Message-ID: On 19/05/2023 00:17, ThreeBlindQuarks via Tutor wrote: > The word I am talking about now is "suffix" and in some sense > it means something appended to the end of something else. That > has more specifix meanings in areas of computer science where > it may mean a part of a filename at the end And there are dedicated functions for manipulating filenames and paths, including removing suffixes. (os.path.splitext()) Although it calls the file suffixes extensions, hence .splitext(). > an old operating system, a file.c;3 Ah, the joys of Vax/VMS > So it looks like the OP thought about perhaps asking the > person who typed in the text a second questions asking what suffix My impression was that they thought Python should remember and reuse the first input value, maybe because it was on the same line? I dunno. > As I see it, if the intent has to strip a suffix for a filename > and especially one that uses a period and may have more than one, > as in modern operating systems, it can be better to hunt for a > module that someone has written carefully and is well tested. Indeed, like os.path But that may not be obvious to a beginner - you need to know what terms to search for - extension in this case! > to back away from the C suffix if you really want what some might call a basename. Which is what os.path calls it, with a method to match. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos From threesomequarks at proton.me Thu May 18 21:45:07 2023 From: threesomequarks at proton.me (ThreeBlindQuarks) Date: Fri, 19 May 2023 01:45:07 +0000 Subject: [Tutor] What's in a name. In-Reply-To: References: Message-ID: I appreciate the correction Cameron. How much does it narrow things if the goal is to only have one OBVIOUS way? I have seen too many places where even the obvious ways were too numerous. If I ask you to take a string and substitute in various parameters held in variables, which method is obvious? At least five major methods are supported that overlap quite a bit and some have relatively unique features. These days, some might argue you should mainly just use an f-string but clearly older code mainly used other methods and there is no pressure to change. Arguably quite a few programs in ANY language have a somewhat obvious way to do parts of a task or even to combine those parts into larger and larger subunits. Python is far from unique in this regard. But consider newly added features that allow you to do things that have often been done another way. I mentioned the walrus operator which provides a new way you can write code even if it does not really need it as in a multi-line style. What about the new pattern matching features? Arguably you could use them to do complex things but also trivial things like use them instead of an if/else statement. I am not making fun of Python but continue to not take seriously anyone who truly believes there are usually obvious ways to do things in a language like Python. I submit many people either do not know the Pythonic way that others claim is a thing or disagree with it at times. I remember reading that perhaps a pythonic way not often found easily in languages like C was to just try something without lots of checking and arrange to deal with errors like dividing by zero. I admit I am attracted by such ideas but also not fully trusting them at times. In various languages I noted the errors that propagated in calculations that contained unknown data as in NA as well as when you allow values like Inf or NaN. Unless you are SURE there are no such numbers, it can get a bit annoying as they are not treated as an error in situations like sum(vector) returning an NA if any one of the contents is NA and propagating that into any equation that uses it and so on. Lots of statistical analyses become garbage unless you use a variant that says things like sum(vector, na.rm=TRUE) OR you pre-process your data and remove or hide parts before doing an analysis. Any catchable error that finally triggers an alarm may be far removed from the cause. So some programmers would rather go slowly and carefully and check as they go along. Arguably, Pythonistas do not advocate this try/except method to be used in complex cases. Sometimes the way to do it is not as obvious as others. Just for fun, consider the quadratic formula and the one best/right way to calculate when it has ? as part of the formula. Some who consider things like efficiency will calculate some parts and store them in variables then continue to calculate the two alternatives. Others will just brute force do two complete and independent calculations. Still others may want to cache answers in case the same one will be asked again. Some may even want to use a fairly expensive equation solver that does not use the formula at all. A language can only force a single solution by making other methods not be present or make them too hard to use much. The goal of Python to me is to be more inclusive and make many ways possible. But, the goal includes fighting some of that bloat mainly by placing much functionality in modules loaded only when needed. So although we are discussing a historical quote, I wonder if they would say that again or even want there to be a main obvious way. Sent with Proton Mail secure email. ------- Original Message ------- On Thursday, May 18th, 2023 at 7:38 PM, Cameron Simpson wrote: > On 18May2023 23:17, ThreeBlindQuarks threesomequarks at proton.me wrote: > > > Python people have made a truly stupid statement years ago suggesting > > that the language generally has one obvious way to do things. > > > That's not what the Zen says: > > There should be one-- and preferably only one --obvious way to do it. > > That's a design objective: for common tasks, there should be an obvious > thing to do for it, and not a plethora of similar features requiring a > careful choice. > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor From cs at cskk.id.au Thu May 18 22:09:33 2023 From: cs at cskk.id.au (Cameron Simpson) Date: Fri, 19 May 2023 12:09:33 +1000 Subject: [Tutor] What's in a name. In-Reply-To: References: Message-ID: On 19May2023 01:45, ThreeBlindQuarks wrote: >I appreciate the correction Cameron. How much does it narrow things if >the goal is to only have one OBVIOUS way? Well, "obvious" is a subjective term. The design objective expressed in the Zen is that for _common_ tasks, there should be an obvious way to do it (which will be correct, i.e. not misleadingly named or with confusing semantics). It's not a statement that this will always be the case, just an expression that this is desirable most of the time. Ergonomics, ease of correct use. >I have seen too many places where even the obvious ways were too numerous. Doubtless. But if (to take your "suffix" based examples) there are many choices, maybe this is a hint that the class you're working on (if it is a class) could do with a purpose built method implementing the commonly preferred way. >If I ask you to take a string and substitute in various parameters held in variables, which method is obvious? That can be a complex task, but probably str.format these days. >At least five major methods are supported that overlap quite a bit and some have relatively unique features. These days, some might argue you should mainly just use an f-string but clearly older code mainly used other methods and there is no pressure to change. Right. Historic features don't go away because that would break code. But if there's a _good_ new feature then that should become the "obvious way to do it" for the common cases. [...] >I am not making fun of Python but continue to not take seriously anyone >who truly believes there are usually obvious ways to do things in a >language like Python. I submit many people either do not know the >Pythonic way that others claim is a thing or disagree with it at times. [...] Reiterating: it is a design objective, both for things in the stdlib and for Pythonic code people are writing anew. It isn't always met, and if the use cases are new or nebulous it _can't_ be met in any universal way. It's just saying that Pythonic code should hopefully offer obvious choices for common needs. Cheers, Cameron Simpson From abelardo.salazar.orozco at gmail.com Thu May 18 21:23:40 2023 From: abelardo.salazar.orozco at gmail.com (Abelardo Salazar Orozco) Date: Thu, 18 May 2023 19:23:40 -0600 Subject: [Tutor] =?utf-8?q?Can=E2=80=99t_find_the_=2Eenv_file?= In-Reply-To: References: Message-ID: I already could. Thank you very much. El El jue, 18 de mayo de 2023 a la(s) 15:49, Dennis Lee Bieber < wlfraed at ix.netcom.com> escribi?: > On Wed, 17 May 2023 11:45:28 -0600, Abelardo Salazar Orozco > declaimed the following: > > >Hi everyone! > > > >I am trying to install Auto-GPT through Python, but I'm stocked in step 5 > >since I can't find . files. > > > >I would appreciate your help very much. > > > > You've already seen requests for OS, etc. but based upon some > follow-up > responses I'm going to make a wild guess. > > I suspect you are running a Linux/UNIX distribution. > > By default any file that begins with a "." is a HIDDEN file when > looking at directory contents. > > COMPARE: > > debian at beaglebone:~$ ls -l > total 68 > -rwxr-xr-x 1 debian debian 531 Apr 16 2021 autotest.py > drwxr-xr-x 2 debian debian 4096 May 12 2021 BBB_IO > drwxr-xr-x 2 debian debian 4096 Aug 19 2020 bin > -rw-r--r-- 1 debian debian 105 Dec 11 2020 bno055.py > drwxr-xr-x 2 debian debian 4096 Sep 8 2020 exploring > -rw-r--r-- 1 debian debian 1637 May 22 2021 hutdown > drwxr-xr-x 2 debian debian 4096 Apr 16 2021 logs > -rwxr-xr-x 1 debian debian 28816 May 11 2021 main > drwxr-xr-x 2 debian debian 4096 Aug 22 2020 OS-setup > -rw-r--r-- 1 debian debian 672 Dec 6 2021 ugly_test.py > > debian at beaglebone:~$ ls -la > total 140 > drwxr-xr-x 11 debian debian 4096 Feb 20 2022 . > drwxr-xr-x 3 root root 4096 Aug 19 2020 .. > -rwxr-xr-x 1 debian debian 531 Apr 16 2021 autotest.py > -rw-r--r-- 1 debian debian 118 Aug 22 2020 .bash_aliases > -rw------- 1 debian debian 5423 Nov 2 2022 .bash_history > -rw-r--r-- 1 debian debian 220 Aug 22 2020 .bash_logout > -rw-r--r-- 1 debian debian 3516 Aug 22 2020 .bashrc > drwxr-xr-x 2 debian debian 4096 May 12 2021 BBB_IO > drwxr-xr-x 2 debian debian 4096 Aug 19 2020 bin > -rw-r--r-- 1 debian debian 105 Dec 11 2020 bno055.py > lrwxrwxrwx 1 debian debian 16 Apr 30 2021 .c9 -> /opt/cloud9/.c9/ > drwxr-xr-x 3 debian debian 4096 Dec 11 2020 .cache > drwx------ 3 debian debian 4096 Jan 5 2021 .config > drwxr-xr-x 2 debian debian 4096 Sep 8 2020 exploring > -rw-r--r-- 1 debian debian 0 Aug 19 2020 .gitconfig > drwx------ 3 debian debian 4096 Aug 22 2020 .gnupg > -rw-r--r-- 1 debian debian 1637 May 22 2021 hutdown > drwx------ 4 debian debian 4096 Mar 2 2021 .local > drwxr-xr-x 2 debian debian 4096 Apr 16 2021 logs > -rwxr-xr-x 1 debian debian 28816 May 11 2021 main > drwxr-xr-x 2 debian debian 4096 Aug 22 2020 OS-setup > -rw-r--r-- 1 debian debian 675 Aug 22 2020 .profile > -rw------- 1 debian debian 691 Feb 20 2022 .python_history > -rw-r--r-- 1 debian debian 75 Apr 16 2021 .selected_editor > -rw-r--r-- 1 debian debian 672 Dec 6 2021 ugly_test.py > -rw------- 1 debian debian 10432 May 12 2021 .viminfo > -rw-r--r-- 1 debian debian 64 Aug 19 2020 .xsessionrc > > If you are using an X-window/desktop environment, you'll have to > find > out how to get it to display hidden files. > > _______________________________________________ > Tutor maillist - Tutor at python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > From blackdymondzinc at gmail.com Mon May 22 12:56:30 2023 From: blackdymondzinc at gmail.com (Michael Reubel) Date: Mon, 22 May 2023 09:56:30 -0700 Subject: [Tutor] RollDieDynamic Message-ID: To whomever this may concern, Hello my name is Michael Reubel. I need some help with installing RollDieDynamic on my system.I am taking an online course for python. And following the steps that are a part of the program didn't work like I thought it would. In the program I have opened my CMD from Windows. - Extracted the zip files under Desktop. - Found out that my zip file was stored in my OneDrive. - I then proceeded to use cd Onedrive. - Typed cd Desktop - cd IntroToPythonMaster (that is how it is titled in my system). - cd examples and i get a message that reads the system cannot find the path specified. I've also searched on Youtube on how to create a Path and I didn't get much help from that either. If someone can help guide me with this problem I would greatly appreciate it. Thank you for your time. Sincerely, Michael Reuebl From Chelsea.Burke at fda.hhs.gov Mon May 22 10:14:02 2023 From: Chelsea.Burke at fda.hhs.gov (Burke, Chelsea) Date: Mon, 22 May 2023 14:14:02 +0000 Subject: [Tutor] Openpyxl Message-ID: Good morning, I'm having issues with openpyxl, specifically the load_workbook function. It previously was working just fine, but I cannot get any workbook to load anymore using this function. Below is the error that keeps popping up every time I run it. Is there something wrong with the source code for this package? I've tried downgrading the versions from 3.1.2 to 3.1.1 and 3.1.0 and still have the same error. [cid:image001.png at 01D98C8D.BE4F5D90] I've tried just loading a blank workbook from different directories as well and still seem to have the error. I do have a package folder for ~penpyxl that seems to be where the code is coming from based on the line 342 given for the error, but the directory is ~penpyxl.worsheet._reader.WorksheetRead.__init__ and not the "openpyxl.worksheet..." directory. Any help on this would be greatly appreciated. Thanks, Chelsea Burke From alan.gauld at yahoo.co.uk Tue May 23 07:18:13 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Tue, 23 May 2023 12:18:13 +0100 Subject: [Tutor] RollDieDynamic In-Reply-To: References: Message-ID: <055E292F-8742-486E-9106-88AFB7DF984E@yahoo.co.uk> Sent from my iPad > On 22 May 2023, at 19:18, Michael Reubel wrote: > > Hello my name is Michael Reubel. I need some help with installing > RollDieDynamic on my system.I am taking an online course for python. And OK, We do not support RollDieDynamic and indeed have never heard of it. However we can try to help out with Python issues. In this case it seems that the problem is not Python related but to do with CMD.EXE on Windows. > - Extracted the zip files under Desktop. > - Found out that my zip file was stored in my OneDrive. > - I then proceeded to use cd Onedrive. > - Typed cd Desktop I?m not sure what you thought that did, but you basically moved into OneDrive then back out again. > - cd IntroToPythonMaster (that is how it is titled in my system). Do you have such a directory on your Desktop? > - cd examples and i get a message that reads the system cannot find the > path specified. Does it exist, you may find it easier using the File explorer tool in Windows. > > I've also searched on Youtube on how to create a Path and I didn't get much > help from that either. It sounds like you are not familiar with basic use of the command line tools in Windows. Anything involving programming (in Python or any other language) usually requires good skills at a command line. I?d suggest finding a tutorial on how to use the CMD.EXE command line to navigate and execute programs before you go any further. If there is a help forum for your package you may find they are better able to advise you since it doesn?t seem to be a Python issue as such, but a package install problem. HTH Alan G From wlfraed at ix.netcom.com Tue May 23 08:49:33 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 23 May 2023 08:49:33 -0400 Subject: [Tutor] Openpyxl References: Message-ID: On Mon, 22 May 2023 14:14:02 +0000, "Burke, Chelsea via Tutor" declaimed the following: >Good morning, > >I'm having issues with openpyxl, specifically the load_workbook function. It previously was working just fine, but I cannot get any workbook to load anymore using this function. Below is the error that keeps popping up every time I run it. Is there something wrong with the source code for this package? I've tried downgrading the versions from 3.1.2 to 3.1.1 and 3.1.0 and still have the same error. > >[cid:image001.png at 01D98C8D.BE4F5D90] > Binary attachments are stripped by the list software (I think I've seen ".txt" files get through, but not even a ".py" will pass). Presuming the script runs in a shell/cmd window, cut&paste the TEXT from the window -- NOT a screen grab. From wlfraed at ix.netcom.com Tue May 23 09:00:44 2023 From: wlfraed at ix.netcom.com (Dennis Lee Bieber) Date: Tue, 23 May 2023 09:00:44 -0400 Subject: [Tutor] RollDieDynamic References: <055E292F-8742-486E-9106-88AFB7DF984E@yahoo.co.uk> Message-ID: <9ldp6ihpullcu4av7naemeaurf7nk6ahhq@4ax.com> On Tue, 23 May 2023 12:18:13 +0100, Alan Gauld via Tutor declaimed the following: > > >Sent from my iPad > >> On 22 May 2023, at 19:18, Michael Reubel wrote: >> - Extracted the zip files under Desktop. >> - Found out that my zip file was stored in my OneDrive. >> - I then proceeded to use cd Onedrive. >> - Typed cd Desktop > >I?m not sure what you thought that did, but you basically moved into OneDrive then back out again. > No, they didn't... "Desktop" is one of the directories that gets linked into OneDrive (along with "Documents", "Photos", and a slew of other predefined Windows directories). >> - cd IntroToPythonMaster (that is how it is titled in my system). > >Do you have such a directory on your Desktop? > >> - cd examples and i get a message that reads the system cannot find the >> path specified. > That whole sequence should be the equivalent of: cd OneDrive\Desktop\IntroToPythonMaster\examples and should (due to the link in OneDrive) be equivalent to cd Desktop\IntroToPythonMaster\examples {That is, there should be -- if the OP is correct in the sequence -- an "IntroToPythonMaster" icon showing somewhere on their screen, as Desktop is where such items are stored} It would be much better if the OP were to cut&paste the actual text from the command shell window showing the sequence (and maybe perform a "DIR" command at the point the error occurs). * SideNote OneDrive is evil and should be killed (mine has been -- using group policy editor [Win10 PRO, not available on HOME]). As the name indicates, M$ OneDrive considers the /cloud/ to BE the primary drive, files are only stored locally for use when the system is not connected to the internet. It is NOT a "backup" scheme (the backup, as it were, is the local copy). From alan.gauld at yahoo.co.uk Sun May 28 18:16:33 2023 From: alan.gauld at yahoo.co.uk (Alan Gauld) Date: Sun, 28 May 2023 23:16:33 +0100 Subject: [Tutor] RollDieDynamic In-Reply-To: <9ldp6ihpullcu4av7naemeaurf7nk6ahhq@4ax.com> References: <055E292F-8742-486E-9106-88AFB7DF984E@yahoo.co.uk> <9ldp6ihpullcu4av7naemeaurf7nk6ahhq@4ax.com> Message-ID: On 23/05/2023 14:00, Dennis Lee Bieber wrote: > On Tue, 23 May 2023 12:18:13 +0100, Alan Gauld via Tutor >>> - I then proceeded to use cd Onedrive. >>> - Typed cd Desktop >> >> I?m not sure what you thought that did, but you basically moved into OneDrive then back out again. >> > No, they didn't... "Desktop" is one of the directories that gets linked > into OneDrive (along with "Documents", "Photos", and a slew of other > predefined Windows directories). Ah! My bad. Yes its stepping down into Desktop within Onedrive. Never having used oneDrive I got misdirected by the Desktop name. Apologies. -- Alan G Author of the Learn to Program web site http://www.alan-g.me.uk/ http://www.amazon.com/author/alan_gauld Follow my photo-blog on Flickr at: http://www.flickr.com/photos/alangauldphotos