[Tutor] SQL querying
Can I do SQL querying in Python? What packages do I need for that purpose? (specifically for mySQL) Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Getting started with Pandas
> You are not returning anything. > You need to use the return keyword otherwise your > function just generates the data internally then > throws it away again. ok, got it - thanks. my code below did not require a return statement, hence I was assuming it wouldn't be needed in my function either. import pandas as pd cities_lst = pd.read_table("cool_cities.csv") cities_lst.head() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Getting started with Pandas
import pandas as pd cities_lst = pd.read_table("cool_cities.csv") cities_lst.head() I was trying to rewrite the above as a function. Unlike my code above, my function below did not return the first 5 rows, but just nothing: def cities(file_name): import pandas as pd cities_lst = pd.read_table(file_name) cities_lst.head() cities("cool_cities.csv") Why does my function not return the first 5 rows? What's the mistake I am making here? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] understanding Python naming conventions & semantics
> A good thing to do but in some cases you have > to settle for "that's just the way Guido made it" :-) Thanks for the elaborate answer. That helps me a lot, as I see some similarities to natural languages: There is a clearly defined structure, but in some cases purely arbitrary decisions have been made (aka exceptions). After all, we're all humans, and we're not living in a perfect world. I naively believed, that in a programming language everything is perfectly well structured (Python is my first programming language). Knowing that this is not the case, makes my learning efforts much easier, as I can always check whether something is a rule or exception in the first place. If it's an exception, I have to memorize it, if it's a rule, I need to understand where it fits into the overall concept of Python. Another important distinction (for me) is that context matters. Such as, for example, that methods are functions associated with objects. (huh, reminds me a bit of Mandarin Chinese where context is (almost) everything) In the end, practice matters ;-) Thank you again! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] understanding Python naming conventions & semantics
I am trying to wrap my head around naming conventions & semantics in Python. Here are two code snippets, and below those two snippets are my questions: # code snippet 1 file_path = "C:\\Users\\...etl.csv" with open(file_path) as file_object: contents = file_object.read() contents_split = contents.split("\n") print(contents_split[:3]) ['Year,Week,Winner,Loser', '1966,1,Miami Dolphins,Oakland Raiders', '1966,1,Houston Oilers,Denver Broncos'] # code snippet 2 file_path = "C:\\Users\\...etl.csv" with open(file_path) as file_object: contents = list(file_object) print(contents[:3]) ['Year,Week,Winner,Loser\n', '1966,1,Miami Dolphins,Oakland Raiders\n', '1966,1,Houston Oilers,Denver Broncos\n'] Here are my questions: - List is a function, and read is a method, is that correct? - Semantic wise it would be always like function(something) and a method would be something.method() .. is that correct? - Assuming the above is correct, it seems that there is a tiny line between methods and functions? Why is something a method or a function? - For example, why is print a function and not a method? something.print() instead of print(something) Just trying to understand logic of Python and conventions, which will then make learning and memorizing things easier. Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there a better way to write my code?
> I wrote this code below > I was wondering if there is a shorter, more elegant way to accomplish this > task. > Thanks! thank you so much everyone! List comprehension is really cool. One thing I like about list comprehension is that you can get a dictionary, tuples or lists as a result by just changing the type of braces. # dictionary colors = ["red", "blue", "white", "yellow"] colors_len = [{color, len(color)} for color in colors] print(colors_len) # tuples colors = ["red", "blue", "white", "yellow"] colors_len = [(color, len(color)) for color in colors] print(colors_len) # lists colors = ["red", "blue", "white", "yellow"] colors_len = [[color, len(color)] for color in colors] print(colors_len) Can you shed some light on when to use which of the above data structures? I assume there is no simple answer to that question, I am still trying to understand the fundamentals of Python (which happens to be my first programming language). Thanks! > animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"] > > # step one: convert the animal list into a list of lists > > animals_lol = [] > > for animal in animals: > animal_split = animal.split(",") > animals_lol.append(animal_split) > > # step two: collect the length of each string in a separate list > > animals_len = [] > > for animal in animals: > animals_len.append(len(animal)) > > # step three: append the length of each string to the list of lists > > for a, b in enumerate(animals_lol): > b.append(animals_len[a]) > > print(animals_lol) > > [['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Is there a better way to write my code?
I wrote this code below which aims to concatenate strings with their respective string length. I was wondering if there is a shorter, more elegant way to accomplish this task. Thanks! animals = ["Dog", "Tiger", "SuperLion", "Cow", "Panda"] # step one: convert the animal list into a list of lists animals_lol = [] for animal in animals: animal_split = animal.split(",") animals_lol.append(animal_split) # step two: collect the length of each string in a separate list animals_len = [] for animal in animals: animals_len.append(len(animal)) # step three: append the length of each string to the list of lists for a, b in enumerate(animals_lol): b.append(animals_len[a]) print(animals_lol) [['Dog', 3], ['Tiger', 5], ['SuperLion', 9], ['Cow', 3], ['Panda', 5]] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to write a function which reads files
> You forgot the parentheses (), and are returning a reference to the > function instead of calling it and returning its result. Do this: > contents = file_object.read() oh, my bad. Thanks! > Also, consider using snake_case instead of PascalCase for your > function name, since the latter is typically used for classes, and > perhaps call it read_file to better describe it? thanks, I wasn't aware of the naming conventions for functions and classes. will bear that in mind! > Note that you used a different name here than in your > function definition! another typo. I made that in my original code already. Thanks, everything works well now! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] How to write a function which reads files
Hi there, I got this here: file_path = "C:\\Users\\...\\MyFile.txt" # path shortened for better readability with open(file_path) as file_object: contents = file_object.read() print(contents) It works. Now I want to convert the code above into a function. This is what I wrote: def FileReader(file_path): with open(file_path) as file_object: contents = file_object.read return contents print(FilePrinter("C:\\Users\\...\\MyFile.txt")) # path shortened for better readability I got this error message: How do I fix my function? Thanks, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Counting Items on a List associated w/ Index #
Hi there, I wrote a function which is supposed to count the number of items on each index #. For starters, here's a list I created to test the function: properties = ["mansion, modern, swimming_pool" , "mansion, historic, air_conditioning", "penthouse, modern, whirlpool"] # index 0 = property type # index 1 = style # index 2 = feature Here's the function: def feature_counter(input_lst, index, input_str): num_elt = 0 output_lst = [] for row in input_lst: split_row = row.split(",") output_lst.append(split_row) for each in output_lst: if each[index] == input_str: num_elt = num_elt + 1 return num_elt This function returns the correct result when checking index 0: print(feature_counter(properties, 0, "mansion")) >>> 2 Weirdly, it returns the wrong result when checking index 1: print(feature_counter(properties, 1, "modern")) >>> 0 and index 2: print(feature_counter(properties, 2, "swimming_pool")) >>> 0 Can anyone advise what's wrong with my function? Thanks, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Looping through Dictionaries
I wrote a function (shopping list) which calculates the total price of the purchase (quantity * price) as well as the stock change (stock - quantity). I know the latter is imperfect (my function does not take into account if items are out of stock for example, but that's my next challenge. The function does exactly what it's supposed to do: def shopping(quantity, price, stock): total = 0 for key in quantity: total += quantity[key] * price[key] stock_update = stock[key] - quantity[key] print(stock_update) print(total) quantity = { "bapple": 10, "banana": 20 } price = { "bapple": 5, "banana": 3 } stock = { "bapple": 20, "banana": 50 } shopping(quantity, price, stock) Now, I want to print the item next to the stock update, and I am receiving an error message. I couldn't figure out how to fix that: def shopping(quantity, price, stock): total = 0 for key, value in quantity.items(): total += quantity[value] * price[value] stock_update = stock[value] - quantity[value] print(key, stock_update) print(total) quantity = { "bapple": 10, "banana": 20 } price = { "bapple": 5, "banana": 3 } stock = { "bapple": 20, "banana": 30 } shopping(quantity, price, stock) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] urllib ... lost novice's question
>> Then, there is another package, along with a dozen other >> urllib-related packages (such as aiourllib). > > Again, where are you finding these? They are not in > the standard library. Have you been installing other > packages that may have their own versions maybe? they are all available via PyCharm EDU ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] urllib ... lost novice's question
Which package should I use to fetch and open an URL? I am using Python 3.5 and there are presently 4 versions: urllib2 urllib3 urllib4 urllib5 Common sense is telling me to use the latest version. Not sure if my common sense is fooling me here though ;-) Then, there is another package, along with a dozen other urllib-related packages (such as aiourllib). I thought this one is doing what I need: urllib.request The latter I found on http://docs.python-requests.org along with these encouraging words: "Warning: Recreational use of the Python standard library for HTTP may result in dangerous side-effects, including: security vulnerabilities, verbose code, reinventing the wheel, constantly reading documentation, depression, headaches, or even death." How do I know where to find the right package - on python.org or elsewhere? I found some code samples that show how to use urllib.request, now I am trying to understand why I should use urllib.request. Would it be also doable to do requests using urllib5 or any other version? Like 2 or 3? Just trying to understand. I am lost here. Feeback appreciated. Thank you! BTW, here's some (working) exemplary code I have been using for educational purposes: import urllib.request from bs4 import BeautifulSoup theurl = "https://twitter.com/rafaelknuth"; thepage = urllib.request.urlopen(theurl) soup = BeautifulSoup(thepage, "html.parser") print(soup.title.text) i = 1 for tweets in soup.findAll("div",{"class":"content"}): print(i) print(tweets.find("p").text) i = i + 1 I am assuming there are different solutions for fetching and open URLs? Or is the above the only viable solution? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] General question rgrd. usage of libraries
Hi there, I just recently learned how to build a basic web scraper with Python 3.5 (I am learning Python for data analytics purposes). Being new to coding, I have a question: How do I know which libraries I need to perform a certain task? For example, in case of this web scraper (which I built with help of a tutorial on YouTube) I need to have urrlib and Beautiful Soup import urllib import urllib.request from bs4 import BeautifulSoup theurl = "https://twitter.com/rafaelknuth"; thepage = urllib.request.urlopen(theurl) soup = BeautifulSoup(thepage, "html.parser") print(soup.title.text) i = 1 for tweets in soup.findAll("div",{"class":"content"}): print(i) print(tweets.find("p").text) i = i + 1 Is there a way I can figure out which libraries I need when drafting my code? Can you share your experiences? Right now, if I wanted for example to populate a Google Sheet with my scraped web content - how would I know which libraries I would need to actually make this happen? I am trying wondering if there is a process to figure out what I exactly need library-wise. Thank you, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Working with APIs - understanding the basics (Python 3.5)
can anyone recommend good resources? I am primarily in search of simple, clean code examples & practical usecases (Google APIs for example). Thanks. Right now, I am learning at Codecademy, Dataquest.io, Datacamp and from "Python Crash Course" by Eric Matthews. I am new to programming, Python is my first language. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Visual Studio Community 2017
> PyCharm :) I dumped VS 2017, after testing several IDEs I am perfectly happy with PyCharm EDU :) It comes with Python 3.5 and importing & working with libraries like matplotlib is really, really easy. PyCharm EDU is a very nice IDE for me as a student ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Visual Studio Community 2017
I wanted to start my first project using matplotlib (I have never worked with libraries before). I am trying to get started with VS Community 2017, and I am having trouble performing the most basic tasks such as installing matplotlib. Anyone here using VS 2017? Or, can anyone recommend an alternative to VS for Windows? Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] understanding code testing
can anyone point me to good learning resources on this subject? (python 3) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating .json files
> You need to open the file to create it: Ok, got you. Thanks, Alan! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] creating .json files
Is there a way to split these two into separate steps: a) creating a .json file b) manipulating it (a, r, w ...) Example: "import json number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] file_name = "my_numbers.json" with open(file_name, "w") as a: json.dump(number_list, a) What if I just wanted to create a .json file and do nothing with it? import json file_name = "my_numbers.json" The above does not do the job. What am I getting wrong here? Thanks. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Count for loops
>>> b = "3"+b[2:] #Removing the decimal point so that there are digits only in >> >> my_number = 3.14159 > > Here you assign a floating point number to mmy_number but > the code Sama wrote was for working with strings read > from a text file. > > You would need to convert it first: > > my_number = str(3.14159) > >> my_number = "3"+my_number[2:] >> print(my_number) Thanks for the clarification. I tested this approach, and I noticed one weird thing: Pi_Number = str(3.14159265358979323846264338327950288419716939) Pi_Number = "3" + Pi_Number[2:] print(Pi_Number) == RESTART: C:\Users\Rafael\Documents\01 - BIZ\CODING\Python Code\PPC_56.py == 3141592653589793 >>> How come that not the entire string is being printed, but only the first 16 digits? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Count for loops
Dear Sama, thank you so much for your explanation and sorry to bother you on the same subject again. I learn the most by taking code apart line by line, putting it together, taking apart again, modifying it slightly ... which is exactly what I did with your code. On Tue, Apr 4, 2017 at 3:20 PM, D.V.N.Sarma డి.వి.ఎన్.శర్మ wrote: > b = "3"+b[2:] #Removing the decimal point so that there are digits only in my_number = 3.14159 my_number = "3"+my_number[2:] print(my_number) This is the error code I got: == RESTART: C:/Users/Rafael/Documents/01 - BIZ/CODING/Python Code/PPC_56.py == Traceback (most recent call last): File "C:/Users/Rafael/Documents/01 - BIZ/CODING/Python Code/PPC_56.py", line 2, in my_number = "1"+my_number[2:] TypeError: 'float' object is not subscriptable >>> I am really trying to understand how to modify strings, floats and variables from different sources. In case of a text file, your code works, but if I apply the same to a float assigned to a variable, it does not work. What am I doing wrong here? Thank you so much for your patience. > the file > n = len(b) > for i in range(n-3): > if b[i:i+4] == get_year: # Taking 4 digit long chunks from successive > positions in b and seeing whether they are equal to get_year > count += 1 # If they are equal increase the count by 1 > > regards, > Sarma. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Count for loops
Sarma: thank you so much, I checked your code, it works. However, can you enlighten me what it exactly does? I do not understand it (yet). Thank you in advance. file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt" with open (file_path) as a: b = a.read() get_year = input("What year were you born? ") count = 0 b = "3"+b[2:] n = len(b) for i in range(n-3): if b[i:i+4] == get_year: count += 1 print("Your birth date occurs %s times in PI!" % (count)) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Count for loops
I wrote a program which checks if PI (first one million digits) contains a person's birth year. file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt" with open (file_path) as a: b = a.read() get_year = input("What year were you born? ") for year in b: if get_year in b: print("Your year of birth occurs in PI!") break else: print("Your year of birth does not occur in PI.") break As a next challenge, I wanted to check how often a person's birth year occurs in PI. Unfortunately, I wasn't able to figure out how to use the loop count properly. Can anyone help? Thanks! file_path = "C:/Users/Rafael/PythonCode/PiDigits.txt" with open(file_path) as a: b = a.read() get_year = input("What year were you born? ") count = 0 for year in b: if get_year in b: count += 1 else: print("Your birth date does not occur in PI.") break sum_count = sum(count) print("Your birth date occurs %s times in PI!" % (sum_count)) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] reading files in Python 3
I can read files like this (relative path): with open("Testfile_B.txt") as file_object: contents = file_object.read() print(contents) But how do I read files if I want to specify the location (absolute path): file_path = "C:\Users\Rafael\Testfile.txt" with open(file_path) as file_object: contents = file_object.read() print(contents) The above does not work ... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] super constructor usage
>> > I am trying to wrap my head around the super constructor. Is it possible to embed a super constructor into an if / elif statement within the child class? if message == "string A": return X elif: return Y How should I modify my code below? (I couldn't solve that by myself) class A: def __init__(self, message): self.message = message print(message) class B(A): def __init__(self, message): print("This is the message from your parent class A:") super(B, self).__init__(message) B("BlaBla") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] super constructor usage
I am trying to wrap my head around the super constructor. Simple example: class A: def __init__(self): print("world") class B(A): def __init__(self): print("hello") super(B, self).__init__() B() Then I changed the parent class A like this, as I wanted to test how the code would look like if I passed arguments: class A: def __init__(self, message): self.message = message print(message) I then modified the child class B like this: class B(A): def __init__(self, message): print("This is the message from your parent class A:") super(B, self).__init__(message) B("BlaBla") That works, however I am not sure about what exactly happens inside the code. What I am concerned about is whether the argument is being actually inherited from the parent class A or does B overwrite the argument. Can anyone advise what the correct solution would be (in case mine is wrong). Thank you. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] FUNCTIONS vs. CLASSES (early beginner questions)
Question: When should I use functions? When should I use classes? I wrote my program twice: as a function and as a class (I did so for educational purposes, to better understand both concepts). Both programs do exactly the same, and the work neatly. Can you advise when I should use functions and when it's appropriate to make use of classes? Any feedback rgrd. my code? Anything I can improve? Thanks! # FUNCTION def ManageFood(): shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": shopping_list.append(food) food = input(prompt) print("These are your foods on your shopping list: %s." % ", ".join(shopping_list)) eat_food = [] store_food = [] for food in shopping_list: print("You bought: %s. " % (food)) prompt = input("What would you like to do with it?\nEnter 'eat' or 'store'. ") if prompt == "eat": eat_food.append(food) elif prompt == "store": store_food.append(food) print("Food for instant consupmtion: %s." % ", " .join(eat_food)) print("Food for storage: %s." % ", " .join(store_food)) ManageFood() # CLASS class FoodManager: def __init__(self): self.shopping_list = [] self.user_input = ("Which foods would you like to purchase?\nEnter 'quit' to exit? ") self.eat_food = [] self.store_food = [] self.user_choice = ("What would you like to do with it?\nEnter 'eat' or 'store'. ") def purchase_food(self): get_food = input(self.user_input) while get_food != "quit": self.shopping_list.append(get_food) get_food = input(self.user_input) print("These are your foods on your shopping list: %s." % ", ".join(self.shopping_list)) def manage_food(self): for item in self.shopping_list: print("You bought: %s. " % (item)) eat_or_store = input(self.user_choice) if eat_or_store == "eat": self.eat_food.append(item) elif eat_or_store == "store": self.store_food.append(item) print("Food for instant consumption: %s." % ", ".join(self.eat_food)) print("Food for storage: %s." % ", ".join(self.store_food)) if __name__ == "__main__": my_food = FoodManager() my_food.purchase_food() my_food.manage_food() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using Class Properly - early beginner question
thanks for your feedback! @boB I wrote a function that does exactly what I want, and that is: Create a shopping list and then let the user decide which items (food) are supposed to be instantly consumed and which ones stored. def ManageFood(): create_shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": create_shopping_list.append(food) food = input(prompt) print("These are your foods on your shopping list: %s." % ", " .join(create_shopping_list)) eat_food = [] store_food = [] for food in create_shopping_list: print("You bought this item: %s. " % (food)) prompt = input("What would you like to do with it?\nEnter 'eat' or 'store'. ") if prompt == "eat": eat_food.append(food) elif prompt == "store": store_food.append(food) print("Food you want to eat now: %s." % ", " .join(eat_food)) print("Food you want to store: %s." % ", " .join(store_food)) ManageFood() PS: Please let me know if you have any suggestions how to write my code above in a shorter, more elegant fashion (it does what it's supposed to do, but not sure if a pro would write it same way I did). Besides that, I want to take it a step further and rewrite the function above as a class, and I don't know how exactly how to do this. (coding newbie pains ... I just learned the basics about classes in Python, but nowhere could I find examples of how to properly initialize classes, given that it operates solely with user input - same goes with with calling that class properly). Here's how far I got on my own: class FoodShopping(object): def __init__ (self, create_shoppping_list, prompt, food, eat_food, store_food): self.create_shopping_list = create_shopping_list self.prompt = prompt self.food = food self.eat_food = eat_food self.store_food = store_food def ManageFood(self, create_shopping_list, prompt, food, eat_food, store_food): create_shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": create_shopping_list.append(food) food = input(prompt) print("These are your foods on your shopping list: %s." % ", " .join(create_shopping_list)) eat_food = [] store_food = [] for food in create_shopping_list: print("You bought this item: %s. " % (food)) prompt = input("What would you like to do with it?\nEnter 'eat' or 'store'. ") if prompt == "eat": eat_food.append(food) elif prompt == "store": store_food.append(food) print("Food you want to eat now: %s." % (eat_food)) print("Food you want to store: %s." % (store_food)) FoodShopping() That's the error message I get when executing my code: Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_29.py == Traceback (most recent call last): File "C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_29.py", line 140, in FoodShopping() TypeError: __init__() missing 5 required positional arguments: 'create_shoppping_list', 'prompt', 'food', 'eat_food', and 'store_food' >>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Using Class Properly - early beginner question
I am trying to write a food shopping list. The user should be able to add items to that shopping list, and later on decide what should happen to those purchased foods: instantly consumed or stored. My initial idea was to create a parent class to populate the shopping list and a child class to manage the purchased items as described above. While writing the parent class, I ran into the following issue: How do I properly declare a variable that takes user input? Do I write methods in the same fashion like in a regular function? And how do I call that class properly? This is what I came up with: class BuyFoods(object): def __init__(self, outlet): self.outlet = outlet def CreateShoppingList(self, shopping_list, prompt, food): self.shopping_list = shopping_list self.prompt = prompt self.food = food shopping_list = [] prompt = ("Which foods would you like to purchase?\nEnter 'quit' to exit. ") food = input(prompt) while food != "quit": shopping_list.append(food) food = input(prompt) print("You just purchased these foods: %s." % ", ".join(shopping_list)) Tesco = BuyFoods("Tesco") Tesco.CreateShoppingList() That's the error message I get: Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> == RESTART: C:\Users\Rafael\Documents\01 - BIZ\PYTHON\Python Code\PPC_28.py == Traceback (most recent call last): File "C:\Users\Rafael\Documents\01 - BIZ\PYTHON\Python Code\PPC_28.py", line 136, in Tesco.CreateShoppingList() TypeError: CreateShoppingList() missing 3 required positional arguments: 'shopping_list', 'prompt', and 'food' >>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] tiny, little issue with list
LogActivities = [] prompt = ("What have you done today? ") prompt += ("Enter 'quit' to exit. ") while True: activity = input(prompt) LogActivities.append(activity) if activity == "quit": print("Let me recap. This is what you've done today: %s." % ", " .join(LogActivities)) This program is supposed to take user input and to log his activities into a list. All works well, only when the user quits, the program adds 'quit' to LogActivities. How do I prevent my program from doing this? Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> = RESTART: C:/Users/Rafael/Documents/01 - BIZ/PYTHON/Python Code/PPC_159.py = What have you done today? Enter 'quit' to exit. shower What have you done today? Enter 'quit' to exit. walk the dog What have you done today? Enter 'quit' to exit. drink coffee What have you done today? Enter 'quit' to exit. prepare lunch What have you done today? Enter 'quit' to exit. take coding lesson What have you done today? Enter 'quit' to exit. quit Let me recap. This is what you've done today: shower, walk the dog, drink coffee, prepare lunch, take coding lesson, quit. What have you done today? Enter 'quit' to exit. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] printing items form list
I want to print individual items from a list like this: You have a book, towel, shirt, pants in your luggage. This is my code: suitcase = ["book", "towel", "shirt", "pants"] print ("You have a %s in your luggage." % suitcase) Instead of printing out the items on the list, my code appends the list to the string. How do I need to modify my code? == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_7.py == You have a ['book', 'towel', 'shirt', 'pants'] in your luggage. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] looping - beginner question
I wrote a program that is supposed to take orders from customers in a bar. If the desired drink is available, the customer will be served. If not, he will be informed that the drink is not available. This is what I wrote: bar = ["beer", "coke", "wine"] customer_order = input("What would you like to drink, dear guest? ") for drink in bar: if customer_order != drink: print ("Sorry, we don't serve %s." % customer_order) else: print ("Sure, your %s will be served in a minute!" % customer_order) What I want the program to do is to "silently" loop through the list of drinks and to print the correct answer. Instead, it loops through each item on the list like this: >>> == RESTART: C:/Users/Rafael/Documents/01 - BIZ/Python/Python Code/PPC_4.py == What would you like to drink, dear guest? coke Sorry, we don't serve coke. Sure, your coke will be served in a minute! Sorry, we don't serve coke. >>> ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] counting number of loops
I want to compare two strings and count the number of identical letters: stringB = "ABCD" stringA = "AABBCCDDEE" for b in stringB: if b in stringA: r = 0 r += 1 print (r) How do I count the output (r) instead of printing it out? (result should be 4). Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Class Inheritance
Hey there, I am trying to wrap my head around Class Inheritance in Python, and I wrote a little program which is supposed to calculate revenues from customers who don't get a discount (parent class) and those who get a 30% discount (child class): class FullPriceCustomer(object): def __init__(self, customer, rate, hours): self.customer = customer self.rate = rate self.hours = hours print ("Your customer %s made you %s USD this year." % (customer, rate * hours)) class DiscountCustomer(FullPriceCustomer): discount = 0.7 def calculate_discount(self, rate, hours): print ("Your customer %s made you %s USD at a 30% discount rate this year." % (self.customer, self.rate * rate * discount)) customer_one = DiscountCustomer("Customer A", 75, 100) customer_two = FullPriceCustomer("Customer B", 75, 100) The DiscountCustomer class instance gets me the wrong result (it does not calculate the discount) and I was not able to figure out what I did wrong here. Can anyone help? Thanks! All the best, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Split Method
Hey there, I am having some issues with splitting strings. I already know how to split strings that are separated through empty spaces: def SplitMyStrings(): Colors = "red blue green white black".split() return (Colors) print(SplitMyStrings()) >>> ['red', 'blue', 'green', 'white', 'black'] ... however I couldn't figure out how to split each character into a list item. This is what I want to get as a result: >>> ['r', 'e', 'd', 'b', 'l', 'u', 'e', 'g', 'r', 'e', 'e', 'n', 'w', 'h', 'i', 't', 'e', 'b', 'l', 'a', 'c', 'k'] I am using Python 3.3.0 Thanks in advance! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python & Django
Hej there, I am very interested to hear your opinion on which version of Python to use in conjunction with Django. Currently, I am taking a class at Udemy and they recommend using Python 2.7 with Django 1.6. because both versions work well with each other. Over the last few months I got pretty much used to Python 3.3.0 which some of you guys recommended to me on this mailing list. Hence, I would prefer to keep using Python 3x but I am not sure if that's a good idea. I heard of a couple folks using Python 3.3.0 with Django 1.6 that they ran into issues, and most of them switched back to Python 2.7. Your thoughts? Thanks in advance! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Activating virtualenv in Windows
Hej guys, does anyone know how to activate virtualenv in Windows? In Terminal it's: source bin/activate Couldn't find the corresponding command for Windows that actually worked. Any ideas? Thanks! Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
>>> Look at this line: >>> >>> > if __name__ == " __main__": >>> >> >> do so very closely :) > > In monospaced font :) > > Took me forever to see it, thanks Gmail... Ok ... found it ;-) Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
I just wrote a unittest for this function here: def PositiveCalculator(*summands): if all(x > 0 for x in summands): return sum(summands) else: raise ValueError("negative value") Here's the test (I want to test whether the function works if the user enters floats instead of integers) : import unittest from all_any import PositiveCalculator class TestCalculator(unittest.TestCase): def test_floats(self): self.assertTrue(PositiveCalculator(3.45, 54.3, 5.62)) if __name__ == " __main__": unittest.main() For some reason the test runs through without giving me any output, and I was wondering what I am doing wrong here? Raf On Tue, Dec 17, 2013 at 4:56 PM, Rafael Knuth wrote: >>> def check_values(a, b): >>> if all(number >= 0 for number in range(a, b)): >>> return True >>> else: >>> raise ValueError("negative number") >>> >>> And: >>> def PositiveCalculator(a, b): >>> if a > 0 and b > 0: >>> return a + b >>> else: >>> raise ValueError("negative number") >> >> >> So zero is now considered a negative number? > > Thanks ;-) > if a >= 0 and b >= 0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
>> def check_values(a, b): >> if all(number >= 0 for number in range(a, b)): >> return True >> else: >> raise ValueError("negative number") >> >> And: >> def PositiveCalculator(a, b): >> if a > 0 and b > 0: >> return a + b >> else: >> raise ValueError("negative number") > > > So zero is now considered a negative number? Thanks ;-) if a >= 0 and b >= 0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
> BUT: this really doesn't make much sense! Your if construct is a lot more > readable than what any or all would give you in this example. > As pointed out repeatedly here, you can always replace any() and all() with > a combination of for and if, it's really a question of readability (and > style) what you choose. Got it. I just wanted to make sure I get a better understanding of how to use any() and all() even though I already had a solution at hand. So far, I worked through 24 out of 68 built-in functions, and I guess I will have a few more questions along the way ;-) Thank you all again! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
got it! Thanks, Peter On Tue, Dec 17, 2013 at 4:27 PM, Peter Otten <__pete...@web.de> wrote: > Rafael Knuth wrote: > >> Hej there, >> >>> I use any() and all() frequently. For example, suppose you have a >>> function that takes a list of numbers, and they are all supposed to be >>> positive. >>> >>> def calculate_values(numbers): >>> if all(number > 0 for number in numbers): >>> # do the calculation >>> else: >>> raise ValueError("negative or zero number found") >>> >>> That could be re-written as: >>> >>> def calculate_values(numbers): >>> if any(number <= 0 for number in numbers): >>> raise ValueError("negative or zero number found") >>> else: >>> # do the calculation >> >> Got it. I played with the examples above, I wrote wrote two functions >> and they work nicely. >> I understand now why it makes sense to use all() and any(): >> >> def check_values(a, b): >> if all(number >= 0 for number in range(a, b)): >> return True >> else: >> raise ValueError("negative number") >> >> And: >> >> def check_values(a, b): >> if any(number >= 0 for number in range(a, b)): >> return True >> else: >> raise ValueError("negative number") >> >> But what if I have to check multiple values within one function? I am >> able to get the task done with a plain vanilla if statement. In the >> exemplary function below the user is expected to enter only positive >> numbers and in case he provides a negative number, a ValueError is >> raised: >> >> def PositiveCalculator(a, b): >> if a > 0 and b > 0: >> return a + b >> else: >> raise ValueError("negative number") >> >> In this function one negative number is tolerated: >> >> def PositiveCalculator(a, b): >> if a > 0 or b > 0: >> return a + b >> else: >> raise ValueError("negative number") >> >> How would I have to modify these two functions if I wanted to use the >> all( ) or any() function respectively? > > The first one could become > > def positive_calulator(a, b): > summands = a, b > if all(x > 0 for x in summands): > return sum(summands) > raise ValueError("negative argument encountered") > > You can make that work with and arbitrary number of arguments (and save a > line of code): > > def positive_calculator(*summands): > if all(x > 0 for x in summands): > return sum(summands) > raise ValueError("negative argument encountered") > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Built In Functions
Hej there, > I use any() and all() frequently. For example, suppose you have a > function that takes a list of numbers, and they are all supposed to be > positive. > > def calculate_values(numbers): > if all(number > 0 for number in numbers): > # do the calculation > else: > raise ValueError("negative or zero number found") > > That could be re-written as: > > def calculate_values(numbers): > if any(number <= 0 for number in numbers): > raise ValueError("negative or zero number found") > else: > # do the calculation Got it. I played with the examples above, I wrote wrote two functions and they work nicely. I understand now why it makes sense to use all() and any(): def check_values(a, b): if all(number >= 0 for number in range(a, b)): return True else: raise ValueError("negative number") And: def check_values(a, b): if any(number >= 0 for number in range(a, b)): return True else: raise ValueError("negative number") But what if I have to check multiple values within one function? I am able to get the task done with a plain vanilla if statement. In the exemplary function below the user is expected to enter only positive numbers and in case he provides a negative number, a ValueError is raised: def PositiveCalculator(a, b): if a > 0 and b > 0: return a + b else: raise ValueError("negative number") In this function one negative number is tolerated: def PositiveCalculator(a, b): if a > 0 or b > 0: return a + b else: raise ValueError("negative number") How would I have to modify these two functions if I wanted to use the all( ) or any() function respectively? Thanks in advance! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Built In Functions
Hey there, I am currently looking into all built in functions in Python 3.3.0, one by one, in order to understand what each of them specifically does (I am familiar with some of them already, but most built in functions are still alien to me). I am working with the Python documentation http://docs.python.org/3/library/functions.html#all but not all examples are clear & self explaining to me as a novice to programming. First question: all(iterable) and any(iterable) - can you give me one or two examples what these functions do and how they are specifically used? Thank you! Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Prime Numbers
Hej there, >> number = 9 >> for element in range(2,9): >> 3 % 2 != 0: >> My assumption is that the program should end the loop after the first >> iteration again and it then should return True. > > No. If it did that, it wouldn't be a *loop* at all, would it? The whole > reason loops (for and while) exist is to run the code repeatedly. If > they only ran once, no matter what, they would be useless. > > Unless you exit a loop early (with a return, a break, or by raising an > exception) the loop will jump back to the beginning until such time as > the loop is completed. Then it will jump to the code following the loop. > > So, here's a simple example: > > for element in range(5): > print(element) > > With your assumption, you might think it will print 0, then stop. But > it doesn't. It prints 0, then 1, then 2, then 3, then 4. Each time > through the loop it jumps back to the beginning, gets the next value > from the range, and only when there are no more values to get does the > for-loop finish. That's actually a good example. Let me explain what I feel confused about. Print actually runs through the entire loop. But let's change the program like this: def RangeOfNumbers (n): for i in range(n): return i print(RangeOfNumbers(5)) When you run this program, your result is: >>> 0 So, return only returns the first value within the loop. If you want the loop run over the entire range of values, you have to change it like this: def RangeOfNumbers (n): List = [] for i in range(n): List.append(i) return List print(RangeOfNumbers(5)) >>> [0, 1, 2, 3, 4] Let's get back to my original program: def is_prime(number): for element in range(2, number): if number % element == 0: return False return True I was assuming that the for loop ends after the first round, just like in my first example above. But as you explained the for loop iterates through the entire range and only stops if a. there are no more values left to iterate through or b. the condition is met (return False if number % element == 0). That's the tiny little detail I am confused about: What does return exactly do? Does it return only the first value within a loop or does it iterate through all values within a loop? (unless a given condition is met) Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Prime Numbers
Hej, I stumbled upon this program here (Python 3.3.0) and I don't quite understand how the for loop plays with the return True statement: def is_prime(number): for element in range(2, number): if number % element == 0: return False return True Now, I would expect the following in case I call the function with the variable 3: number = 3 for element in range(2, 3): 3 % 2 != 0: Loop ends and program returns True. Let's do the same with the variable 9: number = 9 for element in range(2,9): 3 % 2 != 0: My assumption is that the program should end the loop after the first iteration again and it then should return True. But instead, the program returns False (correctly for obvious reasons because 9 is not a prime number). Can anyone help me understand what error in reasoning I am making here? Thanks! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
Hej Steven, thanks for the clarification. I have two questions - one about map function and the other about return. > So, in mathematics we might have a mapping between (let's say) counting > numbers 1, 2, 3, 4, ... and the even numbers larger than fifty, 52, 54, > 56, ... and so on. The mapping function is 50 + 2*x: > > x = 1 --> 50 + 2*1 = 52 > x = 2 --> 50 + 2*2 = 54 > x = 3 --> 50 + 2*3 = 56 > x = 4 --> 50 + 2*4 = 58 > > and so on, where we might read the arrow --> as "maps to". > > So the fundamental idea is that we take a series of elements (in the > above case, 1, 2, 3, ...) and a function, apply the function to each > element in turn, and get back a series of transformed elements (52, 54, > 56, ...) as the result. > > So in Python, we can do this with map. First we define a function to do > the transformation, then pass it to map: > > def transform(n): > return 50 + 2*n > > result = map(transform, [1, 2, 3, 4]) #1 Question In which cases should I use a map function instead of a for loop like this for example: def transform(n, m): for i in range (n, m): print (50 + 2*i) transform(1,5) >>> 52 54 56 58 > A thought comes to mind... an very important lesson is to learn the > difference between return and print, and to prefer return. > > You have written a function that calculates the digit sum. But it is not > *reusable* in other functions, since it cannot do anything but *print* > the digit sum. What if you want to store the result in a variable, and > print it later? Or print it twice? Or put it in a list? Or add one to > it? You're screwed, the function is no use to you at all. #2 Question Strangely, I get entirely different results depending on whether I use return or print within a function. Example: def transform(n, m): for i in range (n, m): print (50 + 2*i) transform(1,5) >>> 52 54 56 58 Versus: def transform(n, m): for i in range(n, m): return (50 + 2*i) print(transform(1,5)) >>> 52 Why do I get entirely different results in each case? &: How do I prevent my loop from breaking after the first round when using return instead of print? All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
Hej there, > I don't know if everyone would consider this more elegant but it's > certainly shorter: Thanks! def DigitSum(YourNumber): > ... return sum(map(int, YourNumber)) > ... DigitSum('55') > 10 I don't understand yet what the "map" function does - can you explain? I read the Python 3.3.0 documentation on that topic but I frankly didn't really understand it http://docs.python.org/3/library/functions.html#map. My search for simple code examples using "map" wasn't really fruitful either. Other than that, I went through each of the 7 alternatives to my "Integer to Digit Sum" program you guys sent me, I understand what each of those programs does. My favorite one is: def DigSum (integer): s = 0 while integer != 0: integer, remainder = divmod(integer, 10) s += remainder print(s) DigSum(537) It's really a beautiful, elegant solution IMHO and way better than my original code (convert int to string, store each digit in an empty list, then convert them back to int and sum them). Again, thank you all! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
>> Tu sum it up (aha!): you algorithm is the right and only one > > No, it's not the only one. It's certainly the most obvious one, but there is > also the pure numbers approach pointed out by me and Alan. So far I received 7 different alternative suggestions, both pure numbers & mixed int/str approach, which is great because I learn far more than I would expect given that the subject discussed is a tiny, little string to digit sum program. I play around with each piece of code I receive, I take notes and I memorize as much as possible for upcoming challenges. Although it's sometimes confusing to me as a novice to programming, I actually like the idea that one and the same task can be solved in different ways in Python (it spurs my creativity). And, again: Thank you all for your elaborate and extremely helpful responses! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Converting integers into digit sum (Python 3.3.0)
Thanks, guys - got it! I was suspecting that my solution is too complex and that there must be a simpler way to convert integers into a digit sum. Have a great morning/day/evening, Raf On Mon, Dec 9, 2013 at 9:23 AM, Amit Saha wrote: > On Mon, Dec 9, 2013 at 6:08 PM, Rafael Knuth wrote: >> Hej there, >> >> I wrote a program that converts an integer into a digit sum: >> >> def DigitSum(YourNumber): >> DigitList = [] >> YourNumber = str(YourNumber) >> for i in YourNumber: >> DigitList.append(int(i)) >> print(sum(DigitList)) >> >> DigitSum(55) >> >>>>> >> 10 >> >> It actually works but I was wondering if that's the only way to solve >> the task of converting an integer into a digit sum? I learned from >> past conversations on this mailing list that often times there is a >> better, more elegant and shorter way to write a program, and I was >> wondering if that's the case here. > >>>> sum([int(digit) for digit in str(55)]) > 10 > > That's using list comprehensions. Since a string is basically a > sequence, you can do the above. > > Best, > Amit. > > -- > http://echorand.me ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Converting integers into digit sum (Python 3.3.0)
Hej there, I wrote a program that converts an integer into a digit sum: def DigitSum(YourNumber): DigitList = [] YourNumber = str(YourNumber) for i in YourNumber: DigitList.append(int(i)) print(sum(DigitList)) DigitSum(55) >>> 10 It actually works but I was wondering if that's the only way to solve the task of converting an integer into a digit sum? I learned from past conversations on this mailing list that often times there is a better, more elegant and shorter way to write a program, and I was wondering if that's the case here. Thanks! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Unit testing in Python (3.3.0) for beginners
Hey there, I struggle to understand what unit testing specifically means in practice and how to actually write unit tests for my code (my gut is telling me that it's a fairly important concept to understand). Over the last few days I learned how to write and work with classes, I learned quite a lot about functions, nested loops and I currently walk through every program in the Python.org wiki "Simple Programs" https://wiki.python.org/moin/SimplePrograms ... and here's the unit test program they provide: import unittest def median(pool): copy = sorted(pool) size = len(copy) if size % 2 == 1: return copy[(size - 1) / 2] else: return (copy[size/2 - 1] + copy[size/2]) / 2 class TestMedian(unittest.TestCase): def testMedian(self): self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7) if __name__ == '__main__': unittest.main() Also, I went through the "Beginning Test-Driven Development in Python" http://net.tutsplus.com/tutorials/python-tutorials/test-driven-development-in-python/ but I have to admit I still don't fully understand how unit tests work in practice and how to write my own unit tests. As it turned out over the last few weeks, the best modus operandi for me as an absolute beginner is to grab a small program, take it apart in the first place, understand how each component works through trial & error, then put all those pieces together and then I kind of get the big picture. Once I "get it" I practice as much as possible to memorize what I just learned and *then* I start readying as many blogs, tutorials etc. as possible to deepen my understanding (I frankly find most tutorials & blogs too complex and confusing from a beginner's viewpoint, and I learn faster by taking code apart and learning through trial & error in the first place). So, what I am specifically searching for is a very simple code sample which I can take apart and iterate through each component, and I was wondering if you are aware of resources that might be helpful? My understanding of unit testing is that I have to embed my code into a test and then I have to define conditions under which my code is supposed to fail and pass. Is that assumption correct? I am a bit lost & confused here .. any help & hing is highly appreciated! Thank you & all the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner's question: Looping through variable & list simultaneously
> We've already established that you've an "off by one" error in the year, but > let's do a closer analysis of your code and mine. Ok, got it - thank you for the clarification Mark. No more questions for today, I learned a lot - thank you all! :-) All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner's question: Looping through variable & list simultaneously
> for x, country in zip ( range (2009,2014), PopularCountries): > print (x, country) > > And yes, Rafael, you can zip together any number of iterators this way. > > -- > DaveA Thanks Dave. Got it! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner's question: Looping through variable & list simultaneously
Hej there, > That's very poor coding, if you're given a function that does exactly what > you want, why rewrite it and worse still, get it wrong? I don't quite understand. I took that advice, tried it - it worked, and then I figured out there's also another way to get there. The output from the "for Country in range(len(PopularCountries))" is exactly the same as with "enumerate", or am I missing something here? >> PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"] >> Year = 2009 >> Backpackers = 100 >> for Country in range(len(PopularCountries)): >> Year += 1 >> Backpackers = Backpackers*1.15 >> print("In %d there were %d backpackers worldwide and their most >> popular country was %s." % (Year, Backpackers, >> PopularCountries[Country])) >> > >> In 2010 there were 115 backpackers worldwide and their most >> popular country was Brazil. > > > Whoops, what happened to 2009? Typo ;-) >> In 2011 there were 1322500 backpackers worldwide and their most >> popular country was China. >> In 2012 there were 1520874 backpackers worldwide and their most >> popular country was France. >> In 2013 there were 1749006 backpackers worldwide and their most >> popular country was India. >> In 2014 there were 2011357 backpackers worldwide and their most >> popular country was Vietnam. >> >> I will now try to further enhance my program by adding a second list >> to the loop. > > > What do you mean by "enhance", get the output correct or make it even worse? > :) Very funny. Couldn't stop laughing ;-) > So here's the code with enumerate. > > > PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"] > Backpackers = 100 > for x, PopularCountry in enumerate(PopularCountries, start=2009): > Backpackers = Backpackers*1.15 > print("In %d there were %d backpackers worldwide and their most popular > country was %s." % (x, Backpackers, PopularCountry)) > > In 2009 there were 115 backpackers worldwide and their most popular > country was Brazil. > In 2010 there were 1322500 backpackers worldwide and their most popular > country was China. > In 2011 there were 1520874 backpackers worldwide and their most popular > country was France. > In 2012 there were 1749006 backpackers worldwide and their most popular > country was India. > In 2013 there were 2011357 backpackers worldwide and their most popular > country was Vietnam. Thanks. Just one last question: Is there a way to loop through an arbitrary number of lists at the same time? Say, if I wanted to loop through the most popular travel guides in each year in addition to most popular country? I couldn't figure that out by myself. Would that be doable with "enumerate" as well? All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner's question: Looping through variable & list simultaneously
Hej there, > Loop around your list using the enumerate builtin function and an > appropriate value for start, see > http://docs.python.org/3/library/functions.html#enumerate thanks! That hint was very helpful, and I rewrote the program as follows (I learned how to enumerate just yesterday and I figured out you can do the same with a range(len(list)) ... so here's how I solved my issue: PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"] Year = 2009 Backpackers = 100 for Country in range(len(PopularCountries)): Year += 1 Backpackers = Backpackers*1.15 print("In %d there were %d backpackers worldwide and their most popular country was %s." % (Year, Backpackers, PopularCountries[Country])) >>> In 2010 there were 115 backpackers worldwide and their most popular country was Brazil. In 2011 there were 1322500 backpackers worldwide and their most popular country was China. In 2012 there were 1520874 backpackers worldwide and their most popular country was France. In 2013 there were 1749006 backpackers worldwide and their most popular country was India. In 2014 there were 2011357 backpackers worldwide and their most popular country was Vietnam. I will now try to further enhance my program by adding a second list to the loop. Again, thank you all! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Beginner's question: Looping through variable & list simultaneously
Hej there, I am writing a little throw away program in order to better understand how I can loop through a variable and a list at the same time. Here's what the program does and how it looks like: It counts the number of backpackers (assuming a growth rate of 15 % year on year) over the last five years: Backpackers = 100 for x in range(2009, 2014): Backpackers = Backpackers*1.15 print("In %d there were %d backpackers worldwide." % (x, Backpackers)) >>> In 2009 there were 115 backpackers worldwide. In 2010 there were 1322500 backpackers worldwide. In 2011 there were 1520874 backpackers worldwide. In 2012 there were 1749006 backpackers worldwide. In 2013 there were 2011357 backpackers worldwide. Now I want to enhance that program a bit by adding the most popular country in each year. Here's what I want to get as the output: >>> In 2009 there were 115 backpackers worldwide and their most popular country was Brazil. In 2010 there were 1322500 backpackers worldwide and their most popular country was China. In 2011 there were 1520874 backpackers worldwide and their most popular country was France. In 2012 there were 1749006 backpackers worldwide and their most popular country was India. In 2013 there were 2011357 backpackers worldwide and their most popular country was Vietnam. I assume that I need to have a list like this: PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"] But I struggle to modify the program above in a way that it loops properly through "Backpackers" and "PopularCountries". >From all my iterations there's only one that came at least halfway close to my desired result: PopularCountries = ["Brazil", "China", "France", "India", "Vietnam"] Backpackers = 100 for x in range(2009, 2014): Backpackers = Backpackers*1.15 PopularCountries = PopularCountries.pop() print("In %d there were %d backpackers worldwide and their most popular country was %s." % (x, Backpackers, PopularCountries)) It loops only once through "Backpackers" and "PopularCountries" (starting with the last item on the list though) and then it breaks: >>> In 2009 there were 115 backpackers worldwide and their most popular country was Vietnam. Traceback (most recent call last): File "C:/Users/Rafael_Knuth/Desktop/Python/Backpackers.py", line 6, in PopularCountries = PopularCountries.pop() AttributeError: 'str' object has no attribute 'pop' My questions: Is there a way to use pop() to iterate through the list in a correct order (starting on the left side instead on the right)? If not: What alternative would you suggest? Do I need to rewrite the program in order to iterate through "Backpackers" and "PopularCountries" at the same time? (for example using a while instead of a for loop?) Or is there a way to modify my existing program? Should "PopularCountries" be a list or do I need a dictionary here? I am using Python 3.3.0. Thank you in advance! All the best, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Nested for loops
> Do you understand how that works? Yep. It's crystal clear now. Thank you. It took a while till I got it, though ;-) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Nested for loops
Hej there, I am trying to figure out how exactly variables in nested loops are generated, and don't get it 100% right yet. Here's my code: for n in range(2, 10): for x in range(2, n): if n % x == 0: print(n, 'equals', x, '*', n//x) break else: print(n, 'is a prime number') And here's what I assume happens inside these for loops: #1 Round: n = 2 x = no result >>> 2 is a prime number #2 Round: n = 3 x = 2 >>> 3 is a prime number #3 Round: n = 4 x = 3 >>> My assumption about the way these two for loops work is wrong, because the output cannot be "4 is a prime number" for obvious reasons. Can anyone help me understand? I am using Python 3.3.0. Thank you! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ string input "for", "not", "while", "else" etc.
> Does German have anything similar? (I presume you are German.) Ich nehme mir die Freiheit. (present) Ich habe mir die Freiheit genommen. (past) And in Polish: Pozwalam sobie. (present) Pozwoliłem sobie. (past) ;-) Cheers, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ string input "for", "not", "while", "else" etc.
Thank you, Peter! On Wed, Nov 27, 2013 at 9:45 AM, Peter Otten <__pete...@web.de> wrote: > Rafael Knuth wrote: > >> simple issue I couldn't find a solution for: >> >> YourName = input(str("What is your name?")) >> print("Hello", YourName) >> >> When executing the program, in case the user input is "for", "not", >> "True", "while" Python interprets that as a command and changes the >> input's color to the corresponding command. The program runs without >> any further issues, but I was wondering: How can I make sure Python >> "understands" that the user input is nothing else but a string? I >> tried to fix that by changing input("What is your name?") to >> input(str("What is your name?)) but that didn't work. >> >> Thanks in advance, > > I took the freedom to report it myself: > > http://bugs.python.org/issue19808 > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ string input "for", "not", "while", "else" etc.
> OK, That's what you'd expect in 3.3 because raw_input is now input(). > > But in that case input() should not do anything with your input. > > Can you post a session showing the input and the odd behaviour? YourName = input(str("What is your name ?")) print("Hello", YourName) Exemplary input & output: Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. >>> RESTART >>> What is your name? for Hello for >>> Color of for is changed to orange on the input line ("What is your name?") Raf > > > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue w/ string input "for", "not", "while", "else" etc.
Hej there, simple issue I couldn't find a solution for: YourName = input(str("What is your name?")) print("Hello", YourName) When executing the program, in case the user input is "for", "not", "True", "while" Python interprets that as a command and changes the input's color to the corresponding command. The program runs without any further issues, but I was wondering: How can I make sure Python "understands" that the user input is nothing else but a string? I tried to fix that by changing input("What is your name?") to input(str("What is your name?)) but that didn't work. Thanks in advance, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fibonacci Series
@Alan @Dave @Dominik thank you all so much for the elaborate explanations! It's really simple and crystal clear now, the most difficult part was actually to detect and overcome my own misconceptions. Once I did that, the rest was really easy. Kind of a valuable learning for the future ;-) Instead of asking: "What's wrong with this code?" I should ask myself: "What's wrong with my assumption about this code?" whenever I hit the wall. Again, thank you so much & have a great week! Raf On Sun, Nov 24, 2013 at 4:48 PM, Alan Gauld wrote: > On 24/11/13 13:05, Rafael Knuth wrote: > >> "a" and "b" on the left side are unchangable tuples and they simply get >> unpacked on the right side. > > > Be careful about terminology here. a,b is a single tuple with two values. > But a and b are variables not tuples. > > Tuples are collections of (one or more) values. In python they are separated > by commas. Thus a single valued tuple looks like > > (5,) > > A double valued tuple like > > (3,4) > > And so on. > Note the parentheses are optional and only needed for > disambiguating the tuple. 3,4 is also a double valued > tuple. > > Variables are names that refer to values. A value can > be any Python object (including a tuple!). So > > a = None > a = 5 > a = 's' > a = (1,2) > > are all valid values for the variable 'a' > > And > > t = ( (1,2), (2,3) ) > > is a single tuple composed of two other tuples. > > So > > a,b = 3,4 > > is assigning the tuple on the right side to > the tuple on the left. It *simultaneously* > assigns 3 to a and 4 to b. > > It doesn't matter what a and b were storing previously > it creates a new tuple on the right and assigns it to > another newly created one on the left. Note that the > right side could be an existing tuple but the one > on the left is always a new tuple. Thus > > a,b = t # see above > > would only create one new tuple (on the left) and a > would have the value t[0], or (1,2) and b would be > t[1] or (2,3). > > The final thing that makes your case complicated is > that a,b appear on both sides of the assignment. But > if you remember that the assignments are effectively > happening simultaneously it all follows the same rules. > > Tuple assignment/unpacking is a powerful technique in Python. > Without it we would need to introduce extra variables so that > > a,b = b, a+b > > would become > > old_a = a > a = b > b = old_a + b > > HTH > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Else vs. Continue
Hej there, I stumbled upon the "continue" statement and to me it looks like it does exactly the same as else. I tested both else and continue in a little program and I don't see any differences between both. Is my assumption correct or wrong? If the latter is the case: Can you give me examples of continue usage that couldn't be done with else? Here's my code sample I mentioned above: for num in range(2,10): if num % 2 == 0: print("Found an even number", num) continue print("Found a number", num) Same program with else: for num in range(2,10): if num % 2 == 0: print("Found an even number", num) else: print("Found a number", num) Thanks in advance! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fibonacci Series
Now I got it, thanks :-) a, b = b, b + a ... I was was wrongly assuming that "a" and "b" on the left side "talk" to each other and that "a" tells "b" something like: "Hey 'b' ... I just assigned another value to you, make sure you execute it." But "a" and "b" don't talk to each other. Each of them executes what it is supposed to and doesn't take notice of what its neighbor variable does. The more sophisticated explanation (from my view point as an absolute beginner who's not familiar with most programming concepts yet) is that "a" and "b" on the left side are unchangable tuples and they simply get unpacked on the right side. I wrote an even more primitive program which helped me understand what *exactly* happens with "a" and "b" with each run: # 1st run a, b = 1, 5 print(a) # 1 print(b) # 5 # 2nd run a, b = b, b + a print(a) # a = b = 5 print(b) # b + a = 5 + 1 = 6 # 3rd run a, b = b, b + a print(a) # a = b = 6 print(b) # b + a = 6 + 5 = 11 # 4th run a, b = b, b + a print(a) # a = b = 11 print(b) # b + a = 11 + 6 = 17 # 5th run a, b = b, b + a print(a) # a = b = 17 print(b) # b + a = 17 + 11 = 28 # 6th run a, b = b, b + a print(a) # a = b = 28 print(b) # b + a = 28 + 17 0 45 All the best, Raf On Sun, Nov 24, 2013 at 12:33 PM, Dave Angel wrote: > On Sun, 24 Nov 2013 11:24:43 +0100, Rafael Knuth > wrote: > >> a, b = b, a +b >> > > > a = b = 1 >> b = a + b = 1 + 1 = 2 >> > > I suggest you play with the statement a bit. Print out both values each > time through the loop. > > The expression b, a+b produces a tuple. The left side a, b *unpacks* that > tuple into the two variables.a and b. > > Perhaps a simpler case might help. Try a, b = b, a What would you expect > it to do and why? > > -- > DaveA > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Fibonacci Series
Hej there, I am making a couple wrong assumptions about the program below, but I do not know where my thinking mistake is. I have some trouble understanding what exactly happens within this loop here: a, b = 0, 1 while b < 10: print(b) a, b = b, a +b What I would expect as an outcome of that while loop, is: >> 1 2 4 8 Here's my (wrong) assumption about that while loop: 1st loop: Pretty much straight forward, as b = 1 on the first line of code. >> 1 2nd loop (the output of the 1st loop is "reused" inside the 2nd loop which is: b = 1): a = b = 1 b = a + b = 1 + 1 = 2 >> 2 3rd loop: a = b = 2 b = a + b = 2 + 2 = 4 >> 4 3rd loop: a = b = 4 b = a + b = 4 + 4 = 8 break. Instead, that program's correct output is: >> 1 1 2 3 5 8 I understand what a Fibonacci Series is, but I struggle to understand what's happening inside that while loop above. Also, I would assume that an arbitrary integer can be assigned to "a" on the first line as what really matters (in my understanding) is the new value assigned to "a" within the loop. This assumption is wrong as well: a, b = 999, 1 while b < 10: print(b) a, b = b, a +b >>> 1 The while loop breaks after b = 1 is printed out. ... which makes me wonder, because I would expect a = 999 to be changed to a = b = 1 after the first loop and the program should execute the 2nd loop in my understanding ... Can anyone clarify please? Thank you! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strange issue w/ Python shell 3.0.0.
> So, what to do about it? While the Python interactive interpreter is > mighty powerful, it does have some limitations, and this is one of them. > You just have to get used to the fact that it is not well-suited for > editing large blocks of code. It is excellent for trying out small > snippets, or for running blocks of code that don't have to change, but > not for editing and running at the same time (at least not until you're > experienced enough to deal with errors like this one). Understood. Should I use a Python IDE like Pycharm or so? Would that help? If so, which ones would you recommend? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Two subsequent for loops in one function - I got it!
> See? It has no output. By the way, the python REPL is your friend! Use it > often when you can't figure out what is happening. Oh, I didn't even know that such a thing exists :-) Cool! Unfortunately, I only found Python REPLs for version 2.7.2 or lower. Is there a REPL for 3.3.0 ..? Thanks, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Two subsequent for loops in one function - I got it!
@Peter @Steven @Don @Danny thank you *so much" for explaining the concept of a nested for loop! Your simplified example Steven made it very clear to me: for x in range(2, 7): print("outer loop, x =", x) for y in range(2, x): print("inner loop, x =", x, "y =", y) I have only one question left. Here's my original program again: for x in range(2, 10): for y in range(2, x): if x % y == 0: print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") So the first output of the outer loop is: 2. It's then passed to the inner loop: for y in range(2,x): if x % y == 0: ... And I was wondering what is happening inside that loop. The output of for y in range (2,2): should be ... none - correct? What exactly happens on the next line of code? if x % y == 0 To me it looks like if 2 % "no value" == 0 is executed here which I assume causes the loop to break - correct? Just want to understand how Python deals with "no values" within a program. Thanks in advance! All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Strange issue w/ Python shell 3.0.0.
> Oh, wait, I see you are using Python 3.0. Don't. Python 3.0 is not > supported because it is buggy. You should use 3.1, or better still, 3.3. > Python 3.3 is much better than 3.1 or 3.2, and 3.0 is buggy and slow. What I was trying to say is that sometimes I get runtime errors even if nothing's wrong with my code. I had those issues with Python 3.3.0 ... I wrote a program and when I executed it, and a runtime error occured. I then copy and pasted that into a new window, I saved it and - surprise, surprise - it ran without any issues. Although I didn't modify my program in any ways. That's why I came up with that question that might sound odd to you whether Python shell somehow "caches" older, buggy versions of my program which I saved previously ... ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Strange issue w/ Python shell 3.0.0.
Hej there, I noticed that sometimes when I do lots of modifications within a program, I get runtime errors even if the program is "clean". I realized that first time when I copy and pasted a program into a new window - it miraculously ran without any problems. Although it was exactly the same program that caused problems in the old window. Stupid rookie question: Does Python shell have a cache or so? And if that's the case - how do I empty it? Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Two subsequent for loops in one function
Hej there, newbie question: I struggle to understand what exactly those two subsequent for loops in the program below do (Python 3.3.0): for x in range(2, 10): for y in range(2, x): if x % y == 0: print(x, "equals", y, "*", x//y) break else: print(x, "is a prime number") The result is: >>> 2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3 I have a very basic understanding of for loops, so for example: for everything in range(10): print(everything) ... the for loop grabs everything in that given range and prints it. But I feel confused by the double use of for loops as show above. Can anyone explain? Thanks Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
>> I'm only stuck at one point: How do I loop back to the beginning in >> case the user input is invalid? > > > Look at Peter's example. He set a variable to false when the input was > wrong. You can check that value in your while loop. Ok, got you! print("TIME TRACKING") while True: hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) break except ValueError: print ("Invalid input") if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") Program works well now, a learned a lot along the way. Thank you & have a great weekend, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ while loops
Hej there, @David @Peter @Amit: Thank you so much - you guys helped me understand my misconceptions and I learned a couple new things. On Thu, Nov 21, 2013 at 12:44 PM, Amit Saha wrote: > On Thu, Nov 21, 2013 at 9:00 PM, Rafael Knuth wrote: >> Hej there, >> >> I want to use a while loop in a program (version used: Python 3.3.0), >> and I expect it to loop unless the user enters an integer or a >> floating-point number instead of a string. >> >> print("TIME TRACKING") >> hours_worked = input("How many hours did you work today? ") >> while hours_worked != str() or int(): >> hours_worked = input("Can't understand you. Please enter a number! ") >> >> print("you worked " + str(hours_worked) + " hours today.") >> >> When I run the program, it keeps looping even if the condition is met. >> How do I need to modify the program on the 3rd line so that it stops >> looping when the user enters a floating-point number or an integer? > > There are two fundamental mistakes in your program: > > 1. The input() function always returns a string. So, there is no way > to check directly whether the user has entered a number or a string. > 2. hours_worked != str() or int() does not do what you want to do. In > Python, str() creates a new string object and similarly int() creates > an integer object, 0. Got you, thank you for the clarification. >>>> def check_input(user_input): > ... try: > ... user_input = float(user_input) > ... except ValueError: > ... return 'Invalid input' > ... else: > ... return user_input > ... >>>> check_input('a') > 'Invalid input' >>>> check_input('1.5') > 1.5 >>>> check_input('1') > 1.0 > > The idea above is basically, you convert the input (a string) to a > float. If the input is a number, 1.5 or 1, the check_input() function > will return the numeric equivalent. However, if the number is a > string, it returns invalid input. You could make use of this in your > program above. > > Hope that helps. It definitely does! I am completely new to programming, and I am taking a Python course at Codecademy. In addition to that, I write tiny, little throw-away programs along the way in order to get more practice. The concept of try/except/else was new to me and it's extremely valuable to know how make use of it. I'm only stuck at one point: How do I loop back to the beginning in case the user input is invalid? I want the program to loop until the user enters a value that is either a float or an int. None of my code modifications gave me the desired result. In case the user input is correct, I can move on and analyze it as I figured out, for example: print("TIME TRACKING") hours_worked = input("How many hours did you work today? ") try: hours_worked = float(hours_worked) except ValueError: print ("Invalid input") if hours_worked < 24: print("You must be a human.") else: print("You must be a cyborg.") All the best, Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue w/ while loops
Hej there, I want to use a while loop in a program (version used: Python 3.3.0), and I expect it to loop unless the user enters an integer or a floating-point number instead of a string. print("TIME TRACKING") hours_worked = input("How many hours did you work today? ") while hours_worked != str() or int(): hours_worked = input("Can't understand you. Please enter a number! ") print("you worked " + str(hours_worked) + " hours today.") When I run the program, it keeps looping even if the condition is met. How do I need to modify the program on the 3rd line so that it stops looping when the user enters a floating-point number or an integer? Thank you! Raf ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Python 3.3 on OpenSUSE 12.3
Hello Jay, thanks for your reply. On Thu, Oct 24, 2013 at 11:45 PM, Jay Lozier wrote: > On Thu, 2013-10-24 at 21:57 +0200, Rafael Knuth wrote: > > Hej, > > I can't get Python 3.3 up and running (it's properly installed but I > > can't launch it), and I was wondering if anyone using OpenSUSE 12.3 > > had similar issues. SUSE community folks weren't really able to help > > me, so I was wondering I give it a try here. > > Thanks, > > Rafael > > Rafael, > > I have both Python 2.7.3 and 3.3.0 installed on openSUSE 12.3. To use > 3.3 I enter python3.3 at the prompt. If I enter python it defaults to > 2.7.3 > > In the shebang #!/usr/bin/env python3.3 > Yes. > > -- > Jay Lozier > jsloz...@gmail.com > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Python 3.3 on OpenSUSE 12.3
Hej, I can't get Python 3.3 up and running (it's properly installed but I can't launch it), and I was wondering if anyone using OpenSUSE 12.3 had similar issues. SUSE community folks weren't really able to help me, so I was wondering I give it a try here. Thanks, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating To Do List Program - Question
Dominik, > OTOH, *if* your claim that you understand the concepts mentioned by Dave > isn't an ill-minded overestimation, I wonder why you don't go and use > these skills. Doyou lack a concept of how to logically build up your > code, or what's the main issue? Exactly. I didn't know how to put those pieces I learned into a program I wanted to create, and I was not aware of which skills I still missed (which turned out to be writing to and reading from files). >> I don't understand yet what a top-level program is, but I will figure that >> out. > > The thing the python interpreter calls, that is not in a class:, def: or > some other block. Ok, go you. > You're welcome back with your results ☺! Thank you! All the best, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating To Do List Program - Question
Hej Dave, thank you for your response. > Your original program had some code that interacted with the user. So > when you went from that to a giant print statement, I, and proably many > others, thought you were just kidding. I noticed that, but I was serious about that. I mean, my giant print statement was really ridiculous to say the least but it did what I wanted the program to do - adding items to the To Do List and printing that list. However, I knew this was my very first iteration and I wanted to improve my program by making those incremental baby steps. > Are you using Python 3.3, under Windows? Python 3.0 under Windows. > So let me ask some questions about your level of understanding. Sure. > Do you know what an if statement is? How about a for or while > statement? Yes, I am familiar with both. > Can you write code in a function, have it take parameters and return > results? Do you know how to call such a function? Yes. > Do you know what a list is? Can you manipulate it at all? Can you > create it from a literal, using the [] syntax. Yes. > Do you know what a file is? Do you know the difference between text > file and binary file? Can you read a text file into a list? Can you > write a list of strings out to a text file? I worked with text files yet, I have to admit I haven't worked with binary files though - and I don't know yet what they are. But I will figure that out. > If you understand all these pieces, you're probably ready to try to > construct a todo list program. If not, I second the suggestion to > follow a tutorial, till it's covered at least all of these. Ok, cool. > (I may have missed quite a few items, but I think all of these are > necessary.) Ok, so I will rewrite that To Do list as you (and the others) suggested and I will get back to you in case I have any further questons. > For example, write a function that builds a list of strings by asking > the user, a line at a time, till the user enters a blank string. The > function should return the list. Ok, understood. > Once you think you have the function written, write a simple top-level > program that calls the function and prints the results. Then have it > print the results one line at a time. I don't understand yet what a top-level program is, but I will figure that out. Again, thank you all. I have a fairly good understanding of how I should proceed now. Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating To Do List Program - Question
Dominik, this was my original question: As of now, I want to understand how I can add further functionalities to my program such as: appending items to the list, removing and replacing items. Can anyone help? Simple as that. Rafael On Mon, Sep 30, 2013 at 1:41 PM, Dominik George wrote: > -BEGIN PGP SIGNED MESSAGE- > Hash: SHA512 > > > > Rafael Knuth schrieb: >>Dominik, >> >>> it's not your program - it's your attitude. We expect you to learn >>for yourself as well, and putting the commands you output into a script >>and execute it clearly isn't beyond what we can expect from someone who >>can use a mail program. >> >>Thanks for the clarification, you were the third kid on the block I >>missed to add to my feedback on behavior I find inappropriate. >>You are suggesting that my attitude is wrong, but what's wrong about >>doing baby-steps even if it's at the level of someone barely able to >>use a mail program? I simply want to create a To Do List program, and >>I couldn't find any tutorials on that, therefore I reached out to the >>mailing list. And here I am, justifying myself for my first clumsy >>attempt to accomplish my goal. >> >>I am still hoping that I will get some feedback from anyone on that >>list that will help me make a tiny little next step. >> >>Thank you in advance, >> >>Rafael > > You already got that - remove the surrounding print() and put it in a script. > > Why haven't you taken that advice yet? > > - -nik > - -- > Diese Nachricht wurde von meinem Android-Mobiltelefon mit K-9 Mail gesendet. > -BEGIN PGP SIGNATURE- > Version: APG v1.0.8-fdroid > > iQFNBAEBCgA3BQJSSWN7MBxEb21pbmlrIEdlb3JnZSAobW9iaWxlIGtleSkgPG5p > a0BuYXR1cmFsbmV0LmRlPgAKCRAvLbGk0zMOJZPLCACyAJ1DL33nvDOZVj3/heWG > zciLXGnvoINbiufZLjl5yPn/yxzJdS2knwUbE1AhuzoxiZCoLFMzZKN4BnXWdG1A > cjqj8e/cin2YUWBG1eu53wcdU4iAhbwaKzLgP5soy8ZLc2cnWtf5Dmrgc+IGw02f > /LZPBgw+XjngbYQ1U8RMH/15NKYuMVhy9WzRO19I4sOUCrQQspEBhvRwejS4eApO > l7PwaHI3A6pxdWITaX/C8nVOpicUMVEDx9LE8+hswvGO6yIulyCkelkeAJgTcj5s > MN6QDglZaguWLcDH3gGXfN6Go28RLPiC2hD1+Hv+JbCriVWxZd2WIBzh5K3It/OT > =0kOH > -END PGP SIGNATURE- > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating To Do List Program - Question
Dominik, > it's not your program - it's your attitude. We expect you to learn for > yourself as well, and putting the commands you output into a script and > execute it clearly isn't beyond what we can expect from someone who can use a > mail program. Thanks for the clarification, you were the third kid on the block I missed to add to my feedback on behavior I find inappropriate. You are suggesting that my attitude is wrong, but what's wrong about doing baby-steps even if it's at the level of someone barely able to use a mail program? I simply want to create a To Do List program, and I couldn't find any tutorials on that, therefore I reached out to the mailing list. And here I am, justifying myself for my first clumsy attempt to accomplish my goal. I am still hoping that I will get some feedback from anyone on that list that will help me make a tiny little next step. Thank you in advance, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating To Do List Program - Question
Hej there, @Alan @Joel: I didn't know that pouring corn on newbies is the purpose of a tutor mailing list. Why don't you try writing a program instead? Why don't you use the cat interpreter instead? I tried my best and that's what I came up with, and I am eager to learn form experienced programmers - step by step at my own pace and in my own manner. Hence, I find your responses arrogant, self-righteous and discouraging. I do not understand why you don't consider what I wrote not a program ("Hello World!" in a more elaborate form), as the user is actually able to a list, to write to and reads from it (in a very primitive manner though). Can anyone explain? However, I find that hint to learn to use SQLite - thank you for that. All the best, Rafael Rafael On Mon, Sep 30, 2013 at 1:43 AM, Alan Gauld wrote: > On 29/09/13 21:42, Rafael Knuth wrote: > >> iteration. I know my program is super cheesy & primitive, but I don’t >> care, it does what I expect it to do, > > > Really? You wrote a program that printed out a different > program to the one you ran and that's what you wanted? > It doesn't do anything about creating a ToDo list. > It doesn't even bring you any closer to creating a ToDo list. > > Now, if instead of just printing it you actually ran > the code you print it might actually get you somewhere > closer. > > But at the moment your program is exactly equivalent to > > print('Hello world') > > except more verbose in its message. > > >> print(""" >> >> Welcome World's Most Geeky To Do List Program >> >> G E E K L I S T 1 . 0 >> >> If you want to add items to the list, enter: >> >> text_file = open("ToDoList.txt", "w") >> text_file.write("add your item here ") >> text_file.write("add action item here ") >> text_file.write("you get the point, right?") >> text_file.close() >> >> If you want to print your to do list, enter: >> >> text_file = open("ToDoList.txt", "r") >> print(text_file.read()) >> text_file.close() >> >> We are constantly improving our program, watch out for version 2.0! >> >> """) > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating To Do List Program - Questions
Joel, I am terribly sorry, I erased that thread accidentally without having read it, and I now found it. Thank you and again - and apologies! Rafael On Mon, Sep 30, 2013 at 12:35 PM, Joel Goldstick wrote: > You restarted the same thread from yesterday where you got several replies. > Go and find that thread. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating To Do List Program - Questions
Hej there, apologies if you're receiving my mail for a second time, I had some issues with Google and I just want to make sure you will receive my email. I am writing a to do list program in Python 3.0. Last week, I shared my first iteration on the mailing list, and the feedback was that I should learn how to create, write to and read from a text file – which I did. Below please find my second iteration. I know my program is super cheesy & primitive, but I don’t care, it does what I expect it to do, and I will improve it in further iteration cycles. As of now, I want to understand how I can add further functionalities to my program such as: appending items to the list, removing and replacing items. Can anyone help? Thank you very much in advance! print(""" Welcome World's Most Geeky To Do List Program G E E K L I S T 1 . 0 If you want to add items to the list, enter: text_file = open("ToDoList.txt", "w") text_file.write("add your item here ") text_file.write("add action item here ") text_file.write("you get the point, right?") text_file.close() If you want to print your to do list, enter: text_file = open("ToDoList.txt", "r") print(text_file.read()) text_file.close() We are constantly improving our program, watch out for version 2.0! """) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Creating To Do List Program - Question
Hej there, I am writing a to do list program in Python 3.0. Earlier this week, I shared my first iteration on the mailing list, and the feedback was that I should learn how to create, write to and read from a text file – which I did. Below please find my second iteration. I know my program is super cheesy & primitive, but I don’t care, it does what I expect it to do, and I will improve it in further iteration cycles. As of now, I want to understand how I can add further functionalities to my program such as: appending items to the list, removing and replacing items. Can anyone help? Thank you very much in advance! print(""" Welcome World's Most Geeky To Do List Program G E E K L I S T 1 . 0 If you want to add items to the list, enter: text_file = open("ToDoList.txt", "w") text_file.write("add your item here ") text_file.write("add action item here ") text_file.write("you get the point, right?") text_file.close() If you want to print your to do list, enter: text_file = open("ToDoList.txt", "r") print(text_file.read()) text_file.close() We are constantly improving our program, watch out for version 2.0! """) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing program: To Do List in Python 3.0
Dave, thank you so much, I will proceed as you suggested. Currently, I am not 100% sure I get it right, but I will start iterating now. All the best, Rafael > > Can you advise how I should proceed in order to > > improve my To Do List program based on the code I wrote so far > > (insofar it's usable at all) ..? Weirdly, writing and reading to files > > is not covered in those tutorials I am working with. > > > First comment: learn to use functions. Don't put anything in top-level > > Your functions should usually take paramaters and return their results. > Avoid writable global values. If you need to return more than one > results, learn to use tuples for that, with automatic tuple unpacking > where appropriate. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Writing program: To Do List in Python 3.0
Alan, On Wed, Sep 25, 2013 at 9:11 PM, Alan Gauld wrote: > On 25/09/13 18:42, Rafael Knuth wrote: > >> I want to write a simple program (To Do List) that stores the input >> data (action items on To Do List). Currently I can only input items >> but the program I wrote doesn't store them. > > > You need to write the data to a file or database when the program closes and > then, when you start the program, read the data from > that file or database. Thank you for the clarification. > > >> Here's the code I wrote so far: > > > OK, This is very basic and can be improved in lots of ways so I'm guessing > you are a new programmer and studying via some kind of > course or tutorial? Self study, yes. Intermediate beginner. I just started writing games such as Hangman, Tic Tac Toe. Now I wanted to write a small To Do List which requires reading and writing to files as you explained (which is exactly what I want to learn now). > > At some stage it will cover reading and writing to files as well as data > structures that will help store your data more effectively and looping > constructs that will help you process it more effectively. > > You can read up on reading and writing to files if you want but > it may be better not to run before you can walk... Consider me a toddler. Can you advise how I should proceed in order to improve my To Do List program based on the code I wrote so far (insofar it's usable at all) ..? Weirdly, writing and reading to files is not covered in those tutorials I am working with. Thank you, Rafael > >> print("This is my to do list") >> >> Monday = input("Monday ") >> Tuesday = input("Tuesday ") >> Wednesday = input("Wednesday ") >> Thursday = input("Thursday ") >> Friday = input("Friday ") >> Saturday = input("Saturday ") >> Sunday = input("Sunday ") >> >> print("So, here are your plans for:" + >> "\nMonday " + Monday + >> "\nTuesday " + Tuesday + >> "\nWednesday " + Wednesday + >> "\nThursday " + Thursday + >> "\nFriday " + Friday + >> "\nSaturday " + Saturday + >> "\nSunday " + Sunday) > > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Writing program: To Do List in Python 3.0
Hej there, I want to write a simple program (To Do List) that stores the input data (action items on To Do List). Currently I can only input items but the program I wrote doesn't store them. Can you help? Thanks, Rafael Here's the code I wrote so far: print("This is my to do list") Monday = input("Monday ") Tuesday = input("Tuesday ") Wednesday = input("Wednesday ") Thursday = input("Thursday ") Friday = input("Friday ") Saturday = input("Saturday ") Sunday = input("Sunday ") print("So, here are your plans for:" + "\nMonday " + Monday + "\nTuesday " + Tuesday + "\nWednesday " + Wednesday + "\nThursday " + Thursday + "\nFriday " + Friday + "\nSaturday " + Saturday + "\nSunday " + Sunday) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Flip the coin 10x and count heads and tails: It works now!
Gents, thank you all for your help. One of you guys asked me to try out your suggestions and then tell you how it goes. Here we go! First, let me recap briefly what the expected outcome of my program was and which difficulties I encountered at the beginning. I was writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails. It obviously did something else than I intended: import random print (""" This program flips a coin 10 times. It then counts the number of heads and tails. """) flips = 0 heads = 0 tails = 0 while flips < 10: flips = flips + 1 if random.randint(1,2) == 1: heads = heads + 1 print("We've got " + str(heads) + " heads here." if random.randint(1,2) == 2: tails = tails + 1 print("We've got " + str(tails) + " tails here.") This is what I got as output: This program flips a coin 10 times. It then counts the number of heads and tails. We've got 1 tails here. We've got 1 heads here. We've got 2 tails here. We've got 2 heads here. We've got 3 tails here. We've got 3 heads here. We've got 4 tails here. We've got 5 tails here. We've got 4 heads here. We've got 6 tails here. We've got 7 tails here. We've got 5 heads here. As it turned out, each of your answers was *partially* correct, so I played around with your suggestions until I got my code up and running. Frankly, I did two mistakes: First, I placed the print statement inside the loop instead of outside of it. And second, I mistakenly called the random function two times inside the loop. In order to resolve that issue, I had to modify the heads and tails variables and then add another variable and put it inside the loop: result = random.randint(1,2) Lastly, I figured out that counting the results can be done in a more elegant fashion. Instead of: variable_XYZ = variable_XYZ + 1 … it can be done this way: variable_XYZ += 1 I got so excited when I saw my program run properly that I decided to pimp it a little bit by printing each head and tail with a time delay while the coin got flipped during the run. Here’s what my code looks like now: import random import time print (""" This program flips a coin 10 times. It then counts the number of heads and tails. """) time.sleep(1) flips = 0 heads = 0 tails = 0 while flips < 10: result = random.randint(1,2) if result == 1: heads += 1 print("head") time.sleep(1) elif result == 2: tails += 1 print("tail") time.sleep(1) flips += 1 print ("\nYou've got " + str(heads) + " heads and " + str(tails) + " tails.") I have one last question to you: I explained twice in my initial mail what I expect my program to do (“I am writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails.”). I did that the introduction as well as inside my code. However, almost each of you asked me what I expect my program to do. I was confused about that and I am wondering if any of you can clarify? I just want to make sure I avoid misunderstandings like these in the future. Thank you all again! All the best, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue w/ program: Flip a coin and count heads and tails
> > I am writing a program in Python 3.3.0 which flips a coin 10 x times and > then counts the number of heads and tails. It obviously does something else > than I intended, and I am wondering what I did wrong: > What is that you intended? Please explain that. I want that program to flip a coin 10 x times and then count the number of heads and tails. That's very much it. On Fri, May 24, 2013 at 1:08 PM, Asokan Pichai wrote: > > > On Fri, May 24, 2013 at 4:31 PM, Rafael Knuth wrote: > >> Hello, >> >> I am writing a program in Python 3.3.0 which flips a coin 10 x times and >> then counts the number of heads and tails. It obviously does something else >> than I intended, and I am wondering what I did wrong: >> > > What is that you intended? > Please explain that. > >> >> import random >> >> print (""" >> >> This program flips a coin 10 times. >> > Actually this is wrong. The program does something else. > > >> >> It then counts the number of heads and tails. >> >> """) >> >> flips = 0 >> >> heads = 0 >> >> tails = 0 >> >> while flips < 10: >> >> flips = flips + 1 >> >> if random.randint(1,2) == 1: >> >> heads = heads + 1 >> >> print("We've got " + str(heads) + " heads here." >> >> if random.randint(1,2) == 2: >> >> tails = tails + 1 >> >> print("We've got " + str(tails) + " tails here.") >> > >> This is what I get as output: >> >> This program flips a coin 10 times. >> >> It then counts the number of heads and tails. >> >> We've got 1 tails here. >> >> We've got 1 heads here. >> >> We've got 2 tails here. >> >> We've got 2 heads here. >> >> We've got 3 tails here. >> >> We've got 3 heads here. >> >> We've got 4 tails here. >> >> We've got 5 tails here. >> >> We've got 4 heads here. >> >> We've got 6 tails here. >> >> We've got 7 tails here. >> >> We've got 5 heads here. >> > Is this an actual output??? Did the program stop here at 5 heads and 7 > tails? > > >> >> Can anyone help? >> >> Thank you so much! >> >> All the best, >> >> Rafael >> > > Asokan Pichai > > "Expecting the world to treat you fairly because you are a good person is > a little like expecting the bull to not attack you because you are a > vegetarian" > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue w/ program: Flip a coin and count heads and tails
Hello, I am writing a program in Python 3.3.0 which flips a coin 10 x times and then counts the number of heads and tails. It obviously does something else than I intended, and I am wondering what I did wrong: import random print (""" This program flips a coin 10 times. It then counts the number of heads and tails. """) flips = 0 heads = 0 tails = 0 while flips < 10: flips = flips + 1 if random.randint(1,2) == 1: heads = heads + 1 print("We've got " + str(heads) + " heads here." if random.randint(1,2) == 2: tails = tails + 1 print("We've got " + str(tails) + " tails here.") This is what I get as output: This program flips a coin 10 times. It then counts the number of heads and tails. We've got 1 tails here. We've got 1 heads here. We've got 2 tails here. We've got 2 heads here. We've got 3 tails here. We've got 3 heads here. We've got 4 tails here. We've got 5 tails here. We've got 4 heads here. We've got 6 tails here. We've got 7 tails here. We've got 5 heads here. Can anyone help? Thank you so much! All the best, Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Random Number Game: Returns always the same number - why?
Your variable assignment for Random_Number is outside of your while loop. Therefore its value never changes. Put it inside the while loop just before the print statement and I think you will get what you That was it! Thank you, you made my day, Bob :-) On Mon, May 20, 2013 at 6:37 PM, boB Stepp wrote: > > On Mon, May 20, 2013 at 11:31 AM, Rafael Knuth wrote: > > > > Hello, > > > > I wrote a simple program, and I was expecting that I would get 100 different random numbers. Instead, I am getting 100 times exactly the same random number. Can anyone advise how I should alter my program? > > > > Thank you! > > > > All the best, > > > > Rafael > > PS. I am using Python 3.3.0 > > > > print (""" > > > > This game will return 100 random numbers between 1 and 100. > > > > """) > > > > import random > > > > Count = 0 > > > > Random_Number = random.randint(1, 100) > > > > while Count <= 100: > > print (Random_Number) > > > > Count = Count + 1 > > > Your variable assignment for Random_Number is outside of your while > loop. Therefore its value never changes. Put it inside the while loop > just before the print statement and I think you will get what you > wanted. > > HTH, > boB > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner level: Why doesn't my code work?
But this is all a distraction -- how exactly are you invoking what you think is Python 3.3.0? What is your operating system? My mistake, I am using two laptops with different operating systems (Windows 7 & SUSE 12.3). I am using Python 3.3.0 on the Windows laptop and I was wrongly assuming that I am running the same version of Python on my SUSE laptop. I simply forgot that I have a Python 2.x version on my SUSE laptop. I tried that game on my Windows 7 laptop (where I have 3.3.0 installed) and it runs nicely. Thank you for your support! import random print(""" This is a magic super computer. He will ask you a couple of questions. An ultra-complicated algorithm will then figure out what your favorite meal is. """) name = input("What is your name? ") age = int(input("How old are you? ")) birthplace = input("Where are you born? ") meal = random.randint(1, 3) if meal == 1: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like hamburgers.") elif meal == 2: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like sushi.") elif meal == 3: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like pizza.") On Sun, May 19, 2013 at 4:54 PM, Peter Otten <__pete...@web.de> wrote: > Rafael Knuth wrote: > > > Thank you, I am using Python 3.3.0 > > [Oscar] > > In Python 3 you should use input(). In Python 2 you should use > > raw_input(). I'm guessing that you're using Python 2. In Python 2 the > > input() function tries to evaluate whatever the user types in as if it > > was Python code. Since Rafael is not a defined variable it fails. The > > fix is to use raw_input() which just returns a string. > > > [Rafael] > > I am not sure I understand. > > "Rafael" is the user's in put, and that value is assigned to the variable > > "name". > > I made sure only a string is accepted as input > > > > name = (str(input("What's your name?")) > > > > Can you clarify? Thank you in advance. > > As Oscar says you are invoking your script with Python 2. Python 2's > input() > function evals user input as a Python expression. For example if you run a > script > > print input("your input please: ") > > and you type > > 1 + 1 > > the script will print > > 2 > > Likewise if you type > > Rafael > > the script will look up the value of a variable named Rafael. This doesn't > exist and therefore you get an exception. > > But this is all a distraction -- how exactly are you invoking what you > think > is Python 3.3.0? What is your operating system? > > If you are using Linux or OSX open a terminal window and try to run your > script from that terminal window with > > python3.3 ~/Documents/3_Tufcik.py > > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Random Number Game: Returns always the same number - why?
Hello, I wrote a simple program, and I was expecting that I would get 100 different random numbers. Instead, I am getting 100 times exactly the same random number. Can anyone advise how I should alter my program? Thank you! All the best, Rafael PS. I am using Python 3.3.0 print (""" This game will return 100 random numbers between 1 and 100. """) import random Count = 0 Random_Number = random.randint(1, 100) while Count <= 100: print (Random_Number) Count = Count + 1 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Beginner level: Why doesn't my code work?
Hello, please post in plain text (not html) in future. Also you should mention what version of Python you're using as it makes a dfference in this case. Thank you, I am using Python 3.3.0 As for the HTML ... I copied the code from the Python Shell - should I post code as a screenshot? Would that resolve that issue you mentioned? In Python 3 you should use input(). In Python 2 you should use raw_input(). I'm guessing that you're using Python 2. In Python 2 the input() function tries to evaluate whatever the user types in as if it was Python code. Since Rafael is not a defined variable it fails. The fix is to use raw_input() which just returns a string. I am not sure I understand. "Rafael" is the user's in put, and that value is assigned to the variable "name". I made sure only a string is accepted as input name = (str(input("What's your name?")) Can you clarify? Thank you in advance. On Sun, May 19, 2013 at 3:16 PM, Oscar Benjamin wrote: > On 19 May 2013 14:04, Rafael Knuth wrote: > > Hello, > > Hello, please post in plain text (not html) in future. Also you should > mention what version of Python you're using as it makes a dfference in > this case. > > > > > here's a tiny little program I wrote: > > > > import random > > > > print(""" > > > > This is a magic super computer. > > > > He will ask you a couple of questions. > > > > An ultra-complicated algorithm will then figure out what your favorite > meal > > is. > > > > """) > > > > name = str(input("What is your name? ")) > > In Python 3 you should use input(). In Python 2 you should use > raw_input(). I'm guessing that you're using Python 2. In Python 2 the > input() function tries to evaluate whatever the user types in as if it > was Python code. Since Rafael is not a defined variable it fails. The > fix is to use raw_input() which just returns a string. > > An alternative fix is to write > > input = raw_input > > at the top of your script. That way you won't need to change anything > else to have it work with Python 3. In fact if you write it like this > > try: > input = raw_input > except NameError: > pass > > then it will work in both Python 2 and 3. > > > Here's the error message I am getting: > > > > Traceback (most recent call last): > > File "/home/rafael/Documents/3_Tufcik.py", line 13, in > > name = str(input("What is your name? ")) > > File "", line 1, in > > NameError: name 'Rafael' is not defined > > > Oscar > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Beginner level: Why doesn't my code work?
Hello, here's a tiny little program I wrote: import random print(""" This is a magic super computer. He will ask you a couple of questions. An ultra-complicated algorithm will then figure out what your favorite meal is. """) name = str(input("What is your name? ")) age = int(input("How old are you? ")) birthplace = str(input("Where are you born? ")) meal = random.randint(1, 3) if meal == 1: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like hamburgers.") elif meal == 2: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + " you probably like sushi.") elif meal == 3: print("Well, " + name + " as a " + str(age) + " year old human being born in " + birthplace + "you probably like pizza.") Here's the error message I am getting: Traceback (most recent call last): File "/home/rafael/Documents/3_Tufcik.py", line 13, in name = str(input("What is your name? ")) File "", line 1, in NameError: name 'Rafael' is not defined Can anyone help? Thanks in advance! Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Issue with string method: str(variable ** n)
Thank you - that makes perfectly sense. Also, I am new to the list, and I appreciate your suggestion. I will include error tracebacks in the future. All the best, Rafael On Thu, May 16, 2013 at 9:14 PM, Dave Angel wrote: > On 05/16/2013 02:58 PM, Rafael Knuth wrote: > >> Hej, >> >> I wrote a tiny little program which I was hoping would take a number as >> input, square and print it: >> >> square = input ("Enter a number. ") >> print (str(square) + " squared is " + str(square ** 2)) >> >> It seems I can't work with variables within the str() string method, and I >> was wondering if anyone can help? >> >> PS. I am using Python 3.3.0 >> >> Thank you in advance! >> >> Rafael >> >> >> In Python 3.3.0, input returns a string. So square is a string. There > isn't any meaning to squaring a string. > > > You probably want either: > > square = float(input("Enter a number.") > or > square = int(input("Enter a number.") > > Suggestion for next time - include the error traceback. > > -- > DaveA > > __**_ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/**mailman/listinfo/tutor<http://mail.python.org/mailman/listinfo/tutor> > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Issue with string method: str(variable ** n)
Hej, I wrote a tiny little program which I was hoping would take a number as input, square and print it: square = input ("Enter a number. ") print (str(square) + " squared is " + str(square ** 2)) It seems I can't work with variables within the str() string method, and I was wondering if anyone can help? PS. I am using Python 3.3.0 Thank you in advance! Rafael ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor