>>> print("hello world") hello world >>> print(3+2) 5 >>> a = 5 >>> print(a+2) 7
message = input() print("I've got a message: " + message) number = int(input()) print(number+1)
To read a decimal number, use float
instead of int
when converting.
>>> 10+8 18 >>> 10-30 -20 >>> 34.2*6 205.20000000000002 >>> 5/2 2.5
>>> 3 == 3 # Equality test True >>> 4 != 4 # Inequality test False >>> 35.2 < 34 False >>> 24 > 2 True >>> 2 > 2 False >>> 2 >= 2 # "Greater or equal" True >>> a = 10 >>> a > 7 and a < 12 # Same as 7 < a < 12 in mathematical notation True >>> b = False # Boolean values True and False are regular values and can be assigned to variables >>> not b # Negation True
>>> a = 3 >>> if a > 2: ... print("A is bigger than 2") ... else: ... print("A is smaller than 2") ... A is bigger than 2 >>> if a == 1: ... print("A is 1") ... elif a == 2: ... print("A is 2") ... elif a == 3: ... print("A is 3") ... elif a == 4: ... print("A is 4") ... A is 3 >>> if a != 3: ... print("some message") ... >>>
As you can see the else
is not mandatory.
The last if statement doesn't print anything because a != 3
is false.
>>> i = 0 >>> while i < 10: ... print("Doing something for the #" + str(i+1) + " time") ... i = i+1 ... Doing something for the #1 time Doing something for the #2 time Doing something for the #3 time Doing something for the #4 time Doing something for the #5 time Doing something for the #6 time Doing something for the #7 time Doing something for the #8 time Doing something for the #9 time Doing something for the #10 time >>>
>>> mustContinue = True >>> while mustContinue: ... message = input() ... if message == "stop": ... mustContinue = False ... messaggio a caso rickroll stop >>>
Syntax errors happen when the python interpreter doesn't understand what you typed. Check your program carefully!
>>> 3a = 2 File "<stdin>", line 1 3a = 2 ^ SyntaxError: invalid syntax
Variables cannot start with a digit, so we get a syntax error.
>>> if a < 5 File "<stdin>", line 1 if a < 5 ^ SyntaxError: invalid syntax
Every statement like if
, while
and so on needs to be ended with :
, otherwise we get an error.
>>> c+3 Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'c' is not defined
The c
variable was not assigned anything to previously. Initialize every variable before using it.
>>> if a >= 3: ... print(a+3) ... print(a-3) File "<stdin>", line 3 print(a-3) ^ IndentationError: unindent does not match any outer indentation level
Every syntactic block is indented and its istruction have the same alignment. In this case adding two spaces at the beginning of the third line would make the code correct.
>>> i = 0 >>> while i < 1000: ... print(i)
Don't forget to increment the index variable at the end of the loop, otherwise your program will never finish.