π Python Basic#
Note
The only way to learn a new programming language is by writing programs in it. - Dennis Ritchie (inventor of C programming language)
Running Python#
Running Python in VS Code#
To open the
ece487_wksp
folder in VS Code, right-click on it and chooseOpen with Code
from the menu.To open the
Terminal
window, go to View and click onTerminal
.Type in
python
and pressEnter
This will launch the Python Shell, where you can input code and see the output. The Shell acts as a sandbox, allowing you to try out code snippets and get immediate feedback. For example, in the Shell, type
2+3
and press Enter, and it will display5
on the next line.Try the following code in the Shell:
2+3 "hello"+" world" a = 2 print(a)
The Python Shell behaves like a calculator, allowing you to perform various mathematical operations.
Now, try the follownig code:
2+2 # add two integers 2+2.0 # add an integer to a floating point number 2*3 # 2 times 3 2**2 # 2 squared 2**3 # 2 cubed 2**128 # Unlike C, integers in Python does not have a size limitation. 2/3 # It returns 1 in C, but 0.6666666666666 in Pyton 2/3.0 # Same as 2/3 in Python. 2//3 # modulo (remainder), same as 2%3 in C 4//3 # modulo (remainder), same as 4%3 in C
To exit the Python Shell, type
exit()
and pressEnter
, or useCtrl+z
and pressEnter
.
Running Python in Command Prompt#
Open Command Prompt or PowerShell (or Terminal on Mac and Ubuntu), and run
python
on Windows orpython3
on Mac.This will open the Python Shell.
Python Programming#
Variables#
Numeric types:
int
,float
,long
,complex
String:
str
Boolean:
bool
(True
/False
)
Pythonβs simple types are summarized in the following table:
Type |
Example |
Description |
---|---|---|
|
|
String: characters or text |
|
|
integers (whole numbers) |
|
|
floating-point numbers (real numbers) |
|
|
Complex numbers (real and imaginary part) |
|
|
Boolean: |
|
|
Special object indicating nulls |
Use the
type()
function to find the type for a value or variable# String c = 'hello' print(type(c)) # Integer a = 1 print(type(a)) # Float b = 1.0 print(type(b)) # Boolean d = True print(type(d)) # None e = None print(type(e)) # Cast integer to string print(type(str(a)))
Math Operators#
+
,-
,*
, and/
Exponentiation:
**
Modulo (Remainder):
%
Logic Operators#
```python
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
```
Try the following code in Python Console.
2+2 2+2.0 2*3 2**3 # exponentiation 2**128 2/3 2/3.0 2//3 # integer division 4//3 2%3 # modulo 4%3 bin(5|2) # convert a number to binary after bit operations bin(5^1) bin(5&1) a = 6 b = 7 print(a==6) # boolean expressions print(a==7) print(a==6 and b==7) print(a==6 or b==6) print(not a==6 and b==6) print(not (a==6 and b==6))
Working with Variables#
In Python, variables store values like strings or numbers. Strings are blocks of text, such as
"Stan Baek is the legendary pirate captain."
Numbers can be integers or decimals.Try the the following code in Python Console.
# a string variable name = "Stan Baek"
You can check the type in use by issuing the type() command
type(name)
It will return
<class 'str'>
Add another string variable:
title = "the legendary pirate captain"
You can concatenate strings using
+
operator:character = name + ": " + title print(character) # It will print "Stan Baek: the legendary pirate captain"
Now, try combining a string with an integer:
# Integer variable age = 726 # This will raise an error print(character + age)
Convert the integer to a string for proper concatenation:
print(character + " is " + str(age) + " years old.")
This will print
Stan Baek: the legendary pirate captain is 726 years old.
You can also request input from the user:
age = input("How old are you? ") print(type(age)) # Since age is a string variable. We need to convert it to integer. age = int(age) # Floating-point numbers x = 3.141 print(type(x)) print(x) # Prints 3.141 print(int(x)) # Prints 3
When creating variables, remember that single or double quotes can be used for strings, but be consistent with your choice.
Functions and Modules#
Python has many built-in functions. For example:
name = "Stan Baek" len(name) # Returns the lenght of the string type(name) # Returns the type of the variable
To explore more built-in functions, visit Pythonβs built-in functions documentation. You can also use the
help()
function to get descriptions:help(len)
You can define your own functions in Python:
def add(a, b): return a+b print(add(3, 4)) # Outputs 7
Python Modules#
You can add extra functionality to Python by importing modules. Modules are collections of additional functions built by others. For example, to access advanced mathematical functions, you can import the
math
module:import math print(math.sqrt(16)) # Outputs 4.0 print(math.sin(math.pi/2)) # Outputs 1.0 print(math.cos(0)) # Outputs 1.0
In Python, itβs a convention to import all required modules at the top of the script. This ensures all dependencies are loaded before theyβre used and makes the code easier to understand. You can also import specific functions from a module:
from math import sqrt, sin, pi print(sqrt(16)) print(sin(pi/2))
We can also import individual functions from a module
from math import sqrt, sin, pi print(sqrt(16)) print(sin(pi/2)) cos(0) # error because cos was not imported
You can also use an alias for a module:
import math as m m.sqrt(16) m.sin(m.pi/2)
Conditional Statements#
The
if
,else
, andelif
statements control the flow of execution based on conditions. The basic syntax is:if expression: statements elif expression: statements else: statements
If no action is needed for a certain condition, you can use the
pass
statement:if expression: pass # Do nothing. else: statements
Example:
word = input("Enter a four-letter word: ") if len(word) == 4: print(word, "is a four-letter word. Well done.") elif len(word) == 3: print(word, "is a three-letter word.") else: print(word, "is not a four-letter word.")
Loops#
Letβs start with a simple
while
statement.x = 1 while x < 5: print(x) x = x + 1
We can use
break
to exit a loop:while True: print(x) x -= 1 if x == 0: break
The
for
loop is commonly used in Python:for i in [0, 1, 2, 3, 4]: print(i)
We can also use
range()
:for i in range(5): # Loops through 0 to 4 print(i)