Monday, 8 October 2012

Print, Input, Mathematical Operators, Lists & Turples

User Input
input() - a user has to input something, it can be text or numbers. Usually there is a message in the brackets (the message needs to be in quotes).
int() - integer - this is a whole number. It means that the user cannot input letters.
int(input("Message here: ")) - how it would look if you wanted someone to input an integer!
The code above wouldn't work, because you need to have a variable in which to save the users answer.

Print
Print is where you want the program to output something.
You can output messages, or variables, or a combination of the two.

age = int(input("Please input your age: "))
print("You are ", age, " years old.")

In the example above, the commas separate out the different bits of the code.

Operators (Mathematical and otherwise)
= - this means that you are saving (or setting) something to a value.
x = 4
This means that x is set to 4.
x = input("Please input your name")
This means that x is set to whatever the user types in.
Think carefully; is x a sensible variable name in the example above?

== - this means that you are checking one value against another.
if x == 4:
  print("x equals 4")
The code above means that is the value store in x is 4, print the message.

+ - This adds things together
- - This subtracts
/ - This divides
* - This multiplies

> - This is greater than
< - This is less than

Lists
A list is where you can store a lot of things (attributes) to one variable (Remember, variable means it can change).
To define a list, it needs a name and then all of the attributes go inside square brackets.
my_list = ["bob", "apple", "green"]
The above list has three attributes 1, 2 and 3.
IMPORTANT: Because nothing in life is easy, even though we start counting at 1, the computer starts counting at 0.
Lists are variable, that means you can add to them and delete out attributes.
del my_list[1]
This would delete out the second thing from the list.
my_list.append("4")
This will add the number 4 to the end of the list.

Turples
A turple is like a list, but it cannot be changed - therefore it is constant.
A turple is defined in the same way as a list, except that it has round brackets and no quotes.
my_turple = (1,2,3)

No comments:

Post a Comment