[Tutor] python -v command
Hi, I'm at a very beginning level of Python knowledge, but I use several Python programs via the Macintosh Unix Terminal. I was trying to quickly see which version of Python I am running and typed in the command "python -v". That was obviously not the correct command to use. It installed several things and now I'm unable to run my Python programs. Can someone tell me if there there is a way to undo the python -v command? Any suggestions for how I can remedy the situation. I'm ready to crawl into a dark hole and hide - I feel very foolish! Thanks so much for putting up with a newbie's silly question. Here's the Terminal output in case that helps at all: admin$ python -v # installing zipimport hook import zipimport # builtin # installed zipimport hook # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site.py import site # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.py import os # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/os.pyc import posix # builtin # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/posixpath.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/posixpath.py import posixpath # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/posixpath.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/stat.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/stat.py import stat # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/stat.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/UserDict.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/UserDict.py import UserDict # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/UserDict.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy_reg.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy_reg.py import copy_reg # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/copy_reg.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/types.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/types.py import types # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/types.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/warnings.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/warnings.py import warnings # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/warnings.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/linecache.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/linecache.py import linecache # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/linecache.pyc import encodings # directory /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/__init__.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/__init__.py import encodings # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/__init__.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/codecs.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/codecs.py import codecs # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/codecs.pyc import _codecs # builtin # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/aliases.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/aliases.py import encodings.aliases # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/aliases.pyc # /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/ascii.pyc matches /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/ascii.py import encodings.ascii # precompiled from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/encodings/ascii.pyc Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. import readline # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/lib-dynload/readline.so >>> ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python -v command
Thank you to everyone for your help. I'm sorry to waste your time with such a silly question. I am now back up and running! I really appreciate your responses. On Fri, May 2, 2008 at 11:16 AM, Kent Johnson <[EMAIL PROTECTED]> wrote: > On Fri, May 2, 2008 at 11:33 AM, Stephanie <[EMAIL PROTECTED]> > wrote: > > Hi, > > I'm at a very beginning level of Python knowledge, but I use several > Python > > programs via the Macintosh Unix Terminal. I was trying to quickly see > which > > version of Python I am running and typed in the command "python -v". > That > > was obviously not the correct command to use. It installed several > things > > and now I'm unable to run my Python programs. > > > > Can someone tell me if there there is a way to undo the python -v > command? > > You have started python in verbose mode. It didn't actually install > anything, it is showing you all the modules that are loaded when > python starts up. > > At the end, notice that the prompt is >>>. That is the python > interpreter prompt. Type control-D to exit the interpreter and get > back to the shell prompt. > > Near the end, notice that it did also print the version - Python > always does that when it runs interactively. You can also use the > command > python --version > to print the version number and exit. > > Kent > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] creat a program that reads frequency of words in file
Hello. i need serious help. i am a very very new python programmer. I have never done any code in my life. I am lost with these assignments for a class i am taking. I hope someone can assist. below is what i have so far which i know is incorrect. my question is how do i create a dictionary and save the words plus counts to it? i created an empty dictionary and i understand the program should read the entire file and create dictionary and store the data into it. but the only way i could get it to run at all was in the way you see below. i don’t think anything is actually being saved into the dictionary. i am so lost… “”" Word Frequency Write a program that reads the contents of a text file. The program should create a dictionary in which the keys are the individual words found in the file and the values are the number of times each word appears. for example, if the word 'the' appears 128 times, the dictionary would contain an element with 'the' as the key and 128 as the value. the program should either display the frequency of each word or create a second file containing a list of each words and its frequency. """ def main(): dict = {} count = 0 text = input('enter word: ') data = open("words.txt").readlines() for line in data: if text in line: count += 1 print("This word appears", count, "times in the file") main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] creating a dictionary for capital quiz program
Good evening, As you may have noticed i am really struggling with functions and dictionaries. I need to figure out why this program is allowing me to continue entering incorrect data instead of telling me my answer is incorrect. also at the end it’s not tallying the incorrect/correct responses properly. please any help would be appreciated. Write a program that creates a dictionary containing the U.S. States as keys and their capitals as values. (Use the internet to get a list of the states and their capitals.) The program should then randomly quiz the user by displaying the name of a state and asking the usr to enter that state's capital. The program should keep a count of the number of correct and incorrect responses. (As an alternative to the US states, the program can use the names of countries and their capitals.)""" import pickle def main(): right = 0 wrong = 0 capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ \ "Arizona": 'Phoenix', \ \ 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ \ 'Colorado': 'Denver', \ \ 'Connecticut': 'Hartford', 'Delaware': 'Dover', \ \ 'Florida': 'Tallahassee', \ \ 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ \ 'Idaho': 'Boise', \ \ 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ \ 'Iowa': 'Des Moines', \ \ 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ \ 'Louisiana': 'Baton Rouge', \ \ 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ \ 'Massachusetts': 'Boston', \ \ 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ \ 'Mississippi': 'Jackson', \ \ 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ \ 'Nebraska': 'Lincoln', \ \ 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ \ 'New Jersey': 'Trenton', \ \ 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ \ 'North Carolina': 'Raleigh', \ \ 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ \ 'Oklahoma': 'Oklahoma City', \ \ 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ \ 'Rhode Island': 'Providence', \ \ 'South Carolina': 'Columbia', \ \ 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ \ 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ \ 'Vermont': 'Montpelier', \ \ 'Virginia': 'Richmond', 'Washington': 'Olympia', \ \ 'West Virginia': 'Charleston', \ \ 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for k in capitals.keys(): state = input('Enter the capital of '+k+' :') if state.upper() == capitals[k].upper(): right += 1 print('Correct') else: wrong += 1 print('Incorrect') choice = input('Do you want to play again y/n: ') if choice.upper() == 'N': print('end of game') else: choice.upper() != 'Y' print("invalid choice") print('Number of correct answers is: ', right) print("Number of incorrect answers is:", wrong) main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creat a program that reads frequency of words in file
thanks on the help. I am now stuck on this program for quizzing on state capitals. Do you mind taking a look please? I can’t get it to tell me the answer is incorrect it just keeps asking me for capitals whether the answer is right or wrong. It also is not giving me correct counts for correct and incorrect answers. Any help would be appreciated. Not sure if i turned HTML. my laptop is fairly new and I’m still assimilating to iOS. Please let me know if the code is hard to read. Thanks ___ Write a program that creates a dictionary containing the U.S. States as keys and their capitals as values. (Use the internet to get a list of the states and their capitals.) The program should then randomly quiz the user by displaying the name of a state and asking the usr to enter that state's capital. The program should keep a count of the number of correct and incorrect responses. (As an alternative to the US states, the program can use the names of countries and their capitals.)""" import pickle def main(): right = 0 wrong = 0 capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', \ \ "Arizona": 'Phoenix', \ \ 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ \ 'Colorado': 'Denver', \ \ 'Connecticut': 'Hartford', 'Delaware': 'Dover', \ \ 'Florida': 'Tallahassee', \ \ 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ \ 'Idaho': 'Boise', \ \ 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ \ 'Iowa': 'Des Moines', \ \ 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ \ 'Louisiana': 'Baton Rouge', \ \ 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ \ 'Massachusetts': 'Boston', \ \ 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ \ 'Mississippi': 'Jackson', \ \ 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ \ 'Nebraska': 'Lincoln', \ \ 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ \ 'New Jersey': 'Trenton', \ \ 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ \ 'North Carolina': 'Raleigh', \ \ 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ \ 'Oklahoma': 'Oklahoma City', \ \ 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ \ 'Rhode Island': 'Providence', \ \ 'South Carolina': 'Columbia', \ \ 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ \ 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ \ 'Vermont': 'Montpelier', \ \ 'Virginia': 'Richmond', 'Washington': 'Olympia', \ \ 'West Virginia': 'Charleston', \ \ 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} for k in capitals.keys(): state = input('Enter the capital of '+k+' :') if state.upper() == capitals[k].upper(): right += 1 print('Correct') else: wrong += 1 print('Incorrect') choice = input('Do you want to play again y/n: ') if choice.upper() == 'N': print('end of game') else: choice.upper() != 'Y' print("invalid choice") print('Number of correct answers is: ', right) print("Number of incorrect answers is:", wrong) main() > On Jun 1, 2015, at 7:42 PM, Alan Gauld wrote: > > I've CCd the list. Please use reply all when responding to the list. > Also please use plain text as HTML/RTF doesn't work on all > systems and code in particular often gets mangled. > > On 01/06/15 23:59, Stephanie Quiles wrote: >> Hello again, >> >> here is the final code… I think :) please see below. Is this is the easiest >> way to go about it? I appreciate your assistance! >> >> defmain(): >> words = {} >> count =0 > > Do you need count? What is its purpose? >> withopen('words.txt')asdata: >> forlineindata: >> text = line.split() >> forwordintext: >> ifwordnot inwords: >> words[word] =1 >> else: >> words[word] +=1 > > Look into the setdefault() method of dictionaries. > It can replace the if/else above. > >> count +=1 >> print(words) > > Aside from the two comments above, good job! > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] creating a dictionary for capital quiz program
Thank you all for your help! I have a text today but I am not confident with this. So basically, what I did wrong was the indentation? Thanks Stephanie Quiles Sent from my iPhone > On Jun 2, 2015, at 10:15 AM, Peter Otten <__pete...@web.de> wrote: > > ZBUDNIEWEK. JAKUB wrote: > >> I'm a newbie, but was able to tune it to correctly reply to user inputs. > >> 2. Why (on Windows) do I have to give inputs in quotes not to cause an >> error (for ll input the error is ' NameError: name 'll' is not defined')? > > If you are running the script under Python 2 you should use > raw_input() instead of input(). input() will take the user input and also > run eval() on it: > > Python 2.7.6 (default, Mar 22 2014, 22:59:56) > [GCC 4.8.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> input("? ") > ? 1 + 1 > 2 >>>> raw_input("? ") > ? 1 + 1 > '1 + 1' > > Python 3 has no raw_input() and input() will behave like raw_input() in > Python 2. > >> 1. My question is can it be optimized in any way? > > In Python 2 capital.keys() builds a list. You can avoid that by iterating > over the dict directly: > > for k in capitals: >... > > Not an optimization, but if the user enters neither Y nor N you might ask > again instead of assuming Y. > > >> def main(): >> >>right = 0 >>wrong = 0 >>capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', "Arizona": >>'Phoenix', \ >> 'Arkansas': 'Little Rock', 'California': 'Sacramento', \ >> 'Colorado': 'Denver', 'Connecticut': 'Hartford', >> 'Delaware': 'Dover', \ 'Florida': 'Tallahassee', \ >> 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', \ >> 'Idaho': 'Boise', \ >> 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', \ >> 'Iowa': 'Des Moines', \ >> 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', \ >> 'Louisiana': 'Baton Rouge', \ >> 'Maine': 'Augusta', 'Maryland': 'Annapolis', \ >> 'Massachusetts': 'Boston', \ >> 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', \ >> 'Mississippi': 'Jackson', \ >> 'Missouri': 'Jefferson City', 'Montana': 'Helena', \ >> 'Nebraska': 'Lincoln', \ >> 'Nevada': 'Carson City', 'New Hampshire': 'Concord', \ >> 'New Jersey': 'Trenton', \ >> 'New Mexico': 'Santa Fe', 'New York': 'Albany', \ >> 'North Carolina': 'Raleigh', \ >> 'North Dakota': 'Bismarck', 'Ohio': 'Columbus', \ >> 'Oklahoma': 'Oklahoma City', \ >> 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', \ >> 'Rhode Island': 'Providence', \ >> 'South Carolina': 'Columbia', \ >> 'South Dakota': 'Pierre', 'Tennessee': 'Nashville', \ >> 'Texas': 'Austin', 'Utah': 'Salt Lake City', \ >> 'Vermont': 'Montpelier', \ >> 'Virginia': 'Richmond', 'Washington': 'Olympia', \ >> 'West Virginia': 'Charleston', \ >> 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} >> >>for k in capitals.keys(): >>state = input('Enter the capital of '+k+' :') >>if state.upper() == capitals[k].upper(): >>right += 1 >>print('Correct') >>else: >>wrong += 1 >>print('Incorrect') >>choice = input('Do you want to play again y/n: ') >>if choice.upper() == 'N': >>print('end of game') >>break >>elif choice.upper() != 'Y': >>print("invalid choice") >> >>print('Number of correct answers is: ', right) >>print("Number of incorrect answers is:", wrong) >> >> main() >> >> Regards, >> Jakub > > > ___ > 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 a dictionary for capital quiz program
What is the +k+ called? How exactly does it work? I'm a big confused on that... Stephanie Quiles Sent from my iPhone > On Jun 2, 2015, at 12:17 PM, Peter Otten <__pete...@web.de> wrote: > > Alan Gauld wrote: > >>> On 02/06/15 15:15, Peter Otten wrote: >>> >>> Not an optimization, but if the user enters neither Y nor N you might ask >>> again instead of assuming Y. >> >> He does. He only breaks if the user enters N >> >>>> choice = input('Do you want to play again y/n: ') >>>> if choice.upper() == 'N': >>>> print('end of game') >>>> break >>>> elif choice.upper() != 'Y': >>>> print("invalid choice") >> >> Y goes round again silently. >> Anything other than Y or N prints the error then tries again. > > ... with the next state. I meant that instead the question "Do you want to > play again y/n:" should be repeated until there is a valid answer, either y > or n. > > Current behaviour: > > $ python capitals.py > Enter the capital of Mississippi :Jackson > Correct > Do you want to play again y/n: x > invalid choice > Enter the capital of Oklahoma : > ... > > So "x" is a synonum for "n". > > Suggested behaviour: > > $ python capitals.py > Enter the capital of Mississippi :Jackson > Correct > Do you want to play again y/n: x > invalid choice > Do you want to play again y/n: z > invalid choice > Do you want to play again y/n: n > end of game > ... > > > ___ > 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] create class Pet
Hello, Having trouble figuring out why this program is not running. could someone please take a look and see where I am going wrong? Here is the error message i am getting : /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/PycharmProjects/untitled3/pets.py Traceback (most recent call last): File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 2, in def main(get_name=name): NameError: name 'name' is not defined Process finished with exit code 1 Thanks Code is below: # __author__ = 'stephaniequiles' # write a class named Pet should include __name, __animal_type, __age class Pet: # pet class should have an __init__ method that creates these attributes. def __init__(self, name, animal_type, age): self.__name = 'name' self.__animal_type = 'animal_type' self.__age = 'age' def set_name(self, name): self.__name = 'name' def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get_age(self): return self.__age # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type # get_age # write a program that creates an object of the class and prompts the use to enter # name, type, age of their pet. # data should be stored as objects attributes. # use objects accessor methods to retrieve the pet's name, type and age # display data on screen # __author__ = 'stephaniequiles' def main(): name = input('what is the name of the pet?: ') animal_type = ('Please enter a type of pet: ') age = int(input('Enter age of pet: ')) self.get_name(name, animal_type, age) print('This will be saved to file.') print('Here is a the data you entered: ') print('Pet Name: ', pet.get_name) print('Animal Type:', pet.get_animal_type) print('Age: ', pet.get_age) main() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] create class Pet
> sorry this is the correct error. it allows me to enter name and age but then > i get the message: /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/PycharmProjects/untitled3/pets.py what is the name of the pet?: riley Please enter a type of pet: cat Enter age of pet: 11 Traceback (most recent call last): File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 15, in main() File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 7, in main pet.get_name(name, animal_type, age) AttributeError: 'module' object has no attribute 'get_name' Process finished with exit code 1 class Pet: # pet class should have an __init__ method that creates these attributes. def __init__(self, name, animal_type, age): self.__name = "name" self.__animal_type = "animal_type" self.__age = "age" def set_name(self, name): self.__name = "name" def set_type(self, animal_type): self.__animal_type = animal_type def set_age(self, age): self.__age = age def get_name(self): return self.__name def get_animal_type(self): return self.__animal_type def get_age(self): return self.__age # create methods, set_name , set_animal_type, set_age, get_name, get_animal_type # get_age # write a program that creates an object of the class and prompts the use to enter # name, type, age of their pet. # data should be stored as objects attributes. # use objects accessor methods to retrieve the pet's name, type and age # display data on screen # __author__ = 'stephaniequiles' import pet def main(): name = input("what is the name of the pet?: ") animal_type = input("Please enter a type of pet: ") age = input("Enter age of pet: ") pet.get_name(name, animal_type, age) print("This will be saved to file.") print("Here is a the data you entered: ") print("Pet Name: ", pet.get_name) print("Animal Type:", pet.get_animal_type) print("Age: ", pet.get_age) main() > On Jun 16, 2015, at 3:49 PM, Mark Lawrence wrote: > > On 16/06/2015 17:45, Stephanie Quiles wrote: >> Hello, Having trouble figuring out why this program is not running. could >> someone please take a look and see where I am going wrong? Here is the error >> message i am getting : >> /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 >> /Users/stephaniequiles/PycharmProjects/untitled3/pets.py >> Traceback (most recent call last): >> File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 2, >> in >> def main(get_name=name): >> NameError: name 'name' is not defined >> >> Process finished with exit code 1 >> >> Thanks >> >> Code is below: >> >> >> # __author__ = 'stephaniequiles' >> >> # write a class named Pet should include __name, __animal_type, __age >> >> class Pet: >> # pet class should have an __init__ method that creates these attributes. >> def __init__(self, name, animal_type, age): >> self.__name = 'name' >> self.__animal_type = 'animal_type' >> self.__age = 'age' >> >> def set_name(self, name): >> self.__name = 'name' > > Further to Alan's answer the above methods are wrong. You're setting all the > instance variables to strings instead of the actual variable names. Get rid > of the single quotes. > > -- > My fellow Pythonistas, ask not what our language can do for you, ask > what you can do for our language. > > Mark Lawrence > > ___ > 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] create class Pet
You are right I don't understand functions very well still. This prompts the next question is there a book or online resource that you suggest I look at? Right now I am using a text book provides by the instructor called Starting Out With Python 3rd ed. Anything you can suggest I reference would be appreciated. I will review the code when I get home. Thanks Stephanie Quiles Sent from my iPhone > On Jun 17, 2015, at 3:40 AM, Alan Gauld wrote: > > On 16/06/15 21:15, Stephanie Quiles wrote: >>> sorry this is the correct error. > > >> File "/Users/stephaniequiles/PycharmProjects/untitled3/pets.py", line 7, >> in main >> pet.get_name(name, animal_type, age) >> AttributeError: 'module' object has no attribute 'get_name' > > There are several errors in this line, all of which suggest > you don't really understand what you are doing with functions, # > classes and objects. You need to re-read your tutorial material > more closely. > > 1) Starting with the reported error. > You called > > pet.get_name(...) > > pet is the name of your file so Python sees that as a module. > But get_name is a method of your Pet class. The class name is > captalized and case matters in Python. 'Pet' is not the > same as 'pet' That's why it says there is no such module > attribute as get_name. > > 2) The method call has 3 arguments: name, type and age. > But your method definition has no attributes (apart > from the obligatory self). When you call a function > (or method) you must only include the arguments that > the function definition expects. So your call to > get_name() would have failed even if you had not > misspelled pet. > > 3) get_name() returns a string value - the __name of the pet. > You call get_name() but do not use or store the result so > it is thrown away. I suspect you meant to print the result > so you should have written something like: > print ( my_pet.getname() ) > > 4) get_name() is a method of the class Pet. That means > you should call it as an attribute of an object which > is an instance of Pet. That is, you must create an > instance of Pet before you try to use any of its methods. > You did not create any instances. Interestingly, your > __init__() method does take the 3 parameters that > you tried to pass to get_name(). This means that > you could have replaced the get_name() call with > > my_pet = Pet(name, animal_type, age) > > Now that we have dealt with that line lets move on > to the rest of your main function... > > You have several lines like: > > print("Pet Name: ", pet.get_name) > > The problem here is that you are passing the method name > into the print function. You are not *calling* the method. > Also you are using the module name (pet) to access get_name, > but it needs to be an instance of Pet - see above. > > To do all that you must use abn instance and put parentheses > after the method name, so it should look like: > > print("Pet Name: ", my_pet.get_name() ) > > The final set of errors have already been highlighted by Mark. > Namely where you set attribute values in the class methods > you are creating strings instead of using the variables. > ie you are writing > > def set_name(self, name): > self.__name = "name" > > where it should be > > def set_name(self, name): > self.__name = name > > with no quote signs. > > If you make all those changes I think it should work. > However, given the number and nature of the errors, I cannot > help but think you need to go back and re-read your > tutorial material. Details are very important in programming > and you seem to still be confused about naming, function definitions and > calling and the relationship between classes and objects/instances. > >> >> Process finished with exit code 1 >> >> class Pet: >> # pet class should have an __init__ method that creates these attributes. >> def __init__(self, name, animal_type, age): >> self.__name = "name" >> self.__animal_type = "animal_type" >> self.__age = "age" >> >> def set_name(self, name): >> self.__name = "name" >> >> def set_type(self, animal_type): >> self.__animal_type = animal_type >> >> def set_age(self, age): >> self.__age = age >> >> def get_name(self): >> return self.__name >> >> def get_animal_type(self): >> return self.__animal_type
[Tutor] GUI program
Hello, i am attempting to create a GUI program using Python 3.4. please see the pasted code below. Why is nothing showing up? i am using Pycharm to run the program to see what it does and it says there are no errors but it does not show me an output. please let me know where i am falling short on this. Thank you __author__ = 'stephaniequiles' """ Write a GUI program that displays your name and address when a button is clicked. when the user clicks the 'show info' button, the program should display your name and address, as shown in the sketch.""" import tkinter class AddressGUI: def __init__(self): self.main_window = tkinter.Tk() self.top_frame= tkinter.Frame() self.mid_frame= tkinter.Frame() self.bottom_frame = tkinter.Frame() self.name_label= tkinter.Label(self.top_frame,\ text='Steven Marcus') self.name_label.pack(side='left') self.value = tkinter.StringVar() self.address_label = tkinter.Label(self.mid_frame,\ text='274 Baily Drive Waynesville, NC 27999') self.address_label.pack(side='left') self.show_button = tkinter.Button(self.bottom_frame,\ text="show info",\ command=self.showinfo) self.quit_button = tkinter.Button(self.bottom_frame,\ tect ='Quit',\ command=self.main_window.destroy) self.show_button.pack(side='left') self.quit_button.pack(side='left') self.top_frame.pack() self.mid_frame.pack() self.bottom_frame.pack() tkinter.mainloop() def showinfo(self): name = 'Steven Marcus' address = '274 Baily Drive Waynesville, NC 27999' info = name + address allinfo = AddressGUI() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] the big o
Hello, I am trying to figure this out but i do not understand any of it. the question asks give the big-o performance of the following code fragment: for i in range(n): for j in range(n): k = 2 + 2 i am not sure how i am supposed to figure this out. i have been reading the book, looking at blog posts and watching online tutorials and i still cannot grasp the big-o. please keep in mind that i have never taken a calc course and that i am a complete novice to programming, even more so to python. Any help would be greatly appreciated. I am pretty much on my own with these since my fellow students are unwilling to help me with anything since they are far more advanced than i am. Thank you, Stephanie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] the big o
Hi Jason, I took Intro to Programming at Albright College and we used Starting Out with Python 3rd ed. Right now I am taking Data Structure and Analysis and we are using This book : http://interactivepython.org/runestone/static/pythonds/BasicDS/InfixPrefixandPostfixExpressions.html Thanks Alan for your explanation. The problem with me getting these terms and things is in part due to the accelerated rate in which my classes run. I cant possible master anything in a 6-8 week course, especially when I have zero programming background and about 2/3 of the class does... So I'll fake it till I make it. Thanks a lot. I think I have a very basic understanding of Big O right now. But if someone could please make it a little easier to figure out postfix and infix? My homework assignment asks me to convert from infix to postfix. I got a very very basic understanding of this but when the problems get a little more involved I get totally lost. Here is an example A+B/C*D-E+F I thought it was something like ABC/+ cd*ef+-?? That's probably wrong but I am trying Stephanie Quiles Sent from my iPhone > On Jul 28, 2015, at 10:07 AM, Joseph Lee wrote: > > Hi Stephanie, > I'm wondering which courses you were introduced to Python and which book you > are using. I do understand how it might be difficult to understand this > concept, especially for someone who is a complete novice to algorithm > analysis where Big O shows up. > I'll answer you inline. > > -Original Message- > From: Tutor [mailto:tutor-bounces+joseph.lee22590=gmail@python.org] On > Behalf Of Quiles, Stephanie > Sent: Monday, July 27, 2015 6:30 PM > To: python tutor > Subject: [Tutor] the big o > >> Hello, > >> I am trying to figure this out but i do not understand any of it. the > question asks give the big-o performance of the following code fragment: > >> for i in range(n): >>for j in range(n): >>k = 2 + 2 > >> I am not sure how i am supposed to figure this out. i have been reading > the book, looking at blog posts and watching online tutorials and i still > cannot grasp the > big-o. please keep in mind that i have never taken a calc > course and that i am a complete novice to programming, even more so to > python. Any help would be greatly appreciated. I am pretty much on my own > with these since my fellow students are unwilling to help me with anything > since they are far more advanced than i am. > >> Thank you, > >> Stephanie > > JL: Okay, let's start from the very beginning. First, before talking about > what Big O means, it is important to go over some basics: > > Big O comes from algorithm analysis, a branch of computer science dealing > with coming up with solutions to problems and analyzing them. In our > context, an algorithm is a list of precise steps to solve a problem. For > example, using Alan's searching example, it could be paraphrased as follows: > > Suppose I have a list of items and I want to search for a specific item. How > would I do this? > > If your friend was asked to do this, what would he or she do? Obviously, > your friend will search for items one at a time until what you are looking > for is found. You or your friend could say: > > First, have a list of items. Then examine one item at a time until what I > want is found. > > This is a description of an algorithm: precise steps to be followed. The > above paragraph describes searching algorithms - given a list of items, a > computer (or a machine whether it's physical or virtual) will go through the > list and compare each item to the target it is looking for. There are more > elegant ways of doing it that mimics how humans perform specific searches, > including the one that Alan described (called logarithmic search, commonly > introduced as binary search in earlier courses). > > Once you have an algorithm, it is time to think about how to implement, or > write it in Python. This is where you need to become skilled at translating > paper instructions to something that Python can understand. In case of > Alan's linear search example, one way to put it is: > > For item in items: >if item == target: >position = items.index(item) > return position > > Essentially, this code fragment says to perform a linear search on a list of > items. As part of learning about Big O and algorithms, it is important to > practice how to translate between English and Python: translate a > description of an algorithm in English to Python by implementing it, and > understand what the code fragment does. > > Now the topic at hand: For decades, computer scientists and software > developers were asking themselves, "
[Tutor] infix to postfix exponent handling
My assignment calls for the program to be edited to handle the “^” symbol. the hint is that it should be done with just one line of code. Here is the assignment: Modify the infix-to-postfix algorithm to handle exponentiation. Use the ^ symbol as the input token for testing. Q-14: Modify the infixToPostfix function so that it can convert the following expression: 5 * 3 ^ (4 - 2) Here is the code : class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0) def peek(self): return self.items[0] def size(self): return len(self.items) def infixToPostfix(infixexpr): prec = {} prec["^"] = 3 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList) print(infixToPostfix("5 * 3 ^ (4 - 2)")) print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )”)) this is the lien that i added: prec["^"] = 3 i also replaced the infixtopostfix to the problem: ("5 * 3 ^ (4 - 2)”)) here is the error I am getting : Traceback (most recent call last): File "/Users/stephaniequiles/Downloads/Listings/listing_3_7.py", line 53, in print(infixToPostfix("5 * 3 ^ (4 - 2)")) File "/Users/stephaniequiles/Downloads/Listings/listing_3_7.py", line 45, in infixToPostfix (prec[opStack.peek()] >= prec[token]): KeyError: '(4' Process finished with exit code 1 Please advise. not sure where i am failing with this Thanks!! Stephanie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] email validation
Hello All, I have a python assignment. I have to make sure that when user inputs email that the program verifies that the address as a @ and a “.” in the entry or else return an invalid email error. A Very rudimentary form of email validation. i cannot get the program to work. Here is what i have so far: import pickle def main(): cont = True emails = open_existing_file() print(emails) # Get data... while cont: name = input("Enter your name :") email1 = input("Enter your email address :") email2 = input("Enter alternate email address :") phone = input("Enter your phone number :") contactlist = [email1,email2,phone] emails[name] = contactlist c = input("Enter another? [y]/n :") if c == 'n' or c == 'N': cont = False def email1(): if '@' not in email and '.' not in email: print('email needs @ and . at the same time') # Save data... outfile = open("emails.dat","wb") pickle.dump(emails,outfile) outfile.close print("Your data has been saved to emails.dat") def open_existing_file(): # returns an empty dictionary or one that has data from a file emails = {} # Load the dictionary try: infile = open("emails.dat","rb") emails = pickle.load(infile) infile.close() except: print("No file to open. Starting with no data.") return emails main() Here is the error message : /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/Downloads/emailsupdate.py Traceback (most recent call last): File "/Users/stephaniequiles/Downloads/emailsupdate.py", line 42, in main() File "/Users/stephaniequiles/Downloads/emailsupdate.py", line 6, in main emails = open_existing_file() UnboundLocalError: local variable 'open_existing_file' referenced before assignment Process finished with exit code 1 not sure why it is not recognizing that the open_existing_file() function needs to be returned to the “emails” variable? I am guessing it has to do with my syntax? any suggestions, please? Thank you Stephanie Quiles ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] email validation
> On Aug 1, 2015, at 5:17 PM, Danny Yoo wrote: > Thank you, the program is now working but when the email is not entered > correctly it doesn’t make me go back and re-enter, it spits out an error code > but then moves on to the next field . Here is the code: import pickle def main(): cont = True emails = open_existing_file() print(emails) # Get data... while cont: name = input("Enter your name :") email1 = input("Enter your email address :") if '@' not in email1 or '.' not in email1: print('email needs @ and . at the same time') cont = False email2 = input("Enter alternate email address :") if '@' not in email2 or '.' not in email2: print('email needs @ and . at the same time') cont = False phone = input("Enter your phone number :") contactlist = [email1, email2, phone] emails[name] = contactlist c = input("Enter another? [y]/n :") if c == 'n' or c == 'N': cont = False def email1(): if '@' not in email1 or '.' not in email1: print('email needs @ and . at the same time') def email2(): if '@' not in email2 or '.' not in email2: print('email needs @ and . at the same time') # Save data... outfile = open("emails.dat", "wb") pickle.dump(emails, outfile) outfile.close print("Your data has been saved to emails.dat") def open_existing_file(): # returns an empty dictionary or one that has data from a file emails = {} # Load the dictionary try: infile = open("emails.dat", "rb") emails = pickle.load(infile) infile.close() except: print("No file to open. Starting with no data.") return emails main() This is the output: /Library/Frameworks/Python.framework/Versions/3.4/bin/python3.4 /Users/stephaniequiles/Downloads/emailsupdate.py {'maria': ['steph', 'sst', '33ed'], 'Jim': 'ththth@ththt', 'Ton': 'tomtomtomt@tomtom', 'Bob': 'b...@bob.com'} Enter your name :sfdgh Enter your email address :sdfkj...@syesgd.com Enter alternate email address :sdfghfds@Asfdgfdcod email needs @ and . at the same time Enter your phone number : I must have something missing but can’t remember what it is. Thanks for your help! Stephanie > On Sat, Aug 1, 2015 at 2:03 PM, Válas Péter wrote: >> Hi Stephanie, >> >> the function should be defined first, and used after. So put it before >> main(). > > > > It's perfectly legal and ok to say: > > ### > def main(): > callHelper() > > def callHelper(): > print("I am the helper") > > main() > ### > > > > Rather, the problem is due to putting the helper function accidentally > nested *within* main: > > > def main(): > callHelper() > >def callHelper(): > print("I am the helper but can't be called until after the > definition") > > main() > # > > > > One technical way to "fix" this is to move it up a bit: > > # > def main(): >def callHelper(): > print("I am the helper but can't be called until after the > definition") > >callHelper() > > main() > # > > > > But this is usually unsatisfactory because we can't then access > callHelper from outside. There can be valid reasons to hide function > definitions at times, but this isn't one of those situations. > > > Válas's suggestion, to move the helper's definition above, does make sense: > > # > def callHelper(): > print("I am the helper but can't be called until after the definition") > > def main(): >callHelper() > > main() > # > > but a key point needs to be made: don't just move it *up*, but move it *out*. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] infix to postfix eval
hello again! I have to unify these methods so that i can enter an infix, convert it to a postfix and then solve. Here are the methods method #1 is : class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.insert(0,item) def pop(self): return self.items.pop(0) def peek(self): return self.items[0] def size(self): return len(self.items) def infixToPostfix(infixexpr): prec = {} prec["^"] = 4 prec["*"] = 3 prec["/"] = 3 prec["+"] = 2 prec["-"] = 2 prec["("] = 1 opStack = Stack() postfixList = [] tokenList = infixexpr.split() for token in tokenList: if token in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" or token in "0123456789": postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return " ".join(postfixList) print(infixToPostfix("5 * 3 ^ ( 4 - 2 )")) print(infixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )”)) method #2 is : def postfixEval(postfixExpr): operandStack = Stack() tokenList = postfixExpr.split() for token in tokenList: if token in "0123456789": operandStack.push(int(token)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token,operand1,operand2) operandStack.push(result) return operandStack.pop() def doMath(op, op1, op2): if op == "^": return op1 ** op2 if op == "*": return op1 * op2 elif op == "/": return op1 / op2 elif op == "+": return op1 + op2 else: return op1 - op2 basically i have to make a main function and somehow unify these two so that user can input an infix, then convert and print the postfix and then solve and print the final calculation. Here is the assignment as written by the instructor: Try to do program #3 from P.144. We began this in class. Here’s what you need to do. We will be using Listings 3.7 and 3.8. First make sure that you can get Listing 3.7 to work. Just test some strings. Note that the code in the text expects the input to be “strings” of letters, each character separated by a space, and uses the “uppercase” statement in its definition. Second make sure that you can get Listing 3.8 to work. Just test some strings. This one you will test with digits. Third, now what you’ll need to do to answer program #3 is to get Listing 3.7 to handle digits rather than letters. This should not require a great deal of change to the code. Look at how Listing 3.8 handles the digits and see if you can duplicate that. Test some simple examples (limit the values from 0 – 9) with each character (token) separated by a space. For example, if we received the input of “3 + 4 * 2”, we would output 3 4 2 * +. (NOTE THE SPACES.) Fourth, once you have this working, you will simply feed this result to Listing 3.8 and the evaluated result should be printed. For example, if we received the input of “3 + 4 * 2”, we would output 3 4 2 * + and also output the value of 11. Below is a sample of what you could show. Keep it simple. print ("This program will accept an infix expression,") print ("convert to postfix, and evaluate the result.") print ("No input validation will be performed.") print ("Please enter the infix expression correctly, as follows:") print ("Enter only numbers 0-9") print ("Separate each character with a space") print ("You can use the following operators: ( ) + - * / ") print ("For example: ( 8 + 2 ) * ( 2 + 4 )") Here’s how a sample run would look. This program will accept an infix expression, convert to postfix, and evaluate the result. No input validation will be performed. Please enter the infix expression correctly, as follows: Enter only numbers 0-9 Separate each character with a space You can use the following operators: ( ) + - * / For example: ( 8 + 2 ) * ( 2 + 4 ) Enter infix string: ( 8 + 2 ) * ( 2 + 4 ) The postfix string is: 8 2 + 2 4 + * The final result is: 60 Thanks! ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] email validation
So i took your advice and i am much closer. however, when i type in an invalid address it loops back to the first prompt and asks you to enter your name: I want it to ask you to re-enter your email address instead how would i go about this? Here is the corrected code : import pickle def main(): cont = True emails = open_existing_file() print(emails) # Get data... while cont: name = input("Enter your name: ") email1 = input("Enter your email address: ") if not is_good_address(email1): continue email2 = input("Enter an alternate email address: ") if not is_good_address(email2): continue phone = input("Enter your phone number: ") contactlist = [email1, email2, phone] emails[name] = contactlist c = input("Enter another? [y]/n: ") if c == 'n' or c == 'N': cont = False # Save data... outfile = open("emails.dat", "wb") pickle.dump(emails, outfile) outfile.close print("Your data has been saved to emails.dat") def is_good_address(addr): if '@' not in addr or '.' not in addr: print('email needs @ and . at the same time') return False else: return True def open_existing_file(): # returns an empty dictionary or one that has data from a file emails = {} # Load the dictionary try: infile = open("emails.dat", "rb") emails = pickle.load(infile) infile.close() except: print("No file to open. Starting with no data.") return emails main() Thanks Stephanie > On Aug 2, 2015, at 10:12 AM, Alan Gauld wrote: > > On 02/08/15 09:31, Alan Gauld wrote: > >> them outside the main block and use them in your tests. In that case you >> only need one function which I'd call something like test_email() > > Ahem. Or you could call it is_good_address() of course! Oops! > >> def is_good_address(addr): >> if '@' not in addr or '.' not in addr: >> print('email needs @ and . at the same time') >> return False >> else: return True > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@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] find pickle and retrieve saved data
how do i go about being able to add a feature to search for individual entries that have been saved into that dictionary or else tell me that the name I entered is not found? Here is the code that i have so far… import pickle def main(): infile = open("emails.dat", "rb") emails = pickle.load(infile) infile.close() name_search = input("Enter a name in the file for info: ") for name in emails: if name[0] == name_search: print("This is the info: ", info) return emails else: print("Entry not Found! Try again.") main() thanks for all the help and suggestions this is really helping me in trying to figure this out! Stephanie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] email validation
ok so i made a few corrections based on what you stated and moved the name variable out of the loop. however, now its doing the same thing with alternate email. if it is entered incorrectly, it goes back to email 1 and you have to re-enter it. i tried the nested loops but they were not working either. where should i insert them into the program to make it work? > On Aug 2, 2015, at 6:54 PM, Quiles, Stephanie > wrote: > > So i took your advice and i am much closer. however, when i type in an > invalid address it loops back to the first prompt and asks you to enter your > name: I want it to ask you to re-enter your email address instead how would i > go about this? > > Here is the corrected code : > > import pickle > > > def main(): >cont = True >emails = open_existing_file() >print(emails) > ># Get data... >while cont: >name = input("Enter your name: ") >email1 = input("Enter your email address: ") >if not is_good_address(email1): continue >email2 = input("Enter an alternate email address: ") >if not is_good_address(email2): continue >phone = input("Enter your phone number: ") >contactlist = [email1, email2, phone] >emails[name] = contactlist >c = input("Enter another? [y]/n: ") >if c == 'n' or c == 'N': >cont = False > ># Save data... >outfile = open("emails.dat", "wb") >pickle.dump(emails, outfile) >outfile.close >print("Your data has been saved to emails.dat") > > > def is_good_address(addr): >if '@' not in addr or '.' not in addr: >print('email needs @ and . at the same time') >return False >else: >return True > > > def open_existing_file(): ># returns an empty dictionary or one that has data from a file >emails = {} ># Load the dictionary >try: >infile = open("emails.dat", "rb") >emails = pickle.load(infile) >infile.close() >except: >print("No file to open. Starting with no data.") >return emails > > > main() > > > Thanks > > Stephanie > > >> On Aug 2, 2015, at 10:12 AM, Alan Gauld wrote: >> >> On 02/08/15 09:31, Alan Gauld wrote: >> >>> them outside the main block and use them in your tests. In that case you >>> only need one function which I'd call something like test_email() >> >> Ahem. Or you could call it is_good_address() of course! Oops! >> >>> def is_good_address(addr): >>> if '@' not in addr or '.' not in addr: >>> print('email needs @ and . at the same time') >>> return False >>> else: return True >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.amazon.com/author/alan_gauld >> Follow my photo-blog on Flickr at: >> http://www.flickr.com/photos/alangauldphotos >> >> >> ___ >> Tutor maillist - Tutor@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 maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] find pickle and retrieve saved data
I'm trying to tell it to print everything under that particular name. I would have to def info, correct? But set it equal to what to make it work? Stephanie Quiles Sent from my iPhone > On Aug 3, 2015, at 3:12 AM, Alan Gauld wrote: > >> On 03/08/15 04:04, Quiles, Stephanie wrote: >> >> def main(): > ... >> name_search = input("Enter a name in the file for info: ") >> >> for name in emails: >> if name[0] == name_search: >> print("This is the info: ", info) > > What is info? Is it supposed to be name? or name[1:]? > Its not set anywhere in your code. > >> return emails > > Notice the return is outside the if block. > So you always return on the first element of the for loop. > >> else: >> print("Entry not Found! Try again.") > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my photo-blog on Flickr at: > http://www.flickr.com/photos/alangauldphotos > > > ___ > Tutor maillist - Tutor@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] palindrome using stack and queue
Hello , i have to write a palindrome tester using a stack and a queue. You will need to handle strings that may have upper/lower case letters and white space between the letters. We will not include punctuation marks in our strings. Here’s an example: The user inputs otto, you read the string in, you print out something like “otto is a palindrome.” The user inputs r a DAr, you output “r aDAr is a palindrome.” here iw the code i originally had which worked: def main(): my_str = input("Enter a string: ") my_str2 = [c for c in my_str.lower() if c.isalpha()] rev_str = reversed(my_str2) # check if the string is equal to its reverse if list(my_str2) == list(rev_str): print(my_str,"is a palindrome") else: print(my_str, "is not a palindrome") if __name__ == '__main__': main() But they want us to use a stack and a queue so how would i go about doing that? Here are the stack and queue classes class Stack: """Top of the stack is at the end of the list""" def __init__(self): self._items = [] def push(self, obj): self._items.append(obj) def pop(self): return self._items.pop() def peek(self): return self._items[-1] def isEmpty(self): return len(self._items) == 0 def __len__(self): return len(self._items) def __str__(self): return "bottom " + str(self._items) + " top" def reverse(self): return self._items.reverse() stack = Stack() stack2 = Stack() class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) any help is always appreciated stephanie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] find pickle and retrieve saved data
I am still struggling with this one. Here is my code to retrieve data from emails.dat file def main(): found = False search = input("Enter a name in the file for info: ") infile = open("emails.dat", "r") name = infile.readline() while name != '': email1, email2, phone, phone2 = (infile.readline()) name = name.rstrip("\n") if name == search: print("name: ", name) print("Email1, alternate email, phone, alternate phone", email1, email2, phone, phone2) print() found = True name = infile.readline() infile.close() if not found: print("That name is not found in file.") main() This is the error i am getting: enter a name in the file for info: sarah Traceback (most recent call last): File "/Users/stephaniequiles/Downloads/findemails.py", line 28, in main() File "/Users/stephaniequiles/Downloads/findemails.py", line 9, in main name = infile.readline() File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/codecs.py", line 319, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte Process finished with exit code 1 > On Aug 3, 2015, at 8:13 AM, Quiles, Stephanie > wrote: > > I'm trying to tell it to print everything under that particular name. I would > have to def info, correct? But set it equal to what to make it work? > > Stephanie Quiles > Sent from my iPhone > >> On Aug 3, 2015, at 3:12 AM, Alan Gauld wrote: >> >>> On 03/08/15 04:04, Quiles, Stephanie wrote: >>> >>> def main(): >> ... >>>name_search = input("Enter a name in the file for info: ") >>> >>>for name in emails: >>>if name[0] == name_search: >>>print("This is the info: ", info) >> >> What is info? Is it supposed to be name? or name[1:]? >> Its not set anywhere in your code. >> >>>return emails >> >> Notice the return is outside the if block. >> So you always return on the first element of the for loop. >> >>>else: >>>print("Entry not Found! Try again.") >> >> -- >> Alan G >> Author of the Learn to Program web site >> http://www.alan-g.me.uk/ >> http://www.amazon.com/author/alan_gauld >> Follow my photo-blog on Flickr at: >> http://www.flickr.com/photos/alangauldphotos >> >> >> ___ >> Tutor maillist - Tutor@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] Fraction Class HELP ME PLEASE!
Hello All, I need to do the following assignment. I need to know how do i hard code an example for each of the operators I am implementing? What i have so far is below? He said he does not care if we plug in some numbers or if we have user input numbers, however I am unsure of how to write a program that tests each operator? Or can i write one that tests all of them? I don’t know where to start with this. Please help! We discussed implementing different operators in our Fraction class. Here is a link to some operators in Python (look at Section 10.3.1). https://docs.python.org/3/library/operator.html You may implement as many of these operators as you like (such as isub, itruediv, etc.) You MUST indicate in your header information which operators you are implementing, and you MUST hard code an example for each. def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom def __str__(self): if self.den == 1: return str(self.num) elif self.num == 0: return str(0) else: return str(self.num) + "/" + str(self.den) def simplify(self): common = gcd(self.num, self.den) self.num = self.num // common self.den = self.den // common` def show(self): print(self.num, "/", self.den) def __add__(self, otherfraction): newnum = self.num * otherfraction.den + \ self.den * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __sub__(self, otherfraction): newnum = self.num * otherfraction.den - \ self.den * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __mul__(self, otherfraction): newnum = self.num * otherfraction.num * \ self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __imul__(self, otherfraction): if isinstance(otherfraction): return self__mul__(otherfraction) def __iadd__(self, otherfraction): if isinstance(otherfraction): return self__iadd__(otherfraction) def __truediv__(self, otherfraction): newnum = self.num * otherfraction.num // self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __radd__(self, otherfraction): newnum = self.num * otherfraction.num // self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def getNum(self): return self.num def getDen(self): return self.den def __gt__(self, otherfraction): return (self.num / self.den) > (otherfraction.num / otherfraction.den) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fraction Class HELP ME PLEASE!
thanks Cameron! Here is what i have so far… new question… how do i test the iadd, imul, etc. operators? Hopefully this time the indents show up. And yes the beginning code came out of our text book I added on some functions myself but they give you a big chunk of it. I am hoping that this is what the professor was looking for. I want to add some more operators but am unsure how to put them in or test them? For example I want to add __ixor__, itruediv, etc. Any other suggestions would be great! Thanks def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm % oldn return n class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom def __str__(self): if self.den == 1: return str(self.num) elif self.num == 0: return str(0) else: return str(self.num) + "/" + str(self.den) def simplify(self): common = gcd(self.num, self.den) self.num = self.num // common self.den = self.den // common def show(self): print(self.num, "/", self.den) def __add__(self, otherfraction): newnum = self.num * otherfraction.den + \ self.den * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __sub__(self, otherfraction): newnum = self.num * otherfraction.den - \ self.den * otherfraction.num newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __mul__(self, otherfraction): newnum = self.num * otherfraction.num * \ self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __imul__(self, otherfraction): if isinstance(otherfraction): return self__mul__(otherfraction) def __iadd__(self, otherfraction): if isinstance(otherfraction): return self__iadd__(otherfraction) def __truediv__(self, otherfraction): newnum = self.num * otherfraction.num // self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __pow__(self, otherfraction): newnum = self.num * otherfraction.num ** self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def __radd__(self, otherfraction): newnum = self.num * otherfraction.num // self.den * otherfraction.den newden = self.den * otherfraction.den common = gcd(newnum, newden) return Fraction(newnum // common, newden // common) def getNum(self): return self.num def getDen(self): return self.den def __gt__(self, otherfraction): return (self.num / self.den) > (otherfraction.num / otherfraction.den) def __lt__(self, otherfraction): return (self.num / self.den) < (otherfraction.num / otherfraction.den) def __eq__(self, otherfraction): return (self.num / self.den) == (otherfraction.num / otherfraction.den) def __ne__(self, otherfraction): return (self.num /self.den) != (otherfraction.num /otherfraction.den) def __is__(self, otherfraction): return (self.num / self.den) is (otherfraction.num / otherfraction.den) def main(): F1 = Fraction(1,2) F2 = Fraction(2,3) print("F1 = ", F1) print("F2 = ", F2) print("Add Fractions: F1 + F2=", Fraction.__add__(F1, F2)) print("Subtract Fractions: F1 - F2=", Fraction.__sub__(F1, F2)) print("Multiply Fractions: F1 * F2=", Fraction.__mul__(F1, F2)) print("True Division with Fractions: F1 / F2=", Fraction.__truediv__(F1, F2)) print("Exponentiation with Fractions: F1 // F2=", Fraction.__pow__(F1, F2)) print("Is F1 Greater than F2?:", Fraction.__gt__(F1, F2)) print("Is F1 less than F2?:", Fraction.__lt__(F1, F2)) print("Is F1 Equal to F2?:", Fraction.__eq__(F1, F2)) print("Is F1 different than F2?:", Fraction.__ne__(F1, F2)) print ("Is F1 same as F2?:", Fraction.__is__(F1, F2)) print("Is:", Fraction.__iadd__(F1, F2)) if __name__ == '__main__': main() > On Aug 6, 2015, at 5:44 PM, Cameron Simpson wrote: > > On 06Aug2015 16:55, Quiles, Stephanie > wrote: >> I need to do the following assignment. I need to know how do i hard code an >> example for each of the operators I am implementing
Re: [Tutor] Fraction Class HELP ME PLEASE!
t("Is F1 different than F2?:", Fraction.__ne__(F1, F2)) print("Radd:", Fraction.__radd__(F1, F2)) print("Modulo of F1 and F2(this prints the remainder):", Fraction.__mod__(F1, F2)) print("Rshift( returns F1 shifted by F2:", Fraction.__rshift__(F1, F2)) if __name__ == '__main__': main() > On Aug 6, 2015, at 9:51 PM, Cameron Simpson wrote: > > On 06Aug2015 23:50, Quiles, Stephanie > wrote: >> thanks Cameron! Here is what i have so far… new question… how do >> i test the iadd, imul, etc. operators? > > Like the others, by firing them. You test __add__ by running an add between > two expressions: > > F1 + F2 > > You test __iadd__ by running the augmented add operation: > > F1 += F2 > > and so forth. The "i" probably comes from the word "increment" as the > commonest one of these you see is incrementing a counter: > > count += 1 > > They're documented here: > > https://docs.python.org/3/reference/datamodel.html#object.__iadd__ > > The important thing to note is that they usually modify the source object. So: > > F1 += F2 > > will modify the internal values of F1, as opposed to __add__ which returns a > new Fraction object. > >> Hopefully this time the >> indents show up. > > Yes, looks good. > >> And yes the beginning code came out of our text >> book I added on some functions myself but they give you a big chunk >> of it. > > I thought it looked surprisingly complete given your questions. It's good to > be up front about that kind of thing. Noone will think less of you. > >> I am hoping that this is what the professor was looking for. >> I want to add some more operators but am unsure how to put them in >> or test them? For example I want to add __ixor__, itruediv, etc. >> Any other suggestions would be great! > > Adding them is as simple as adding new methods to the class with the right > name, eg: > > def __iadd__(self, other): > ... update self by addition of other ... > > If you want to be sure you're running what you think you're running you could > put print commands at the top of the new methods, eg: > > def __iadd__(self, other): > print("%s.__iadd__(%s)..." % (self, other)) > ... update self by addition of other ... > > Obviously you would remove those prints once you were satisfied that the code > was working. > > Adding __itruediv__ and other arithmetic operators is simple enough, but > defining __ixor__ is not necessarily meaningful: xor is a binary operation > which makes sense for integers. It needn't have a natural meaning for > fractions. When you define operators on an object it is fairly important that > they have obvious and natural effects becauase you have made it very easy for > people to use them. Now, you could _define_ a meaning for xor on fractions, > but personally that is one I would not make into an operator; I would leave > it as a normal method because I would want people to think before calling it. > > The point here being that it is generally better for a program to fail at > this line: > > a = b ^ c # XOR(b, c) > > because "b" does not implement XOR than for the program to function but > quietly compute rubbish because the user _thoght_ they were XORing integers > (for example). > > Added points: make your next reply adopt the interleaved style of this > message, where you reply point by point below the relevant text. It makes > discussions read like conversations, and is the preferred style in this list > (and many other techincal lists) because it keeps the response near the > source text. Hand in hand with that goes trimming irrelevant stuff (stuff not > replied to) to keep the content shorter and on point. > > Other random code comments: > > [...snip: unreplied-to text removed here...] >> def gcd(m, n): >> while m % n != 0: >> oldm = m >> oldn = n >> >> m = oldn >> n = oldm % oldn >> return n > > It reads oddly to have a blank line in the middle of that loop. yes i > —Yes i think i put in that blank line in error i have corrected this in my code >> class Fraction: >> def __init__(self, top, bottom): >> self.num = top >> self.den = bottom >> >> def __str__(self): >> if self.den == 1: >> return str(self.num) >> elif self.num == 0: >> return str(0) >> else: >> return str(self.num) + "/" + str(self.den) > > While your __s
[Tutor] generate random number list and search for number
Hello everyone, Totally lost here. i have to create a program that asks user to input a value and then search for this value in a random list of values to see if it is found. Please see below for more detailed info. This problem requires you to use Python. We want to test out the ordered sequential search algorithm (Listing 5.2). Here’s how we will do it. We’ll need to have a routine that will generate some random numbers for us to place into a list. We’ll need to have a main function to drive the program. And we’ll need to have Listing 5.2 to actually run through our list to check for some value that we will be looking for. • First, we’ll need to import time to use the clock routine, and we’ll need to use the randrange routine from random. • Next, we’ll want our main( ) routine to call our createRandnums( ) routine and have this routine return our list of random numbers. Once we have the list, we’ll start the time clock and then pass the list, along with a value to “search for” to the orderedSequentialSearch() routine. This routine will return True or False as to whether or not it found the value in the list. Once the routine has completed, we’ll want to stop the clock in main. By subtracting “end – start”, we’ll be able to figure out how long the routine took to run. • The createRandnums routine will accept two parameters (how many numbers do you want, and what is the upper limit on the randrange routine), and this will simply run a loop to create the numbers and append them to a list. Once the list is complete, we can then use the sort routine on the list to arrange the numbers in order. The function will now return the sorted list to main( ). The main( ) routine will then record the clock time, call the search routine, receive back a True or False value from the search, stop the clock, and print our whether or not the value was in the list, and how long the search took. Some comments: why am I placing an upper bound on the randrange function? Well, consider if we want to generate 100 random numbers. If we run a loop 100 times, and each time through the loop we say something like x=randrange(1,101), we’ll be getting numbers from 1 – 100 inclusive. Now since the loop will run 100 times, and we’re only picking numbers from 1 – 100, we’re bound to get a number of repeats in the list. But if we, say, still run the loop 100 times, but we say x=randrange(1,300), we’ll still be generating 100 numbers (because the loop runs 100 times), but our spread of numbers should be better. We’ll need to figure out what value to look for in the list. We could ask the user to supply a value. You need to run the program for lists of 100, 1000, and 1 random numbers. A sample of how you might proceed follows: This program will generate a list of random numbers and test the sequential search algorithm Enter number of random integers to create in list: 100 Enter high-end random number to generate: 300 Enter number to find within list: 23 Here are the results: Item to find in random list of 100 values: 23 Sequential search: Found= False Time: 9.91956746077e-006 Here is the thing I am totally lost. Here is what i have so far… i created the main function and i ask the user to search for a number. I have assigned a range of 100. but here is one of my questions how do i assign to search within a value range(for example, i want the program to spit out 100 numbers between 1-300). how would i go about doing this? also how do i call the orderedSequentialSearch so i can check to see if value is in list? import time import random def orderedSequentialSearch(alist, item): pos = 0 found = False stop = False while pos < len(alist) and not found and not stop: if alist[pos] == item: found = True else: if alist[pos] > item: stop = True else: pos = pos + 1 return found def main(): list_range = 100 find = int(input("enter search number: ")) for num in range(1, list_range + 1): if random.randint(1, list_range) != 0: print(random.randint(1, list_range)) if random.randint(1, list_range) == find: print("Number Found.") else: print("not found") if __name__ == '__main__': main() Thank you so much in advance! Stephanie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Binary tree expressions
Hello! Not sure if anyone can help me with these or not but here it goes... I have to draw an expression tree for the following (a+b)*c-(d-e). I believe that the last move would go first in the tree so in this case you would subtract c after computing what d-e was. So my tree would start out looking like this : (-) / \ (+) (-) / \ / \ Sorry not sure how to better draw that... Is that correct so far? Where do I go from there if I am? The c is really throwing me off here. Here's the other tree: ((a+b) *c-(d-e)) ^ (f+g) So for this one you would do everything in the double parentheses first so a+b and d-e then multiple the sum of a+b by c Then I would subtract c from the sum of d-e. Then I would look at the right side and add f+g Finally I would calculate the sum of the left side ^ of the sum of f+g. So my tree would start with the ^ its children would be * (left child) + (right child) Is that right so far? Thanks for your help in advance! The tutorials online are not quite as complicated so I get consider once you start adding in more operators. Stephanie Quiles Sent from my iPhone ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Binary tree expressions
Yes I got the exact same thing. I figured it out once I sent the email. It is easier to start the tree from the bottom and work your way up than the way I was doing it which was from the top down. Thanks for your reply Alex, it was still helpful to get someone else's interpretation Stephanie Quiles Sent from my iPhone > On Aug 19, 2015, at 2:41 AM, Alex Kleider wrote: > >> On 2015-08-18 07:36, Quiles, Stephanie wrote: >> Hello! >> Not sure if anyone can help me with these or not but here it goes... >> I have to draw an expression tree for the following (a+b)*c-(d-e). >> I believe that the last move would go first in the tree so in this >> case you would subtract c after computing what d-e was. So my tree >> would start out looking like this : >> (-) >> / \ >> (+) (-) >> / \ / \ >> Sorry not sure how to better draw that... >> Is that correct so far? Where do I go from there if I am? The c is >> really throwing me off here. >> Here's the other tree: >> ((a+b) *c-(d-e)) ^ (f+g) >> So for this one you would do everything in the double parentheses >> first so a+b and d-e then multiple the sum of a+b by c >> Then I would subtract c from the sum of d-e. >> Then I would look at the right side and add f+g >> Finally I would calculate the sum of the left side ^ of the sum of f+g. >> So my tree would start with the ^ its children would be * (left child) >> + (right child) >> Is that right so far? > > Here's how I interpret the issue: > > (a+b)*c-(d-e) > > >- > / \ > * - >/ \ / \ > + c d e > / \ > a b > > ((a+b) *c-(d-e)) ^ (f+g) > >^ > / \ >- + > / \/ \ > * - fg >/ \ / \ > + c d e > / \ > a b > > If I understand the problem correctly, it seems to be a test of your ability > to understand precedence as in 'order of operation.' > > Parentheses trump any of the following. > ^ is highest of the ones involved here. > * is next (as is division but that's not involved here) > + and - are lowest. > > Hope this helps. > > > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Dividing a float derived from a string
Hi there, I have been posed with the following challenge: "Create a script that will ask for a number. Check if their input is a legitimate number. If it is, multiply it by 12 and print out the result." I was able to do this with the following code: input = raw_input("Insert a number: ") if input.isdigit(): print int(input) * 12 else: print False *However*, a colleague of mine pointed out that a decimal will return as False. As such, we have tried numerous methods to allow it to divide by a decimal, all of which have failed. Do you have any suggestions? Additionally, we are using 2.7, so that might change your answer. Thank you in advance for any help you can provide! -Stephanie ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dividing a float derived from a string
What else could I do in that testing portion that would allow for a decimal point? In order for a decimal to be True, it would have to accept both the digits and the decimal point. On Thu, Nov 20, 2014 at 10:36 PM, Danny Yoo wrote: > > I have been posed with the following challenge: > > > > "Create a script that will ask for a number. Check if their input is a > > legitimate number. If it is, multiply it by 12 and print out the result." > > > > I was able to do this with the following code: > > > > input = raw_input("Insert a number: ") > > if input.isdigit(): > > print int(input) * 12 > > else: > > print False > > > > However, a colleague of mine pointed out that a decimal will return as > > False. > > > Hi Stephanie, > > > Let me try to reproduce the problem you're reporting. I'll use the > interactive interpreter to help me. > > ## > >>> def f(): > ... n = raw_input("Insert a number:") > ... if n.isdigit(): > ... print int(n) * 12 > ... else: > ... print False > ... > >>> f() > Insert a number:10 > 120 > ### > > This is just slightly different than the program you've given me. I'm > replacing the variable name "input" with "n" to avoid potential > confusion, as there is a separate toplevel function called "input" in > the Python standard library. I'm also defining it as a function > called f(), just to make it easy for me to call it multiple times. > > > From the transcript above, I don't think I can see your problem yet. > It would be helpful to present a concrete example of a failure, to > make problem reproduction easier ... oh! Ah, I see what you're saying > now, I think. > > By "decimal", you probably don't just mean a number in base-10: you > may mean a number that has a _decimal point_. > > ## > >>> f() > Insert a number:3.14 > False > ## > > Is this the problem that you're considering? > > > If so, you should be able to handle this additional case without too > much trouble. You're learning how to use conditional statements, and > there's nothing that prevents you from expanding a branch that > considers one possible, to one that considers multiple possibilities: > > > if blah blah blah: > do some thing > elif blah blah blah: > do something else > else: > do something even more different > > > > You might check, additionally, to see if the string has a decimal > point, and then if it does, check that the left and right hand parts, > before and after the decimal, are all digits. > > > The find() method on strings can be helpful: > > > >>> s = "3141.5926" > >>> s.find(".") > 4 > > > If we know where the decimal is, we can start slicing up the string > into the left and right hand sides, using the string slicing operator: > > # > >>> s[0:4] > '3141' > >>> s[4:] > '.5926' > ## > > > So you can probably adjust your program to check for this possibility. > > > But to get this right in full generality is surprisingly a _lot_ more > tedious than you might initially expect. :P You should really check > with your instructor. When the problem says "number", what does the > problem mean? > > This is not as dumb a question as it sounds at first. As an example > of what can make this complicated: is "3/4" considered a number, > according to the problem statement? What about scientific notation? > If you're really pedantic (or have a sense of humor), you might even > ask yourself: how about roman numerals? > > So you really should touch base with your instructor. That will > probably help in clarifying what does appear to be a under-defined > term in the problem statement. > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Dividing a float derived from a string
Alan, I am getting a syntax error when I print the following: input = raw_input("Insert a number: ") try: print float(input) * 12 except: TypeError, ValueError: print False The "try" is coming up as red. Any idea why? On Fri, Nov 21, 2014 at 12:23 AM, Alan Gauld wrote: > On 20/11/14 21:20, Stephanie Morrow wrote: > > input = raw_input("Insert a number: ") >> if input.isdigit(): >> print int(input) * 12 >> else: >> print False >> >> /However/, a colleague of mine pointed out that a decimal will return as >> False. As such, we have tried numerous methods to allow it to divide by >> a decimal, all of which have failed. Do you have any suggestions? >> Additionally, we are using 2.7, so that might change your answer. >> > > The simplest solution is simply to convert it to a floating point number > instead of an integer. float() can convert both integer and floating > point(decimals) strings top a floating point number. > > But how do you deal with non numbers? > In Python we can use a try/except construct to catch anything that fails > the conversion: > > try: > print float(input)*12 > except: > print False > > But that's considered bad practice, it's better to put the > valid errors only in the except line like this: > > try: > print float(input)*12 > except TypeError, ValueError: > print False > > So now Python will look out for any ValueErrors and TypeErrors > during the first print operation and if it finds one will instead > print False. Any other kind of error will produce the usual Python error > messages. > > You may not have come across try/except yet, but its a powerful technique > for dealing with these kinds of issues. > > > -- > Alan G > Author of the Learn to Program web site > http://www.alan-g.me.uk/ > http://www.amazon.com/author/alan_gauld > Follow my phopto-blog on Flickr at: > 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] Dividing a float derived from a string
This one worked! Thank you very much! :D On Fri, Nov 21, 2014 at 3:14 AM, Adam Jensen wrote: > On Thu, 20 Nov 2014 21:20:27 + > Stephanie Morrow wrote: > > > Hi there, > > > > I have been posed with the following challenge: > > > > "Create a script that will ask for a number. Check if their input is a > > legitimate number. If it is, multiply it by 12 and print out the result." > > > > I was able to do this with the following code: > > > > input = raw_input("Insert a number: ") > > if input.isdigit(): > > print int(input) * 12 > > else: > > print False > > > > *However*, a colleague of mine pointed out that a decimal will return as > > False. As such, we have tried numerous methods to allow it to divide by > a > > decimal, all of which have failed. Do you have any suggestions? > > Additionally, we are using 2.7, so that might change your answer. > > > > Thank you in advance for any help you can provide! > > > > -Stephanie > > How about using a floating point type cast to convert the string to a > number within a try/except block? Maybe something like this: > > try: > x = float(input("Enter a number: ")) > print(x * 12) > except ValueError: > print("Not a valid number.") > > A little enhancement might involve removing any spaces from the string so > something like '5.6 e -3' will also be valid input. Like this: > > x = float(input("Enter a number: ").replace(' ','')) > ___ > 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] While Loops: Coin Flip Game
Thanks everyone! I should be using algorithms for even such programs at my level. The solution to reiterate the coin flip every time in the loop works. Thanks a lot! Dawn ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] While Loops: Coin Flip Game :p:
Greetings, As a thread starter, I thought I should write the rewritten code I got that others helped me get to, since this thread is still going on. # Coin Flips# The program flips a coin 100 times and then# tells you the number of heads and tailsimport random print "\a"print "\tWelcome to 'Coin Flipper!'"print "\nI will flip a coin 100 times and then tell you"print "the number of heads and tails!\n" # set the coinheadsCount = 0tailsCount = 0count = 1 while count <= 100:coin = random.randrange(2)if coin == 0: headsCount += 1else:tailsCount += 1count += 1 print "The number of heads was", headsCountprint "The number of tails was", tailsCount raw_input("\n\nPress the enter key to exit.") ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor