Instructor: David Cao (davidcao@seas) TAs: Winnie Wang (winniew1@sas) Jack Hourigan (hojack@seas)
# Isn't Python great? print("Hello, World!")
// Java class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
// Go package main import "fmt" func main() { fmt.Println("hello world") }
// C++ #include <stdio.h> int main() { printf("Hello, World!"); return 0; }
// rust fn main() { println!("Hello World!"); }
There are two ways of running Python. Either we can invoke Python directly within it's interpreter, or we can write files with our Python code.
❯ python Python 3.10.12 (main, Jan 18 2024, 12:41:08) [Clang 15.0.0 (clang-1500.1.0.2.5)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
>>> 5 + 10 15 >>> 5 ** 2 25 >>> my_var = "Hello, World!" >>> print(my_var) Hello, World! >>>
If you've written your Python in a file, you can simply run it like so
❯ echo "print('Hello, World!')" > my_script.py ❯ python my_script.py Hello, World!
my_object = MyClass() my_object.do_something()
def my_func(a, b, c): ... # functions themselves are objects! print(my_func) # prints out: <function my_func at 0x102aad990>
# my incredibly insightful comment """ a really long and more insightful comment that needs multiple lines """ print("Hello, World!")
>>> my_var = 10 # no type declaration needed! >>> type(my_var) int >>> my_var = "hello!" >>> type(my_var) str >>> my_var = 10 >>> str(my_var) "10" >>> print(my_var) # print casts everything to a str implicitly >>> my_var = "10" >>> int(my_var) 10 >>> my_var = None # None is Python's null >>> type(my_var) NoneType >>> type(type(my_var)) # every type is type type :) type
# note the : token to indicate a scope if x > 15: print("x is larger than 15") elif x < 15: print("x is less than 15") else: print("x is exactly 15") # this could also be written as if x > 15: print("x is larger than 15") elif x < 15: print("x is less than 15") else: print("x is exactly 15") # but I don't recommend it as it looks messy # however, these are useful as one-line control statements y = "gt" if x > 15 else "lte"
i = 0 # again note the : token and indentation while i < 10: print(i) i += 1 # there is no do-while in Python, instead while True: do_something() if condition: break # exit loop
for i in range(0,10): print(i) for i in range(0,10): if i % 2 == 0: # skip below code and continue loop continue print(i)
# functions are defined using the "def" keyword # once again, we see our good friend : def my_func(x): return x + 5 def my_func(x): # you can stub out functions with the pass keyword # my_var = my_func(x) # will result in my_var = None pass
We will revisit functions later to see the power of Python's functional attributes!