CS50 - getting start

Get input from user and print

In [1]:
age = input("Your age? ") # python 3, raw_input for python 2
print("Your age:",age) # don't need space after "age"
Your age? 30
Your age: 30

Nếu dùng cs50, thì cần phải cài nó trước, có thể đọc trong Python note 1.

pip install cs50

Ví dụ bên dưới, nhận input số từ người dùng (nhưng chỉ ở dạng string, chuyển qua float trước khi sử dụng)

In [3]:
# not convert
x = input("x: ")
y = input("y: ")
kq = x+y
print("kq:",kq) # like a string
x: 12
y: 5
kq: 125
In [4]:
# convert to float
x2 = float(input("x: "))
y2 = float(input("y: "))
kq2 = x2+y2
print("kq2:",kq2) # it's numbers
x: 12
y: 5
kq2: 17.0
In [5]:
# convert to int
x3 = int(input("x: "))
y3 = int(input("y: "))
kq3 = x3+y3
print("kq3:",kq3) # it's int, not float
x: 12
y: 5
kq3: 17
In [8]:
# wrong input
x4 = int(input("x:"))
kq4 = x4**5
print("kq4:",kq4)
x:a
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-30799f53c534> in <module>()
      1 # wrong input
----> 2 x4 = int(input("x:"))
      3 kq4 = x4**5
      4 print("kq4:",kq4)

ValueError: invalid literal for int() with base 10: 'a'

From cs50 library

In [10]:
from cs50 import get_int

def main():
    i = get_int("integer: ")
    print(f"hello,{i}")
    
if __name__ == "__main__":
    main()
integer: hello,None

Turtle

In [12]:
import turtle

def draw_square(t, sz):
    """Make turtle t draw a square of sz."""
    for i in range(4):
        t.forward(sz)
        t.left(90)

wn = turtle.Screen()        # Set up the window and its attributes
wn.bgcolor("lightgreen")
wn.title("Alex meets a function")

alex = turtle.Turtle()      # Create alex
draw_square(alex, 50)       # Call the function to draw the square
wn.mainloop()