Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Learning python part 2 (syntax and variables)

hello world syntax variable type

  • Please log in to reply
19 replies to this topic

#1 saeras

saeras

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 64 posts

Posted 11 February 2010 - 08:27 AM

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:

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.

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.

#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 — 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.

#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.

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:

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.

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:

#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.
  • 1
Posted Image

#2 Phoenixz

Phoenixz

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 222 posts

Posted 11 February 2010 - 12:09 PM

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

#3 saeras

saeras

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 64 posts

Posted 11 February 2010 - 12:21 PM

Yes indentation is pythons way of encasing it into () so to say. for example:
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

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.
  • 0
Posted Image

#4 exicute

exicute

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 146 posts

Posted 13 February 2010 - 11:19 AM

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:
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.
  • 0
Posted Image
My Tutorials|Build A Computer|Cat 5E|

#5 saeras

saeras

    CC Resident

  • Just Joined
  • PipPipPipPip
  • 64 posts

Posted 13 February 2010 - 11:25 AM

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:
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. ^^
  • 0
Posted Image

#6 exicute

exicute

    CC Addict

  • Just Joined
  • PipPipPipPipPip
  • 146 posts

Posted 13 February 2010 - 11:28 AM

Yep, thanks for the speedy reply too. +rep
  • 0
Posted Image
My Tutorials|Build A Computer|Cat 5E|

#7 Prog4rammer

Prog4rammer

    CC Newcomer

  • Just Joined
  • PipPip
  • 14 posts

Posted 09 March 2010 - 05:41 AM

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

#8 James.H

James.H

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 569 posts

Posted 23 March 2010 - 08:23 AM

Am following this series, good tut :)
  • 0

#9 totolzz

totolzz

    CC Lurker

  • Just Joined
  • Pip
  • 4 posts

Posted 30 July 2010 - 11:05 PM

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

#10 legacy

legacy

    CC Newcomer

  • Just Joined
  • PipPip
  • 14 posts

Posted 16 January 2011 - 05:11 PM

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
  • 0

#11 Flying Dutchman

Flying Dutchman

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1090 posts
  • Location:::1
  • Programming Language:C++, Python

Posted 16 January 2011 - 05:18 PM

Posting an error and code if possible would make it easier to help you, legacy. :)
  • 0

The roots of education are bitter, but the fruit is sweet.


#12 legacy

legacy

    CC Newcomer

  • Just Joined
  • PipPip
  • 14 posts

Posted 16 January 2011 - 05:30 PM

my code for the if statement
If 1 == 1:
    print("It's troo")
else:
    print("I guess 1 isn't equal to 1")

my error: There's an error in your program: invalid syntax, then takes me back and highlights 1

my code for username stuff
name = 'Anreas'
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?')
same error just highlights True
  • 0





Also tagged with one or more of these keywords: hello world, syntax, variable type