<a target="_blank" href="https://drive.google.com/file/d/1EGR30nWyoyZmbLMtD1J6-6gPpt4rTVCy/view?usp=sharing"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a> <br /> # Intro to Python - Part 1 If you've never programmed before, this tutorial is recommended for you. In this notebook, we focus on fundamental concepts of programming in Python: - **Variables** & **Operators** - **Booleans** & **Conditionals** - **Lists** & **Loops** - **Functions** ## Hello world `print` is a Python function that displays the value passed to it on the screen. We call functions by putting parentheses after their name, and putting the inputs (or _arguments_) to the function in those parentheses `()`. ```python # The print function print('Hello world!') print("Hello Ma'am") print('I "said" just do it') print(1,2,3,4,5,6,7, sep=',', end='|') print(8,9,10,11,12,13,14, sep='.') ``` Hello world! Hello Ma'am I "said" just do it 1,2,3,4,5,6,7|8.9.10.11.12.13.14 The first line above is a **comment**. In Python, comments begin with the `#` symbol. Comments are not executed and they are used for noting down important concept. ## Variables & Operators ### Value A **value** is one of the basic things a program works with, like a letter or a number. The values we have seen so far are `1`, `2`, and `'Hello, World!'`. These values belong to different **types**: `2` is an integer, and `'Hello, World!'` is a **string**, so-called because it contains a “string” of letters. ```python type('Hello world!') ``` str ```python type(2) ``` int ### Variables One of the most powerful features of a programming language is the ability to manipulate **variables**. A variable is a name that refers to a value. An **assignment statement** creates new variables and gives them values: ```python name = "CoderSchool" pi = 3.1415926535897932 n = 21 print(type(name)) print(type(pi)) print(type(n)) ``` <class 'str'> <class 'float'> <class 'int'> A `float` is a number with a decimal place - very useful for representing things like weights or proportions. **Reassigning** the value of an existing variable looks just the same as creating a variable - it still uses the `=` assignment operator. Try reading over the code below and predicting what it's going to do when run. ```python a = 1 print(a) a = 2 print(a) a = a + 2 print(a) ``` ### Operators **Operators** are special symbols that represent computations like addition and multiplication. | Operator | Name | Description | | -------- | -------------- | -------------------------------------------------- | | `a + b` | Addition | Sum of `a` and `b` | | `a - b` | Subtraction | Difference of `a` and `b` | | `a * b` | Multiplication | Product of `a` and `b` | | `a / b` | True division | Quotient of `a` and `b` | | `a // b` | Floor division | Quotient of `a` and `b`, removing fractional parts | | `a % b` | Modulus | Integer remainder after division of `a` by `b` | | `a ** b` | Exponentiation | `a` raised to the power of `b` | | `-a` | Negation | The negative of `a` | ```python a = 16 b = 3 print(a // b) print(a % b) print(a ** b) ``` 5 1 4096 ## Booleans & Conditionals ### Booleans Python has a type **`bool`** which can take on one of two values: **`True`** and **`False`**. ```python x = True print(x) print(type(x)) ``` True <class 'bool'> Rather than putting `True` or `False` directly in our code, we usually get boolean values from **Boolean Operators**. These are operators that answer yes/no questions. We'll go through some of these operators below. | Operation | Description | | --------- | -------------------------------- | | `a == b` | `a` equal to `b` | | `a != b` | `a` not equal to `b` | | `a < b` | `a` less than `b` | | `a > b` | `a` greater than `b` | | `a <= b` | `a` less than or equal to `b` | | `a >= b` | `a` greater than or equal to `b` | > Notice > Remember to use `==` instead of `=` when making comparisons. > > - If you write `n == 2` you are asking about the value of n. > - When you write `n = 2` you are changing the value of n. There are three **logical operators**: `and`, `or`, and `not`. The semantics (meaning) of these operators is similar to their meaning in English. For example, `x > 0 and x < 10` is true only if x is greater than 0 and less than 10. `n%2 == 0 or n%3 == 0` is true if either of the conditions is true, that is, if the number is divisible by 2 or 3. Finally, the `not` operator negates a boolean expression, so `not (x > y)` is true if `x > y` is false, that is, if x is less than or equal to y. ### Conditional if statement In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the program accordingly. **Conditional statements** give us this ability: ```python x = 1 if x > 0: print('x is positive') elif x < 0: print('x is negative') else: print('x is zero') ``` x is positive ## Lists & Loops ### Lists Lists in Python represent ordered sequences of values. They can be defined with comma-separated values between square brackets. For example, here is a list of the first few prime numbers: ```python primes = [2, 3, 5, 7, 11, 13, 17, 19] ``` We can access individual list elements using Python's square bracket indexing syntax. Python uses **_zero-based_** indexing, so the first element has index 0. ```python primes[0] ``` 2 Elements at the end of the list can be accessed with negative numbers, starting from -1: ```python primes[-1] ``` 19 ### `for` Loop Loops are a way to repeatedly execute some code. Here's an example: ```python for i in primes: print('i =', i) ``` i = 2 i = 3 i = 5 i = 7 i = 11 i = 13 i = 17 i = 19 The `for` loop specifies: - The variable name to use (in this case, `i`) - The set of values to loop over (in this case, `prime`) You use the word **`in`** to link them together. The object to the right of the "`in`" can be any object that supports iteration. Basically, if it can be thought of as a group of things, you can probably loop over it. ```python for i in range(5): print('hello') ``` **`range()`** is a function that returns a sequence of numbers. It turns out to be very useful for writing loops. In the example, we want to repeat the action print out 'hello' 5 times. ### `while` loop The other type of loop in Python is a `while` loop, which iterates until some condition is met: ```python n = 10 while n > 0: print(n) n = n - 1 print('Booooom!!') ``` 10 9 8 7 6 5 4 3 2 1 Booooom!! The argument of the `while` loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False. ## Functions In the context of programming, a **function** is a named sequence of statements that performs a computation. When you define a function, you specify the name and the sequence of statements. Later, you can “call” the function by name. Functions start with a header introduced by the `def` keyword. The indented block of code following the `:` is run when the function is called. ```python def is_odd(n): if n % 2 == 1: print(n, 'is an odd number') else: print(n, 'is an even number') ``` ```python is_odd(2) ``` 2 is an even number ```python is_odd(3) ``` 3 is an odd number **`return`** is another keyword uniquely associated with functions. When Python encounters a `return` statement, it exits the function immediately, and passes the value on the right hand side to the calling context. ```python def is_odd_with_return(n): if n % 2 == 1: return "It's an odd number" else: return "It's an even number" print('This will never be showed') ``` ```python print(is_odd_with_return(2)) ``` It's an even number ```python print(is_odd(2)) ``` 2 is an even number None Without a `return` statement, a function will return a special value `None`. ## Exercises Let's meet our little turtle again. | Function | Description | | ----------------- | ------------------------------------------------------------------------------------------------------------------------ | | `forward(units)` | Moves the turtle in the direction it is facing, by units pixels | | `backward(units)` | Moves the turtle in the opposite of the direction it is facing, by units pixels | | `right(degrees)` | Turns the turtle to right by the given degrees many degrees | | `left(degrees)` | Turns the turtle to left by the given degrees many degrees | | `goto(x, y)` | Moves the turtle to the point defined by `x`, `y` | | `penup()` | Lifts the pen, turtles movement will not draw anything after this function is called | | `pendown()` | Puts the pen down, causing the turtle movements to start drawing again | | `pensize(w)` | Changes the width of the pen | | `speed(s)` | Sets the speed of turtle's movements. s can be a value in interval `[1,13]` where 1 is the slowest and 13 is the fastest | | `bgcolor(c)` | Change the background color | | `color(c)` | Change the pen color | | `clear()` | Clear any drawing on the screen | **Run the cells below before you start** ```python !pip3 install ColabTurtle ``` ```python # Import the library from ColabTurtle.Turtle import * ``` ### Exercise 1 Read the code below and draw on paper what will be the output: ```python initializeTurtle() speed(13) big_line = 100 little_line = 50 angle = 90 left(angle) forward(big_line) count = 0 while count < 4: right(angle//2) if count != 3: forward(little_line) else: forward(big_line) count = count + 1 right(90) forward(130) ``` ### Exercise 2 Read the code below and draw on paper what will be the output: ```python initializeTurtle() speed(13) count = 0 while(count < 180): forward(2) right(1) count = count + 1 right(45) forward(300) left(90) backward(150) right(45) backward(250) ``` ### Exercise 3 Write a function that takes a number from 10 to 200, and draw a square with the length equal the input number. ```python def draw_square(length): # YOUR CODE HERE initializeTurtle() speed(13) # YOUR_CODE_HERE ``` ### Exercise 4 Write a function that takes the inputs as three numbers `x`, `y`, and `r`. The function should draw a circle with radius `r` and the center at the coordinate (x, y). Here is the coordinate grid: <img src="https://i.imgur.com/T1aoL1e.png" width="400px"/> ```python import math pi = math.pi def draw_circle(x, y, r): initializeTurtle() speed(13) # YOUR_CODE_HERE ``` ### Exercise 5 Write a function that draw a grid of plus sign that looks like below: <img src="https://i.imgur.com/Fm8l85y.png" width="400px" /> The distance between two adjacent plus signs on the same row or column is **100 pixels**. ```python # YOUR_CODE_HERE ``` ## References - [CheckIO](http://www.checkio.org/): a gamified website containing programming tasks in Python 3 - [LearnPython](https://www.learnpython.org/): an interactive Python tutorial that is suitable for absolute beginners - [Automate the Boring Stuff with Python](https://automatetheboringstuff.com/): small and practical programs to automate tasks on the computer - [Think Python](https://greenteapress.com/thinkpython/html/index.html): how to think like a computer scientist