print("Zeile")
if 1 > 2:
print("Five is greater than two!")
print("This is a second statement.")
else:
print("The world is a disk!")
Zeile The world is a disk!
if 5 > 2:
print("Five is greater than two!")
Cell In[4], line 2 print("Five is greater than two!") ^ IndentationError: expected an indented block
The code below prints the full list
import keyword
print(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
# This is a comment
print("Hello, World!")
print("Hello, World!") #This is a comment
print()
command.Let's see some examples
x = 10
print(x)
x = "This is a string"
print(x)
10 This is a string
snake_case
(all lowercase letters with words separated by underscores).ALL_CAPS
with words separated by underscores. Constants are usually defined at the top of a module.is
, has
, can
, or should
. E.g., is_approved
PascalCase
(each word starts with an uppercase letter, no underscores).x = 4
y = 5
z = x + y
print(z)
x = "Text"
y = " more text"
z = x + y
print(z)
9 Text more text
These are the built-in data types of Python
Type Category | Data Types |
---|---|
Text Type | 'str' |
Numeric Types | 'int', 'float', 'complex' |
Sequence Types | 'list', 'tuple', 'range' |
Mapping Type | 'dict' |
Set Types | 'set', 'frozenset' |
Boolean Type | 'bool' |
Binary Types | 'bytes', 'bytearray', 'memoryview' |
None Type | 'NoneType' |
Some of these we will use soon, while others you will learn throughout the semester.
bool
has only two possible values: True
or False
True
or False
.False
correspons to the value of 0, any other number is considerd True
(will be important for casting to bool)x = (10 < 9)
print(x)
False
is_true = 10 > 9
if (is_true):
print("10 is greater than 9")
10 is greater than 9
Python konws 3 numeric data types:
| Type | Explanation | Example |
| --------- | ----------------------------------------------------------------------------------------------------- | ---------------------- |
| int
| A whole number, positive or negative, without decimals, of unlimited length. | 3, 88, -12837654 |
| float
| Float, or "floating point number" is a number, positive or negative, containing one or more decimals. | 7.5, 1212.875620, 35e3 |
| complex
| Complex numbers are written with a "j" as the imaginary part: | 3+5j |
x = 10 # int
y = 10.0 # float needs a .0 to be a float
z = 2 + 3j # complex
Float can also be scientific numbers with an "e" to indicate the power of 10
x = 35e3
print(x)
35000.0
str
'hello'
can be used as well as "hello"
.my_name = "John \"guitar\" \\\" Mayer"
print(my_name)
my_name = 'John'
John "guitar" \" Mayer
my_text = "this is 'ok' a double-quote needs an escape: \" to work"
my_text = 'here we can use "" but \' must be escaped'
print("this is a \nreturn")
this is a return
first_name = "John"
last_name = "Doe"
full_name = first_name +"\n "+ last_name
print(full_name)
John Doe
print(full_name.upper())
print(full_name.count("oe"))
JOHN DOE 1
Here are the most important ones:
a = str(3) # Change an int value to a string
print(type(a))
b = int(3.7) # Change a float value to an int
print(b)
c = float(3) # Change an int value to a float
print(c)
c = int("3") # Change a string value to a int
print(c)
<class 'str'> 3 3.0 3
is
operator checks whether two variables point to the same object in memory, not just if they have the same value.x = 10.0
id(x)
4562233424
y = x
id(y)
4562233424
x is y
True
x is 10.0
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="? <>:1: SyntaxWarning: "is" with a literal. Did you mean "=="? /var/folders/9d/kn6wbnzj4d59jnkrn0n0qmbc0000gn/T/ipykernel_74124/938034634.py:1: SyntaxWarning: "is" with a literal. Did you mean "=="? x is 10.0
False
y = 20.0
print(id(y))
x = y
print(id(x))
x = 12
print(id(x))
4562233424 4562233424 4518236264
x = 10
print(type(x))
x = "This is a string"
print(type(x))
<class 'int'> <class 'str'>
print()
Reference: https://www.w3schools.com/python/python_operators.asp
We need arithmetic operators to calculate.
Operator | Name | Example |
---|---|---|
+ |
Addition | x + y |
- |
Subtraction | x - y |
* |
Multiplication | x * y |
/ |
Division | x / y |
% |
Modulus | x % y |
** |
Exponentiation | x ** y |
// |
Floor division | x // y |
5**2
25
We need assignment operators to assign values to variables.
Operator | Example | Same As |
---|---|---|
= |
x = 5 |
x = 5 |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
x = 5
x *=2
print(x)
10
Comparison operators are needed to make decisions.
The result of a comparison operator is always true
or false
.
Operator | Name | Example |
---|---|---|
== |
Equal | x == y |
!= |
Not equal | x != y |
> |
Greater than | x > y |
< |
Less than | x < y |
>= |
Greater than or equal to | x >= y |
<= |
Less than or equal to | x <= y |
4 == 2
False
4 > 2
True
Logical operators are important if a decision is more complex and needs to consider several comparisons.
The logical operators can only compare values of True
(>0) or False
(=0) and result in True
or False
.
Here's the table formatted in Markdown:
Operator | Description | Example |
---|---|---|
and |
Returns True if both statements are true | x < 5 and x < 10 |
or |
Returns True if one of the statements is true | x < 5 or x < 4 |
not |
Reverses the result; returns False if true | not (x < 5 and x < 10) |
x = 7
not (x > 5 and x < 10)
False
x = 4
if (x > 5):
print("x is greater than 5")
elif
parts, and the else
x = 3
if x > 5:
print("x is greater than 5")
elif x < 2:
print("x is less than 2")
else:
print("x between 2 and 5")
x between 2 and 5
while
statement for loops:a = 0
while a < 10:
print(a)
a += 2
0 2 4 6 8
list
fruits = ["apple", "orange", "grape"]
apple = fruits[0]
print(fruits[1])
orange
Here are some examples of common list actions:
fruits = ["apple", "orange", "grape", "orange"]
fruits.append("banana") # add a new element to the end
print(fruits)
fruits.insert(1, "cherry") # add a new element at index 1
print(fruits)
fruits.pop(2) # remove element at position 2
print(fruits)
fruits.sort() # sort the list
same_fruits = fruits.copy() # returns a copy of the list
print(fruits)
['apple', 'orange', 'grape', 'orange', 'banana'] ['apple', 'cherry', 'orange', 'grape', 'orange', 'banana'] ['apple', 'cherry', 'grape', 'orange', 'banana'] ['apple', 'banana', 'cherry', 'grape', 'orange']
list1 = ["abc", 34, True, 40, "male"]
for ... in ...:
statement for thisfruits = ["apple", "orange", "grape", "banana"]
for fruit in fruits:
print(fruit)
apple orange grape banana
range()
function to create a list of arithmetic progressionslist = range(5) # Creates a list with 5 values, starting from 0
list = range(5, 10) # Creates a list with int from 5 to 9 (interval 5, 10)
list = range(0, 10, 3) # Creates a list auf values between 0 and 10 with increase of 3 very step
for i in range(0, 8, 2): # in C++ this would be for (int i=0; y<10; i+=2)
print(i)
0 2 4 6
for
and while
loopsbreak
jumps out of the complete loop and continues after the loop statementcontinue
continues with the next iteration of the loopfor i in range(10):
if i == 1:
continue # go to the next loop, don't execute code below
if i == 4:
break # completely jump out of the loop
print(i)
print("This is the next line of code after the loop")
0 2 3 This is the next line of code after the loop