View Poll Results: Who do you think is the best beginner?

Voters
19. You may not vote on this poll
Page 6 of 22 FirstFirst ... 4567816 ... LastLast
Results 51 to 60 of 216

Thread: [Beginner] Programming Challenge: 2

  1. #51
    Join Date
    Nov 2006
    Location
    Pennsylvania
    Beans
    423

    Re: [Beginner] Programming Challenge: 2

    PHP Code:

    class ForumUser:

        
    def __init__(self):
            print 
    "Welcome, new forum user! We must set up your account."
            
    print "To exit the setup at anytime, simply type 'exit' (excluding quotations)."

            
    self.name ""
            
    self.age = -1
            self
    .user = -1

            self
    .__set_all()

            
    self.to_string()

        
    def __set_all(self):
            print 
    "The first step is to set your user name.\n"
            
    self.set_name()

            print 
    "Next, please enter your age.\n"
            
    self.set_age()

            print 
    "Finally, enter your user ID.\n"
            
    self.set_user()

        
    def set_name(self):
            print 
    "Forum Name must have at least 1 character, may not begin with a space and cannot be 'exit', 'Exit', etc.\n"
            
    name_ok False
            
    while name_ok == False:
                
    self.name raw_input("Enter Desired Name: ")
                
    self.__y_n_exit(self.name)

                if 
    self.name == "":
                    print 
    "I told you, your name must be at least 1 character long!\n"
                    
    continue
                if 
    self.name[0] == " ":
                    print 
    "I told you, space as first character is not allowed!\n"
                    
    continue
                else:
                    
    name_ok True
                    
    print "Your user name is: %s \n " self.name

        def set_age
    (self):
            print 
    "Your age must be a number greater than 0, although I have a feeling you are much older than 1!\n"
            
    age_ok False
            
    while age_ok == False:
                
    self.age raw_input("Enter Your Age: ")
                
    self.__y_n_exit(self.age)

                
    self.age self.__string_to_int(self.age)

                if 
    self.age == 'error'
                    continue
                
    elif self.age 1:
                    print 
    "You aren't that young! Enter your real age!\n"
                    
    continue
                
    elif self.age 199:
                    print 
    "I don't think anyone is that old! Enter your real age!\n"
                    
    continue
                else:
                    
    age_ok True
                    
    print "Your age is: %d" self.age

        def set_user
    (self):
            print 
    "Your user ID must be greater than 0 and less than 999999\n"
            
    userid_ok False
            
    while userid_ok == False:
                
    self.user raw_input("Enter Your ID: ")
                
    self.__y_n_exit(self.user)

                
    self.user self.__string_to_int(self.user)

                if 
    self.user == 'error':
                    continue
                
    elif self.user 1:
                    print 
    "ID Must be greater than 0!\n"
                    
    continue
                
    elif self.user 999999:
                    print 
    "ID Must be less than 1000000!\n"
                    
    continue
                else:
                    
    userid_ok True
                    
    print "Your ID is: %d" self.user

        def to_string
    (self):
            if 
    self.user != 999999:
                print 
    "You are %s, aged %d, with user id %d. Next year you will be %d and the next user id is %d" % (self.nameself.ageself.userself.age+1self.user+1)
            else:
                print 
    "You are %s, aged %d, with user id %d. Next year you will be %d and there can be no next user!" % (self.nameself.ageself.userself.age+1)

        
    def __string_to_int(selfstring):
            try:
                return 
    int(string)
            
    except ValueError:
                print 
    "I don't think you entered a normal number! Try Again."
                
    return 'error'

        
    def __y_n_exit(selfstring):
            if 
    string.lower() == 'exit':
                print 
    "\nYou have decided to exit, come back soon!"
                
    quit()

    user ForumUser() 
    Last edited by TreeFinger; August 6th, 2008 at 05:47 PM.
    Your Ubuntu User number is # 15355

    A must Read for anyone interested in Computer Programming.

  2. #52
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: [Beginner] Programming Challenge: 2

    Quick Python version, I'll work on a C one after dinner

    Code:
    #!/usr/bin/env python
    #coding: utf-8
    
    import sys
    
    class User(object) :
    
        def __init__(self) :
            self.__username = ""
            self.__uid = 0
            self.__age = 0
    
            print "Okay, I'm going to ask you a few details about yourself."
            print "Remember that at any prompt, you may type \"exit\" to quit."
    
        def testInputForExit(self, input) :
            if input == "exit" :
                print "Good bye!"
                sys.exit(0)
    
    
        def promptUsername(self) :
            print "\nPlease enter your username and press Enter."
            while True :
                username = raw_input()
                self.testInputForExit(username)
                username=username.strip()
    
                if username != "" :
                    self.__username = username
                    break
    
                print "Error. Your username must contain at least one non-space character."
    
    
        def promptAge(self) :
            print "\nNow, please enter your age."
            while True :
                age = raw_input()
                self.testInputForExit(age)
    
                try :
                    age = int(age)
                    assert age >= 0 and age <= 130
                except ValueError :
                    print "Error. You must enter an integer."
                except AssertionError :
                    print "Error. You must enter a stricly positive integer no greater than 130."
                else :
                    self.__age = age
                    break
    
        def promptUid(self) :
            print "\nAlmost there! Now, please enter your user ID."
            while True :
                uid = raw_input()
                self.testInputForExit(uid)
    
                try :
                    uid = int(uid)
                    assert uid > 0
                except ValueError :
                    print "Error. You must enter an integer."
                except AssertionError :
                    print "Error. You must enter a strictly positive integer."
                else :
                    self.__uid = uid
                    break
    
        def printString(self) :
            print "You are %s, aged %s next year you will be %s, with user id %s, the next user is %s." % \
                    (self.__username, self.__age, self.__age + 1, self.__uid, self.__uid +1)
    
    if __name__ == "__main__" :
        user = User()
        user.promptUsername()
        user.promptAge()
        user.promptUid()
        user.printString()
    Last edited by Bachstelze; August 8th, 2008 at 10:28 PM.
    「明後日の夕方には帰ってるからね。」


  3. #53
    Join Date
    Mar 2008
    Beans
    1,755

    Re: [Beginner] Programming Challenge: 2

    Alright, starting off. I am aware that it better practice to use OPP instead of global variables but this is the way that I wanted to do it for my own personal learning experience. I'm happy with the end result:

    PHP Code:
    #!/usr/bin/python

    import sys

    name 
    0
    age 
    0
    uid 
    0

    def getname
    ():
        global 
    name
        name 
    raw_input(str("What is your name? "))
        if 
    name == "exit":
            
    sys.exit()        
        if 
    name[0] == " ":
            print 
    "\nPlease do not start your name with a space.\n\nTry again.\n"
            
    getname()
        try:
            
    name str(name)
        
    except:
            print 
    "\nAre you sure thats your name?\n\nTry again.\n"
            
    getname()
        
    def getage():
        global 
    age
        age 
    raw_input("How old are you? ")
        
        if 
    age == "exit":
            
    sys.exit()
        
        try:
            
    age int(age)
        
    except:
            print 
    "\nYour age needs to be an integer.\n\nTry again.\n"
            
    getage()
        if 
    age 100:
            print 
    "\nThats too old.\n\n Try again.\n"
            
    getage()
        
    elif age <= 0:
            print 
    "\nYou must be older than that.\n\nTry again.\n"
            
    getage()
            

    def getuid():
        global 
    uid
        uid 
    raw_input("What is your forum user id? ")

        if 
    uid == "exit":
            
    sys.exit()
        
        try:
            
    uid int(uid)
        
    except
            print 
    "\nUser IDs should be in the form of integers\n"
            
    getuid()
        if 
    uid 1:
            print 
    "\nThe user ID you have entered is invalid.\n\nTry again.\n"
            
    getuid()
        
    elif uid 999999:
            print 
    "\nThe user ID you have entered in invalid.\n\nTry again.\n"
            
    getuid()        


    def main():

        print 
    "\n\nPlease answer the following questions.\n\n You can type exit at any time to quit.\n"
        
    getname()
        
    getage()
        
    getuid()

        
    nextyear age 1
        nextuid 
    uid 1

        
    print "\n\nYou are %s, aged %s next year you will be %s, with user id %s, the next user is %s.\n" % (nameagenextyearuidnextuid)

        
    raw_input("Press the enter key to exit.\n")

    main() 

  4. #54
    Join Date
    Jul 2008
    Beans
    9

    Re: [Beginner] Programming Challenge: 2

    After a few hours of me banging my head against anything that was in close proximity, reading through man page after man page, and wasting even a few more hours trying to figure out why fflush() wasn't working on stdin, I think I finally have some working code here.

    It was compiled using gcc 4.2.3 on Linux 2.6.24-19.

    PHP Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <assert.h>
    #include <ctype.h>

    #define NAME_LEN 21
    #define BUF_SIZE 21

    #define AGE_MIN 10
    #define AGE_MAX 100

    #define ID_MIN 1
    #define ID_MAX 999999

    #define QUIT_STRING "exit"

    void get_string(charpromptcharstringunsigned int string_length)
    {
      
    char buffer[BUF_SIZE];
      
    char c;

      
    printf("%s"prompt);

      
    /* Read in BUF_SIZE characters from standard input and store it in buffer. */
      
    fgets(bufferBUF_SIZEstdin);

      
    /* If the user types "exit" at any point, then that's what we need to do. */
      
    if (strncmp(bufferQUIT_STRINGstrlen(QUIT_STRING)) == 0)
        exit(
    EXIT_SUCCESS);

      
    /* This code could use some explaining. What happens when you type in a
         string longer than the buffer is that it copies over the length of the
         buffer, but leaves the rest of what was entered still in the input queue.
         For most compilers, fflush() is only designed for output buffers, and
         using it on input buffers has an unknown effect. (However, I believe that
         MS VC++'s version of fflush may be used on stdin.) What this code does is
         (1) checks to see if our local buffer string is full, and (2) if this is
         the case, then that means we have some "overflow" still in the stdin
         queue. The while loop then reads in the rest of the unwanted characters
         from the queue and discards them, so we won't have problems when we try
         and read new user input in the future. */
      
    if (strlen(buffer) >= BUF_SIZE 1)
        while ((
    fgetc(stdin)) && != '\n');

      
    /* Copies our local copy to the string whose address was passed in. This
         only copies up to string_length characters. */
      
    strncpy(stringbufferstring_length);
    }

    void get_username(charpromptcharstringunsigned int string_length)
    {
      
    char username[BUF_SIZE];
      
    int hasChars 0;
      
    int i;

      do {
        
    get_string(promptusernameBUF_SIZE);

        if (
    username[0] == ' ') {
          
    printf("Sorry, your username cannot begin with a space.\n");
          continue;
        }

        
    /* This scans the string to see if there is at least one character (as
           opposed to all numbers) in the string. In addition, it gets rid of the
           newline character which is kept on from the fgets() function called in
           the get_string function. */
        
    for (0BUF_SIZEi++) {
          if (
    username[i] == '\n'){
        
    username[i] = '\0';
        break;
          }

          if (
    isalpha(username[i])) {
        
    hasChars 1;
          }
        }

        if (! 
    hasChars)
          
    printf("Sorry, your username must contain at least 1 character.\n");

      } while ((! 
    hasChars) || username[0] == ' ');

      
    strncpy(stringusernamestring_length);
    }

    unsigned int get_number(charpromptunsigned int minunsigned int max)
    {
      
    char input_string[BUF_SIZE];

      
    unsigned int number 0;

      do {
        
    printf("%s (%d-%d): "promptminmax);
        
    get_string(""input_stringBUF_SIZE);
        
        
    /* Converts the string representation of the number to an actual integer
           stored value. */
        
    number = (unsigned int)atoi(input_string);

        
    /* atoi will return 0 if an error has occured, so we must check the first
           character to see if it is actually a 0, or if atoi just returned with an
           error. */
        
    if (number == && input_string[0] != '0') {
          
    printf("That wasn't a number. Please try again.\n");
          continue;
        }
      } while (
    number min || number max);

      return 
    number;
    }

    int main(int argccharargv[])
    {
      
    char name[NAME_LEN]; name[0] = '\0';
      
    unsigned int ageid;

      
    /* We want to make sure that the quit string can actually fit inside the
         buffer. Otherwise, all hell may break lose. */
      
    assert(strlen(QUIT_STRING) < BUF_SIZE);

      
    printf("Type '%s' at any time to quit.\n\n"QUIT_STRING);

      
    /* Retrieve and validate all input */
      
    age get_number("Please enter your age"AGE_MINAGE_MAX);
      
    id get_number("Please enter your user id"ID_MINID_MAX);
      
    get_username("Please enter your forum name: "nameNAME_LEN);
      
      
    /* Output the final results */
      
    printf("You are %s, aged %d next year you will be %d, with user id %d, the next user is %d.\n"nameageage+1idid+1);

      
    /* We are home at last! */
      
    return EXIT_SUCCESS;

    EDIT: I changed the CODE tags to PHP tags, so the code is easier on your eyes, even though the OCD side of me is making me twitch because it's labeled something that it's not.
    Last edited by wtfnomorenames; August 6th, 2008 at 11:28 PM.

  5. #55
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 2

    @wtfnomorenames

    It prints "Sorry, your username must contain at least 1 character." every time. Please fix it, I'd hate to have your code disqualified for such a minor detail

  6. #56
    Join Date
    Jul 2008
    Beans
    9

    Re: [Beginner] Programming Challenge: 2

    Quote Originally Posted by LaRoza View Post
    @wtfnomorenames

    It prints "Sorry, your username must contain at least 1 character." every time. Please fix it, I'd hate to have your code disqualified for such a minor detail
    Wow, thanks for that! I restructured some things, and didn't even notice that. I corrected it in my post above.

  7. #57
    Join Date
    Nov 2005
    Location
    Sendai, Japan
    Beans
    11,296
    Distro
    Kubuntu

    Re: [Beginner] Programming Challenge: 2

    @LaRoza : not sure if we may comment on other users' code here. If not, feel free to delete this.

    @Titan8990 : okay, a few comments:

    1) "Shebang" line. You should use #!/usr/bin/env python instead of #!/usr/bin/python, because Python is not always intalled at /usr/bin/python. For example, if I tried to execute your script on my FreeBSD system, it would not start, because Python is intalled at /usr/local/bin/python. On the other hand, #!/usr/bin/env python is a nice way to make sure your script runs on all platforms (see here if you want to know why).

    2) Global variables. You really shouldn't use them, and you can avoid it without needing to use OOP, just pass the variables you need to be modified as arguments to your function, and use the return values, like :

    PHP Code:
    age 0
        
    def getage
    (oldage):
        
    age raw_input("How old are you? ")
        
        if 
    age == "exit":
            
    sys.exit()
        
        try:
            
    age int(age)
        
    except:
            print 
    "\nYour age needs to be an integer.\n\nTry again.\n"
            
    getage()
        if 
    age 100:
            print 
    "\nThats too old.\n\n Try again.\n"
            
    getage()
        
    elif age <= 0:
            print 
    "\nYou must be older than that.\n\nTry again.\n"
            
    getage()

        return 
    age

    def main
    (age):

        print 
    "\n\nPlease answer the following questions.\n\n You can type exit at any time to quit.\n"
        
    age getage(age)
        
    nextyear age 1

        
    print "\n\nYou are aged %s next year you will be %s." % (agenextyear)

        
    raw_input("Press the enter key to exit.\n")

    main(age
    3) Recursivity. It is absolutely not needed here, as it doesn't make your code any more readable, and could lead to problems if you have some fool of a user who keeps entering invalid data, due to the enormous amount of function calls in your stack that would create. It would be better to use a while loop to keep prompting until a valid value is entered without making additional function calls.

    4) str(x) when x is a string (you're not the only one who've done that one, though). What the heck? If x is a string, str(x) will simply return x, there is absolutely no point in doing this (and even more so in trying to make it raise an exception) when you're certain it is the case.

    5) name = 0. Setting an initial value for a parameter that is not of the correct type for it (0 is an illegal name, as it is not a string) should be avoided, as it might confuse people who read your code and might want to reuse it.
    Last edited by Bachstelze; August 7th, 2008 at 01:51 PM.
    「明後日の夕方には帰ってるからね。」


  8. #58
    Join Date
    Apr 2008
    Beans
    246

    Re: [Beginner] Programming Challenge: 2

    Should we let usernames contain spaces as long as it does not begin with a space?

  9. #59
    Join Date
    Apr 2007
    Beans
    14,781

    Re: [Beginner] Programming Challenge: 2

    Quote Originally Posted by wtfnomorenames View Post
    Wow, thanks for that! I restructured some things, and didn't even notice that. I corrected it in my post above.
    I'll test it out. It works well, definately one of the top ten assuming we don't get a bunch of C guru's here

    Quote Originally Posted by HymnToLife View Post
    @LaRoza : not sure if we may comment on other users' code here. If not, feel free to delete this.
    Why not. It is all about learning.

    1) "Shebang" line.
    Just to let others know, I copy and paste code to run it, but I will run it with the appropriate interpreter even if it isn't specified or specified correctly.


    Quote Originally Posted by linkmaster03 View Post
    Should we let usernames contain spaces as long as it does not begin with a space?
    User names can contain spaces, but as long as the program doesn't break when it is entered (even if it doesn't record the name in full) it is Ok. Using spaces will be a possible tie breaker if it comes down to that.

  10. #60
    Join Date
    Mar 2008
    Beans
    796

    Re: [Beginner] Programming Challenge: 2

    First program ever written with python these threads are an awesome idea
    PHP Code:
    #! /usr/bin/python

    import sys
    resp 
    raw_input("What is your forum name (Type quit to exit)? ")
    if 
    resp == "quit":
        print 
    "Goodbye"
        
    sys.exit()
    else:
        print 
    "Thank You"

    resp1 raw_input("What is your age (Type quit to exit)? ")
    if 
    resp1 == "quit":
        print 
    "Goodbye"
        
    exit()
    else:
        
    resp1 int(resp1)
        if 
    resp1 1:
            print 
    "That is not a valid age, Goodbye"
            
    exit()
        else:
            if 
    resp1 999999:
                print 
    "That is not a valid age,Goodbye"
                
    exit()
            else:
                print 
    "Thank You"

    resp2 raw_input("What is your forum ID (Type quit to exit)? ")
    if 
    resp2 == "quit":
        print 
    "Goodbye"
        
    exit()
    else:
        
    resp2 int(resp2)
        if 
    resp2 1:
            print 
    "That is not a valid forum ID, Goodbye"
            
    exit()
        else:
            if 
    resp2 999999:
                print 
    "That is not a valid forum ID, Goodbye"
                
    exit()
            else:
                print 
    "Thank You"

    print "You are %s, aged %s next year you will be %s, with user id %s, the next user is %s." % (respresp1,resp1 1resp2resp2 +1

Page 6 of 22 FirstFirst ... 4567816 ... LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •