M.S. 53 Light Poster

for example I don't know what this is called » [('cat', 'meow'), ('dog', 'ruff')]

It's called a list of tuples

so I can now remove the square brackets but I want to make it liek this ↴

catmeow
dogrugg

You can do something like this:

your_list = [('cat', 'meow'), ('dog', 'ruff')]
for tpl in your_list:
    print tpl[0]+tpl[1]
M.S. 53 Light Poster

off topic but wise ;-)

Where shall I begin, please your majesty?" he asked.
"Begin at the beginning", the king said, gravely, "and
go on till you come to the end: then stop ."

Alice in wonderland.

M.S. 53 Light Poster
def main():
    with open(raw_input("Enter file name: ", "r")) as fin:
        for num, line in enumerate(fin.readlines()):
            print("%d: %s"%(num+1, line))

it is without error checking, u
you can add exception catching to it.

M.S. 53 Light Poster

Thanks pyTony.
it is now far more better.
just as a suggestion, I think it can be a simple project for beginners. if you agree with me, please state this project in a better English for other beginners. :-)

M.S. 53 Light Poster

Assuming that every person has a National ID number, I am trying to check if the
Entered number is a valid ID number, under these conditions:
1. ID number must be of 10 digits length.
2. If ID length is greater than/equal to 8 and less than 10 digits, add one or two 0s to the left.
3. ID's digits must not be all the same(e.g. '1111111111', '222222222',...
4. Multiply the first 9 digits by numbers 10 to 2 respectively,
add them up and devide the sum by 11:
4.1.if the reminder is less than 2: the reminder must be equal to the last ID digit
4.2.if the reminder is equal to/greater than 2, subtract it from 11:the reminder must be equal to the last ID digit
if any condition is not met, the ID number is INVALID.
this is my effort:

def ID_check(ID_code):
    if (all(x==ID_code[0] for x in ID_code)) or len(ID_code)<8 or len(ID_code)>10 :
        return False
    if 8<=len(ID_code)<10:
        ID_code = (10- len(ID_code))*'0'+ID_code
    intlist = [int(i) for i in ID_code]
    control = (intlist[0]*10+intlist[1]*9+intlist[2]*8+intlist[3]*7+intlist[4]*6+intlist[5]*5+intlist[6]*4+intlist[7]*3+intlist[8]*2)%11
    if control<2:
        return control == intlist[9]
    elif control >= 2:
        control = 11 - control
        return control == intlist[9]

print ID_check(raw_input("Enter Your ID Code Number: "))

Any Suggestion/Correction is appreciated.

P.S. Sorry for my English, Its not my First language.

M.S. 53 Light Poster

the values in those two function have to be returned, in order to assign them to variables in main:

def starfighter ():
    strength = 20
    pilot = 55
    intelli = 40
    stamina = 35
    return strength, pilot, inteli, stamina
def chiefdiplomat ():
    strength = 45
    pilot = 20
    intelli = 50
    stamina = 35
    return strength, pilot, inteli, stamina
M.S. 53 Light Poster

and... the module profession.py returns nothing!
so your player will not have any of those properties.

M.S. 53 Light Poster

I'm using py4a on android and it helps me script things for my android phone.
stuff like searching messages for desired words,
text encryption and sending via sms
reboot options for root devises
bluetooth control with gui
and some more, I scripted already.

M.S. 53 Light Poster

what OS does it have? Android/iOS/Win Mobile?

M.S. 53 Light Poster

first no need to use print when assigning a user input to a variable.
secondfunction arguments are pre-requisit for function. so get those two user input vars out of the function.

M.S. 53 Light Poster

just write down some code and then try to enhance it step by step. then come back here and ask your questions.

what is yor algorithm or logic?

M.S. 53 Light Poster

I dont know wx and dont know how to fill searchbox :D but for searching a word or words u can add queries to google address:

www.google.com/search?q=SEARCH+WORDS
query = 'what is Python'
search_google = 'www.google.com/search?q=%s'%query
M.S. 53 Light Poster

One step further:

data = ''' Max Medium 12345678 58 152
Jane Johnson 87654321 78 201
Bill Bupkiss 23456789 29 29
Nate Newby 98765432 0 0
Harold Humphries 11223344 43 160
Carol Cramer 22334455 102 400
Alvin Adams 33445566 67 120
Fred Frederick 44556677 81 250
Phillip Parker 55667788 44 168
Sam Spade 24681357 16 30 '''

import pprint

data_list = [[int(item) if len(item)<=3 and item.isdigit() else item for item in line.split()] for line in data.split('\n')]

pprint.pprint(data_list)
M.S. 53 Light Poster

it seems that you didnt get what snippsat pointed out.
there is no get/set method in his code. so you can't call them .

M.S. 53 Light Poster

just something to start with:

data_list = [line.split() for line in myFile.readlines()]
M.S. 53 Light Poster

python uses (* asterix) for multiplication. in line 54 it assumes the s(s-side1) as a function call not a multiplication.
it should look like

s*(s-side1)*(s-side2)...
M.S. 53 Light Poster

you have to assign thevariable before using it. in your case, replace the line 1 and 2 with each other.

in python 2.x use raw_input instead of input and then convert it to integer or float.

M.S. 53 Light Poster

Importing modules inside anonymous functions:

t = lambda: __import__('time').localtime()
print('Date: %s/%s/%s'%(t().tm_mday, t().tm_mon, t().tm_year))
M.S. 53 Light Poster

Erratum :)

line 6: elif length > 6:

M.S. 53 Light Poster

what structure has the data in the text file?
show some of its data.
btw, range() doesnt work with float.

M.S. 53 Light Poster
define get_score(with a string argument):
    length = len(string)
    score = 0
    if length < 3:
        score = 0
    elif score > 6:
        score = length multiplied by 1
    elif other condition:
        apply other rules to score
    ...
    return score
M.S. 53 Light Poster

instead of confusing while MainLoop == 1 you can use:

while True:
    '''do stuff'''
    break
M.S. 53 Light Poster

Book: Think Java. it is really a cool book :)

M.S. 53 Light Poster

look at the full traceback record. and it's better to post the full traceback here...

M.S. 53 Light Poster

or

def shippingRate ( poundage , classification ):
    shipping_rate = poundage * classification
    return shipping_rate
M.S. 53 Light Poster

you should return shipping_rate in the second function:

def shippingRate ( poundage , classification ):
    return poundage * classification
M.S. 53 Light Poster

btw, read the pys60 documentation and API. you can find all functionalities you need.

M.S. 53 Light Poster

what is your targeted devise? if sysmbian:

import inbox    
box = inbox.Inbox(inbox.EInbox)
for sms_ID in box.sms_messages():
    print box.content(sms_ID)
M.S. 53 Light Poster

if you mean to write and run code, there is no support for python 3.3. SL4A only supports 2.6.2 and 3.0.1.

M.S. 53 Light Poster

post your code and traceback if you want to attract forum's experts attention. otherwise you wont get any help ;)

M.S. 53 Light Poster

simplest way:

url= 'http://maps.google.com/maps?q=%s+%s' % (latitude,longitude)
M.S. 53 Light Poster

Thanks bros for comments
specially pyTomy for introducing decorators and __str__ method.

M.S. 53 Light Poster

Thanks for this informing comment, Gribouillis.
I corrected iter and added one more function.
any further guide is appreciated.

#from math import*

class Triangle(object):
    """Checks if given sides can make a Triangle then shows the Angles."""
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.triangletype = ""
        self.A = self.B = self.C = 0
        self.__check_triangle()

    def __check_triangle(self):
        """Checks if given sides can make a Triangle"""
        if not (abs(self.c-self.b) < self.a < self.c+self.b):
            raise ValueError("Not a Triangle!")

    def get_angles(self):
        """Calculates the Angles based on the Cosine Rule."""
        self.A = degrees(acos((self.b**2+self.c**2-self.a**2)/float(2*self.b*self.c)))
        self.B = degrees(acos((self.a**2+self.c**2-self.b**2)/float(2*self.a*self.c)))
        self.C = 180 - (self.A+self.B)
        return self.A, self.B, self.C

    def triangle_type(self):
        """Gets the type of Triangle."""
        if self.A == 90 or self.B == 90 or self.C == 90:
            self.triangletype = "Right"
        elif self.a == self.b == self.c:
            self.triangletype = "Equilateral"
        elif (self.A == self.B or self.A == self.C or self.C == self.B):
            self.triangletype = "Isosceles"
        else:
            self.triangletype = "Scalene"

        return self.triangletype



if __name__ == '__main__':
    a,b,c =  (float(x) for x in raw_input("Enter Sides(Separated by a Space): ").split())
    t = Triangle(a,b,c)
    print "A: %.2f\nB: %.2f\nC: %.2f"%t.get_angles()
    print t.triangle_type()
M.S. 53 Light Poster

you can repeat your code for every word in string.split then join them at the end.

M.S. 53 Light Poster

This is me with another project for beginners :)
The Project as stated by ZZucker about 2 months ago:
"Given the length of three sides, write a function that checks if it is
possible to create a triangle."
I could solve it with an annonymus function like this:

is_triangle = lambda a,b,c: a+b!=c and a+c!=b and b+c!=a and c-b<a<c+b

But as I'm trying to understand using "class"es, I did code the following
class.
Now, Is this an acceptable class?
Thank you in advance for your comments :)

#from math import*

class Triangle(object):
    """Checks if given sides can make a Triangle then shows the Angles."""
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c
        self.A = self.B = self.C = 0

    def _istriangle(self):
        """Checks if given sides can make a Triangle"""
        if self.a+self.b!=self.c and self.a+self.c!=self.b and self.b+self.c!=self.a and self.c-self.b < self.a < self.c+self.b:
            return True
        else: return False

    def get_angles(self):
        """Calculates the Angles based on the Cosine Rule."""
        if self._istriangle():
            self.A = degrees(acos((self.b**2+self.c**2-self.a**2)/float(2*self.b*self.c)))
            self.B = degrees(acos((self.a**2+self.c**2-self.b**2)/float(2*self.a*self.c)))
            self.C = 180 - (self.A+self.B)
            print "It is a Triangle!"
            print "Angles Are:\nA: %.2f\nB: %.2f\nC: %.2f" %(self.A,self.B,self.C)
        else: print "Not-A-Triangle"


if __name__ == '__main__':
    a,b,c =  (float(x) for x in raw_input("Enter Sides(Separated by a Space): ").split())
    t = Triangle(a,b,c)
    t.get_angles()
M.S. 53 Light Poster

I'm satisfied now hehehe ;-)

M.S. 53 Light Poster

wow thank you all for these nice codes. I'm learning from them. But qhat your codes should look like if I needed to print out all longest words not just the first occurance of first max len word.

M.S. 53 Light Poster

Thank you pyTony. your Code motivated me to read about itertools :)

Using takewhile doesnt return any word, but an empty list. I think its bacause when takewhile meets the first matching word, it stops iteration and excludes the first found word from the list. In other word, the list of longest words will always be Empty.

PS: yes I call myself beginner because I have no background inProgramming, CS or any other kind of tech. I am a Rehabilitation profesional. BUT I'm in Love with Python and whenever I find free time, I spend it on Learning python. :D

M.S. 53 Light Poster

This is and answer to one of the Vegaseat's recent projects for beginners.
I share my solution here because -as a begginer and do learn python as a hobby-
I need your feedback. So please tell me am I doing it the right way?
Thanks in advance for comments

from string import punctuation as punc

def find_longest(text):

    words = list(set(word.strip(punc) for word in text.split()))
    length = len(sorted(words,key=len,reverse=1)[0])
    longest= [word for word in words if len(word)==length]

    return longest, length



#=============== TEST ==============#

text = """Python is probably one of the few programming languages which is both simple and
powerful. This is good for both and beginners as well as experts, and more importantly, is
fun to program with. This book aims to help you learn this wonderful language and show
how to get things done quickly and painlessly - in effect 'The Perfect Anti-venom to your
programming problems'."""

wordlist, length = find_longest(text)
print "Longest Word's Length: %d" %length
print "Longest Word(s): %s" %(str(wordlist))
M.S. 53 Light Poster

actually inbox.Inbox in my phone(s60v3 n95) lacks some functionallity that I need.say for example, if I wanted to delete only recived messages from only one contact among 60 contacts and 1300+ SMSs, there is no option to do that.
(in newer symbian^3 it is almost possible, but not in s60v3).

I am just using the Python API for accessing Messaging on my phone. this class is just for collecting the functions I want use for each messaging folder(i.e. Inbox, Sent, Draft, Outbox).

M.S. 53 Light Poster

A Separation (or Separation of Nader and Simin) by Asghar Farhady.
The Dreamers.
Forest Gump.

M.S. 53 Light Poster

this is my first attempt to implement OOP. IS this class ok?(in terms of structure)
AND another Question:
there are some folders in message application in Symbian phones
and sometimes there are up to 1000 messages in each folders.
I do itterate over all messages for gathering their info about sender/reciever/etc
but its very slow to use this clas for every folder.
how can I make a class that prevents me from itteratin over and over?
some info:
a messaging folder accessed from python returns a list of IDs from all of messages
for every ID there is a dict that contains info about that message.

#-------------------------------------------------------------------------------
# Name:        DelSMS
# Purpose:     Application for deleting SMS messages in Nokia Symbian Phones
# Author:      M.S.
# Created:     22/09/2012
# Copyright:   (c) Mohsen Sarhady 2012
# Python Version:     PyS60 v1.45(Python 2.2.2)
#-------------------------------------------------------------------------------
# -*- coding: utf-8 -*-

import inbox

class DelSMS:
    """Class for deleting SMS messages with diferent possibilities:
       -Dlete Messages in different folders
       -Delete Messages for a contact in different folders
       -Delete messages that contain a search keyword"""

    def __init__(self, folder):
        self.folder=folder
        self.m=folder.sms_messages()

    def contacts_by_folder(self):
        """Returns the list of contacts in the given folder."""
        contacts = []
        if len(self.m) != 0:
            for idx in self.m:
                address = self.folder.address(idx)
                if address not in contacts:
                    contacts.append(address)
        contacts.sort()
        return contacts

    def del_by_folder(self):
        """Deletes messages in the given folder."""
        if len(self.m) != 0:
            for idx in self.m:
                self.folder.delete(idx)

    def del_by_contact(self, contact):
        """Deletes Messages by Contact …
M.S. 53 Light Poster

a ')' at the end of line 1 is missing:

celsius = float(input("What is the Celsius temperature? "))
vegaseat commented: sharp eye +14
M.S. 53 Light Poster

All the Info you need, is accessible through the API documentation: menu > help > API help > bluetooth facade.

from android import Android

droid = Android()

check = droid.checkBluetoothState().result
if check != 1:
    droid.toggleBluetoothState(1,0)
    print "Bluetooth turned ON!"
    droid.bluetoothMakeDiscoverable(300)
    print "Bluetooth is Discoverable for 300sec now"

else:
    droid.toggleBluetoothState(0,0)
    print "Bluetooth turned OFF!"
M.S. 53 Light Poster

General suggestion: Read some introductory python texts like 'Hello Word' book, 'Dive into Python 2' ebook, etc.
For PyS60: Read the "Mobile Python" book and "Python on Symbian" online ebook at nokia developer.
One More: Try to read other programmers applications and scripts for s60 nokia phones. those are good tutorials ;)

M.S. 53 Light Poster

pyo, is os dependent i think, and there is no way to compile a py to pyo on the phone. you can compile or decompile py/pyc files using many apps out there as symbian packages (e.g. BestDeCompiler.sis).
if you make a pyo on pc from a pys60 script, i think it wont run on your phone.

M.S. 53 Light Poster

there is no example needed. just pack your script with py2sis application and type y for autostart in its wizard. thats it.

M.S. 53 Light Poster

the most widely used pys60 is v1.45 and is a port of python 2.2.2. the pys60 v1.9.7 that is a python 2.5 port that is less used.
for pys60 there are many modules for manipulating files and dirs, as an example I can suggest the pow_light fm module or fman module.there is also a shutil module for pys60.

M.S. 53 Light Poster

Try the TopWindow module for the graphics and those Icons (actually they are not icons but images that are linked to an app uid for App Run). the cursor is an image too and moves by defined keys(e.g. left/right arrow keys) via a redraw callback.
Implementing graphics like these is an advanced topic in canvas gui programming, at least in my oppinion :D

M.S. 53 Light Poster
ordertype =  raw_input(" Is the order for pickup or delivery? ")

while True:
    if not (ordertype.lower() in ["p","d"]):
        print "No, Enter only P or D!"
        ordertype =  raw_input("Is the order for pickup or delivery? ")
    else:
        print "Ok, %s Entered" %ordertype
        break
dan.nitschke commented: Excellent Response! +0