Python
Printing 'hello, world'
print("hello, world")
we don't need \n
or ;
here as we did in C
getting input
in C:
string answer = get_string("What's your name? ");
printf("hello, %s\n", answer);
in Python:
answer = get_string("What's your name? ")
print("Hello, " + answer)
F-Strings
The last program can be implemented in a different way as follows
answer = input("What's your name? ")
print(f"hello, {answer}")
Just like in C, we still have for counter variables
in C:
counter = 0;
counter = counter + 1;
/* or */
counter += 1;
/* or */
counter ++;
in Python
counter = 0
counter = counter + 1
# or
counter += 1
# this syntactic sugar does not exist
counter++
Conditions
in C:
if (x < y)
{
printf("x is less than y\n");
}
in Python:
if x < y:
print("X is less than y") # but indentation is must
illustrated in
Loops
in C:
we had while
, for
loops
e.g.
while (true)
{
printf("hello, world\n");
}
in Python:
while True: # True must be capitalized
print("hello, world")
illustrated in
repeating for a number of times
in C:
int i = 0;
while (i < 3)
{
printf("hello, world");
i++;
}
in Python
i = 0
while i < 3:
print("hello, world")
i += 1
like the for loop in C, we have a foreach loop in python
for i in [0, 1, 2]: # <-- this is a list
print("Hello, world")
Types
- Python is a "loosely typed language" while C is a "strongly typed language"
Data types in python:
- bool
- float
- int
- str (string)
Sequence types
other data types:
- range
- list (an array that resizes itself)
- tuple (for implementing comma separated values)
- dict (store)
- set (just like in maths without duplicate elements)
blur.py
from PIL import image, imageFilter
before = Image.open("bridge.bmp") # '.' is serving a new role here
# in C we used . to access a variable inside a struct
# in Python we can have functions inside a structure
after = before.filter(ImageFilter.BoxBlur(10))
after.save("out.bmp")