880 Posted Topics
Re: This will do it,try not to use bare except. except (<some error>, <another error>) You can also use `except IOError as error: print error` This will give you an error message with specific information about the caught exception. def file_exists(): while True: file_name = input("Enter a file name: ") try: … | |
Re: I have structured code better by using functions and some changes/corrections. This make it easier to test code and as you want start and stop the quiz. import random try: input = raw_input except: pass def all_quest(): '''All questions that can be used''' questions = [("Denis Glover wrote the poem … | |
Re: dean.ong.14 you have asked this qustion before. In the last post i tok time to structured and change code for a better soultion,did you even look at that? http://www.daniweb.com/software-development/python/threads/438691/import-random-failed..-please-help-me#post1886678 | |
Re: You can read direct from web,then you dont have to save and read from txt. This way you always get uppdatet info when website change. Example. from bs4 import BeautifulSoup #Use urllib to read html source code html = '<b>Mostly Cloudy, 50 F</b>' soup = BeautifulSoup(html) tag = soup.find('b') weather_info … | |
Re: [QUOTE]The code it is not tested, but should be worked [/QUOTE] You should test it because it is not working:-/ Here you have one way off do it. This is for python 3 that i think you use. Homework?,they may spot that you havent wirte this code(some smart shortcut in … | |
Re: > i have to copy paste my downloaded python packages for them to work? You do not copy/paste into site-packages folder yourself,you can but that's not the correct way(and it may not work). 3 methods: First the manual way. You download a packages extract to where-ever you want. From command … | |
Re: I think you have teacher with java background. There are really no need for getters/setters in both of these Class. Java programmers will often introduce private members, and then add getters and setters. This is evil; the attribute should have been public in the first place. Something to read [Python … | |
Re: That's not the whole traceback. Post whole traceback and code where traceback occur. | |
Re: As postet Lardmeister there are no official wxpython version for python 3 yet. The porting to python 3 is under way with Project Phoenix http://wiki.wxpython.org/ProjectPhoenix There are working version to test here. http://wxpython.org/Phoenix/snapshot-builds/ I have tested code over and it work in python 3.2. | |
Re: Yes a for loop and using comparison operators will work. Here is a hint. t = (20, 58, 70, 92, 98) A,F = 0,0 for mark in t: if mark < 60: F += 1 elif mark >= 90: A += 1 else: pass print('{} people got A\n{} people got … | |
Re: Based on previous post this is your output. [' 6', ' 4.5', ' 10', ' 4', ' 10'] #print(grade) #string_grades = str(grade) print([float(i) for i in grade]) # [6.0, 4.5, 10.0, 4.0, 10.0] print([i.strip() for i in grade]) #Clean string list ['6', '4.5', '10', '4', '10'] print(','.join([i.strip() for i in … | |
Re: > how would i convert the output to a list? with open('grade.txt') as in_file: lst = [i.split(',') for i in in_file] print(lst) If you don't want new line(\n),use `i.strip().split(',')` | |
Re: Schol-R-LEA you have a couple of mix up(typo error) `while sum in point: while result in point:` Should be `if sum in point:` no **in** statement in while loop. > Sorry I guess I should explain after the player rolls the sum of the two die that is 4,5,6,8,9,10 that … | |
Re: > it apears that when slicing with a negative step, the start and endpoints need to be reversed With negative step values,slicing will automatically step into in Alice in Wonderland reversed world. Like this we can look at vaules for `seq[start:stop:step]` >>> seq = '123456789' >>> slice(None,None,1).indices(len(seq)) #[::1] (0, 9, … | |
Re: If only value 0xFFFF has duplicate vaules,then `set()` would be fine. >>> lst = [0x123D, 0x844F, 0x33E9, 0xFFFF, 0xFFFF, 0xFFFF] >>> set(lst) set([4669, 13289, 33871, 65535]) If you want to keep duplicate vaules before 0xFFFF,lety say 0x844F and 0x844F. Then set() is not way. | |
Re: Yes `with open(...)` always close the file object when a iteration has finished. The advantage of using a with statement is that it is guaranteed to close the file no matter if nested block exits. If the nested block were to contain a return statement,or a continue or break statement, … | |
Re: Some additional info. Sometime it can convenient to not type in filename manually,but extract filename from url. Like when downloading more than one image or iterate over a list of url`s. `strip()` is not needed here for a single image. But can be needed if iterating over many url`s to … | |
Re: >>> m = 1 >>> oldVelocity = m.v Traceback (most recent call last): File "<interactive input>", line 1, in <module> AttributeError: 'int' object has no attribute 'v' As it say int object has no attibute 'v' The dot "." is the member access operator. Generally an object of a class … | |
Re: As posted over we need more info,like input data. Code use [Numpy](http://numpy.scipy.org/) and it use function add() and dot(). To see what these numpy function dos,look into numpy doc here is [add()](http://www.scipy.org/add?highlight=%28add%29) To test function so it work i guessed for a nested list as input data. from numpy import … | |
Re: > I get the step value counting down and was able to get the correct outcome but I am confused on the ending value (-1) and why that made it work. >>> start = 7 >>> stop = 1 >>> step = -1 >>> for r in range(start,stop,step): r 7 … | |
Re: > ok lets say every character is 3 digits. i want to read from file and print each character. How to do this? Something like this. def foo(filename, chunks): with open(filename) as f: numb_list = list(f.read()) return [numb_list[i:i+chunks] for i in range(0, len(numb_list), chunks)] lst = foo('data.txt', 3) for item … | |
Re: > But I believe that this is not the best way of writing the program. If you look at the while loop, the condition will never evaluate to true. Is this right? Yes that loop will not work,only way that will work if you guess right on first attempt. It … | |
Re: One more. with open('original.txt', 'a') as f_out: for i in range(0,2): text = raw_input("Enter message:") f_out.write('{}\n'.format(text)) | |
Re: To not use ugly "global",a more sensible solution would be to give functions arguments. def file_read(file_in): with open(file_in) as f: return(f.read()) def lowercase_letter(text): return text.lower() afile = file_read('savetonight.txt') print lowercase_letter(afile) jim.lindberg1 do not use norwegian name for function. | |
Re: It`s simpel with python to,and this is a python forum. @crishein14 save script in folder with files and run. import os, glob for numb,name in enumerate(glob.glob('*png')): os.rename(name, '{num:03d}.png'.format(num=numb)) | |
Re: A sample of input data would help,regex i use under may fail. > What I have been wresting with is getting my program to seemingly work with re.sub >>> import re >>> s = "abc [ k '0 ir e ] 123" >>> re.sub(r'\[.*\]', 'k_ir_e', s) 'abc k_ir_e 123' Remeber … | |
Re: > enjoy: Not so much to enjoy in that code. You dont read file line by line as @vimalya mention. With `read()` you read all file into memory. `del` we almost never need to use in python. Example. data.txt--> header 1 2 3 4 5 6 7 8 9 --- … | |
Re: A regex version,but i do like Vega soultion better. import re def is_alpha_space(name): name_nospace = ''.join((name.split())) if re.search(r"\W", name_nospace) or len(name_nospace) < 1: return False return True name = "Mark Zumkoff" print(is_alpha_space(name)) # True name = "Mark Zumkoff@" print(is_alpha_space(name)) # False name = " " print(is_alpha_space(name)) # False | |
![]() | Re: Some tips about your code GDICommander's Dont use "file" as an variable name,it`s a reseverd keyword for python. You dont need "import string" to use split. So it could look like this,wihout \r\n [CODE] my_file = open("example.csv", "rb") for line in my_file: l = [i.strip() for i in line.split(',')] print … |
Re: Can simplify code to this. import re from ftplib import FTP with open('params.txt.txt') as f: ip = re.search(r"IP.*'(.*)'", f.read()).group(1) ftp = FTP(ip) ftp.login() > I made the changes but it still is not working. Now getting Can be something like port,firewall problem or Active and Passive mode. http://stackoverflow.com/questions/3451817/python-ftplib-timing-out | |
Re: Fix your indentations(4 space) Python will not work with wrong indentations. Shall look like this. [CODE]def __init__(self, image, x, y): self.image= image self.xPos=x self.yPos=y self.dir=1[/CODE] If you dont know this,read some basic lesson before you try pygame. Like [URL="http://www.swaroopch.com/notes/Python"]byte og python[/URL] | |
Re: Colons(:) are basic and important in python. Other languages use `{ }` or other method to indicate/use a code block. Python use `indentation` after colons(:) to indicate/use a code block. word = 'hi' if word == 'hi': print'Now this block get executed an word is equal to hi' else: print'Now … | |
Re: Dont use variable name as `sum` and `file`,these word are use by python. So my_file is ok because it not used by python an give a NameError. >>> sum <built-in function sum> >>> file <type 'file'> >>> my_file Traceback (most recent call last): File "<interactive input>", line 1, in <module> … | |
Re: > What is the most Pythonic way? Not to typecheck. Need to know the type of an object? Let me make a brief argument: **No, you don't.** Just use the object as if it was whatever you expect it to be, and handle any errors that result. http://www.siafoo.net/article/56 > @S.Lott … | |
Re: Did you read my post in your last thread? http://www.daniweb.com/software-development/python/threads/428603/python-delete-str-from-file | |
Re: > How do you make Python delete a string or a number (in this case, .0) from a file? Example: Here many think about this in a wrong way. The way you do is not deleting from orgnial file. You do changes that is needed and then you write result … | |
Re: The best way is to always use raw string(`r`) when give path in windows. There is also an option to use `\\` or `/`. So this do not work. `os.chdir('C:\test')` This work. os.chdir(r'C:\test') os.chdir('C:\\test') os.chdir('C:/test') The reason why is this way,is that a singel backslashes(`\`) in python can(do) get read … | |
Re: Or shorten ZZucker function down to this. All you need to know if it`s True or False. def palindrome(mystr): return mystr.lower() == mystr[::-1].lower() mystr = "racecar" print palindrome(mystr) | |
Re: You are getting the memory adress of object. class Foo(object): def bar(self): return 'Hello' Test class. >>> obj = Foo() >>> print obj <__main__.Foo object at 0x0356B110> >>> print obj.bar <bound method Foo.bar of <__main__.Foo object at 0x0356B110>> >>> print obj.bar() Hello As you see until a make correct call … | |
Re: I only use BeautifulSoup or lxml,because they are by far the two best parser for python. Can show you on way with BeautifulSoup. `soup.find_all('router')` find all ruter tag,i take out router 1 `router_tag[0]` Then put id and ip text in a dictionary. from bs4 import BeautifulSoup xml_file = """\ <routingTable> … | |
Re: from bs4 import BeautifulSoup html = """\ <html> <head> <title>html page</title> </head> <body> <div>Hello world</div> </body> </html> """ soup = BeautifulSoup(html) head_tag = soup.find('head') head_tag.name = 'New name' print soup.prettify() """Output--> <html> <New name> <title> html page </title> </New name> <body> <div> Hello world </div> </body> </html> """ | |
Re: I did not guess the right answer. I did now that that `exec "print(a+b)"` evaluate to 7 and that `dict(a=6, b=9)` make a dictionary. So False was my guess because 7 in not in that dictionary,and only 'a' and 'b' would return True. I did probably know that this was … | |
![]() | Re: > Is it possible to create a scripting language using Python? Yes,but why? Your script show that you have very much to learn before thinking about writing an other language in python. An postet over now code is almost a joke with infinite recursion,do you know what this mean? Programming … ![]() |
Re: I change the code little,to how i think it should look. Ask if you dont understand it. def average(a,b,c): avr = (a+b+c) / 3.0 return avr def main(): user_input = input("Please enter any three numbers: ") numbers = [float(i) for i in user_input] avr = average(numbers[0],numbers[1],numbers[2]) print('The average of these … | |
Re: > I dont know why but extend adds 'devide' as another list to oper No. > I couldn't find "extend" function for lists Have you even looked? Help from interactive interpeter. >>> help(oper.extend) Help on built-in function extend: extend(...) L.extend(iterable) -- extend list by appending elements from the iterable The … | |
Re: A little help or mayby to much. >>> s = "This is it!".split() >>> s ['This', 'is', 'it!'] >>> len(s[0]) 4 >>> [len(i) for i in s] [4, 2, 3] Try to figure out what happens in code over. And as a practise **[len(i) for i in s]** write this … | |
Re: a,b are are really bad variable names. It`s ok to use only in small code examples,should not be used in finish scripts. **if b in i** really easy to understand? Bare **except:** should not be used. I explain better why not in this post. http://www.daniweb.com/software-development/python/threads/423971/python-program-detect-if-files-exist#post1812471 There is no need to … | |
Re: abhilam we have answered you in this post. http://www.daniweb.com/software-development/python/threads/425088/reading-a-column-from-text#post1817281 Why do you post same question in this two year old thread(marked solved)?,this is not good at all. | |
Re: Another way to get the same result you can look at. flag = 1 with open('over.txt') as f, open('output', 'w') as f_out: for line in f: if line.startswith(' Panicle'): flag = 0 if not flag: f_out.write(line[-19:]) |
The End.