+ Reply to Thread
Page 1 of 2 12 LastLast
Results 1 to 10 of 17

Thread: Learning python part 2 (syntax and variables)

  1. #1
    saeras's Avatar
    saeras is offline Learning Programmer
    Join Date
    Jan 2010
    Location
    Sweden
    Posts
    67
    Rep Power
    8

    Learning python part 2 (syntax and variables)

    In this chapter i will go over common syntax and the different variable types.

    lets start then.

    We'll begin with looking at an if statement:

    Code:
    If 1 == 1:
        print('It's troo')
    else:
        print('I guess 1 isn't equal to 1')
    Whats going on here is that first python checks if 1 = 1, if thats the case then it will print "It's troo". however if it isn't the case python will jump to the else clause and print "I guess 1 isn't equal to 1". Also python have no '({' clauses to mark the beginning or end of an if statement. Instead python uses indentation. Let's see an example of that.

    Code:
    While True:
        If a == 1:
            print('a is 1')
            print('the things in this indentation')
            print('is what will happen when a is 1')
        Elif a == 2:
            print('a is 2')
            #this is checked after the first if statement
            #meaning if a is 1 then this clause will be skipped
        Else:
            print('what is a anyway?')
            #This clause will be skipped if either a is 1 or 2
        
        print('this is outside of the else clause')
        print('because its not in the else clause indentation')
    
    print('This prints if the program manages to ')
    print('break out of the infinite while loop')
    So if your gonna write something that happens if an if statement is true then you write it in its own indentation and when you wanna break out of it you go down one indentation. What this does is making everyone write code in a similar way making it easier to read. If your still unsure about how this indentation works you can go play with some if statements and print in the command line.
    As you can see in the previous example python uses boolean expressions to check if things are true or false. So how does a boolean expression look like in python.

    Code:
    #you can write if statements like this but i try to avoid it.
    If a == 2: print('a is 2') 
    #If a is 2 then "a is 2" will be printed
    
    #here follows some other boolean expressions
    If a <= 2: #If a is less than or equal to 2.
    If a >= 2: #If a is greater than or equal to 2.
    If a < 2: #If a is less than 2.
    If a > 2: #If a is greater than 2.
    If a != 2: #If a is not equal to 2.
    
    #you can also fill in several condition checks into one if statement
    If a == 2 or a == 7: #If a is equal to 2 or if a is equal to 7.
    If not a == 2: #If a isn't equal to 2.
    If a < 7 and a > 2: #If a is less than 7 or greater than 2.
    If any of this feels unclear you can do a Google search on boolean expressions or you could ask on codecall in the python section and I'm sure that ppl will come rushing to your aid.

    But before we can put any of this to good use we need to know about variables. In python we have str, int, list, tuple and dictionary. Although going through them all and all their features would take an whole tutorial for them self. If you want to know more about the advanced features of different variables you can go to the site your gonna learn to love 5. Data Structures &mdash; Python v2.6.4 documentation . If you want to know anything about python it can most likely be found there.

    Following are some easy operations to get you going on using variables.

    Code:
    #if you haven't noticed by know the '#' character is used to put in a comment
    
    #Strings
    str = 'hello'
    name = 'Andreas'
    
    # " or ' can be used to contain a string
    text = "This is my tutorial isn't it nice"
    
    #Watch out though because 
    #Would end the string premature
    text = 'This is my tutorial isn't it nice' 
    
    #if you want to write a str over several lines you can use this 
    longtext = """This string
    can be written on several lines
    note that it has to be on the same indentation though"""
    
    #to add something to a str you use this
    part1 = 'hello'
    part2 = 'world'
    
    #this will make part1 = 'helloworld'
    part1 += part2  or  part1 = part1 + part2 
    
    #to add a space you could insert one in this manner
    part1 = part1 + ' ' + part2 #which would make part1 = 'hello world'
    
    #to pick out a certain part of a str you can use this
    str = 'abcd'
    print(str[0]) #would output a
    print(str[2:3])  #would output c
    #you can play around with this some and 
    #see what happens if you enter negative numbers
    
    #Integers
    a = 1
    a += 2 #a = a + 2
    print(a) #would output 3
    
    #you can also assign several values in one line
    #even those of different types 
    a, b, c, d = 1, 'hello', 2, 7
    
    #or assign a single value to several variables
    a = b = c = 10
    I'm gonna have to come back to lists, tuples, and dictionaries in another tutorial since they have lots of nice features. Feel free to browse around in the link provided earlier though to find some info about them.

    Using this we can for example write a very simple (and insecure) login system.

    Code:
    name = 'Andreas'
    password = 'abcd'
    
    While True:
        input_name = raw_input('enter your name: ')
        input_password = raw_input('enter the password: ')
    
        If input_name == name And input_password == password:
            print('hello Andreas')
            raw_input('press enter to continue')
            Break
        Else:
            print('Did you misspell something?')
    What will happen here is that when you enter "Andreas" as name and "abcd" as password it will greet you and wait for you to press enter. When you press enter it will break out of the while loop and the program will stop running. Watch out when your using break it might produce unwanted result when you nest while loops with either other while loops or for loops. So for example:

    Code:
    While True:
        For x in range(5):
            if x == 3:
                break
    Would break out of the For loop, to fix this you can use this.

    Code:
    i = 1
    While i == 1:
        For x in range(5):
             if x == 2:
                 i = 0
                 Break
    This would make i to 0 and break the for loop when x is 2. Which would in turn break the while loop seeing how i isn't 1 anymore.

    A few words about for loops. A for loop is a loop that go through w.e you want to go through. Some examples:

    Code:
    #This will print out 0, 1, 2, 3, 4
    For x in range(5):
        print(x)
    
    #this will print out a, b, c, d
    str = 'abcd'
    for x in str:
        print(x)
    Basically a for loop will iterate through any iterable object.

    It's funny when you start writing and it easy becomes more than you imagine it would. Well this should be enough to get you started doing some simple coding or get you interested enough to continue learning. I will try and go more in depth in the following tutorials.

    Feel anything have been left out? Had trouble with something? Or want something changed?
    Post a comment about it and I will see what I can do.

  2. CODECALL Circuit advertisement
    Join Date
    Always
    Location
    Advertising world
    Posts
    Many

     
  3. #2
    Phoenixz is offline Programming Professional
    Join Date
    Dec 2008
    Posts
    256
    Blog Entries
    1
    Rep Power
    13

    Re: Learning python part 2 (syntax and variables)

    Small question, is indentation that important? (does it actually read the whitespace unlike others?)

  4. #3
    saeras's Avatar
    saeras is offline Learning Programmer
    Join Date
    Jan 2010
    Location
    Sweden
    Posts
    67
    Rep Power
    8

    Re: Learning python part 2 (syntax and variables)

    Yes indentation is pythons way of encasing it into () so to say. for example:
    Code:
    If 2 == 1:
    print('hello')
    Wouldn't work because python doesn't see "print('hello')" as a part of the if clause. In fact if you would try to run it it would give you an error cause python sees the if clause as empty.

    This code

    Code:
    if 2 == 1:
        Print('2 is not equal to 1')
    Print('2 is equal to 1')
    Would run "print('2 is equal to 1')" because python sees it as outside the if clause.
    I hope this answers your question.

  5. #4
    exicute's Avatar
    exicute is offline Programming Expert
    Join Date
    Jan 2010
    Location
    Ohio
    Posts
    398
    Rep Power
    10

    Re: Learning python part 2 (syntax and variables)

    Alright I've read this tut and understood everything so far, but I have 2 quick questions.

    I'm trying to write a python program that takes 2 number from the user and calculates the sum. Here is my code:
    Code:
    input_num1 = raw_input('Enter the first integer: ')
    input_num2 = raw_input('Enter the second integer: ')
    
    input_num1 += input_num2
    
    print(input_num1)
    
    raw_input('Press Enter to continue')
    I am assuming that it thinks the inputs are strings, but how do I declare them as integers? (My guess it's done somewhere done near the "raw_input", correct?)

    All it does it put the 2 numbers side by side (As in input is 5 and 5 and it prints 55 rather than 10), how do you do a numerical calculation in python?

    A simple sample of code will suffice.

    My Tutorials|Build A Computer|Cat 5E|

  6. #5
    saeras's Avatar
    saeras is offline Learning Programmer
    Join Date
    Jan 2010
    Location
    Sweden
    Posts
    67
    Rep Power
    8

    Re: Learning python part 2 (syntax and variables)

    Yea python sees the input from raw_input as strings therefor it just contencates them instead of doing the desired calculation. To make them integers instead just add a simlpe int(). Example:
    Code:
    number = int(raw_input('445'))
    As an interesting side note using str() would turn it into a string. You could also use eval() which will take a guess at what you presented and change it to the desired type.
    eval() has proven really useful in many cases so it's worth to remember. Also if you want to check what type a variable is you can use type() . I hope this answers your question.

  7. #6
    exicute's Avatar
    exicute is offline Programming Expert
    Join Date
    Jan 2010
    Location
    Ohio
    Posts
    398
    Rep Power
    10

    Re: Learning python part 2 (syntax and variables)

    Yep, thanks for the speedy reply too. +rep

    My Tutorials|Build A Computer|Cat 5E|

  8. #7
    Prog4rammer's Avatar
    Prog4rammer is offline Newbie
    Join Date
    Jan 2010
    Location
    Gaza
    Posts
    14
    Rep Power
    0

    Re: Learning python part 2 (syntax and variables)

    Thanks for this Part is Very easy to leaning and very Cool ..
    I Hope see the next Part and non question now

    Some Words Me : "♪●Software Engineer and Love Programming in Java and PHP under Ubuntu System ... ♪♥ "

  9. #8
    Join Date
    Nov 2009
    Location
    London
    Posts
    866
    Blog Entries
    3
    Rep Power
    14

    Re: Learning python part 2 (syntax and variables)

    Am following this series, good tut

  10. #9
    totolzz is offline Newbie
    Join Date
    Jul 2010
    Posts
    5
    Rep Power
    0

    Re: Learning python part 2 (syntax and variables)

    thanks for this tut,i understand what for a loop to use.. it takes time to get in my mind..whewww

  11. #10
    legacy is offline Newbie
    Join Date
    Jan 2011
    Posts
    16
    Rep Power
    0

    Re: Learning python part 2 (syntax and variables)

    I don't know what I'm doing wrong. Everytime I type the first bit of code I get a syntax error and it highlights the first 1
    EDIT
    and when I run the code for the username and password I get a syntax error and it highlights True

+ Reply to Thread
Page 1 of 2 12 LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. learning python part 4 (a look at functions)
    By saeras in forum Python Tutorials
    Replies: 2
    Last Post: 09-22-2011, 03:13 PM
  2. Learning Python part 0 (prelude)
    By saeras in forum Python Tutorials
    Replies: 8
    Last Post: 07-23-2011, 12:04 PM
  3. learning python part 3 (lists, dictionaries and tuples)
    By saeras in forum Python Tutorials
    Replies: 1
    Last Post: 03-04-2011, 07:19 AM
  4. Replies: 5
    Last Post: 03-25-2010, 01:41 AM
  5. Learning python part 5 (modules)
    By saeras in forum Python Tutorials
    Replies: 1
    Last Post: 02-19-2010, 04:21 AM

Tags for this Thread

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