Computer Programming || Gaming || Technology || ai

Python Basics


  1. print(‘Hello world!’)
  2. print(‘Spam and eggs…’)
  3. 5 + 4 – 3
  4. 2 * (3 + 4)
  5. (-7 + 2) * (-4)
  6. 11 / 0
  7. 9.8765000
    9.8765
  8. 6 * 7.0
    42.0
  9. 9 ** (1/2)
    3.0
  10. (-7 + 2) * (-4)
  11. 20 // 6
  12. 1.25 % 0.5
  13. “Python is fun!”
  14. \n
  15. print(“Hello\nWorld!”)
  16. input(“Enter something please: “)
  17. print(“First string” + “, ” + “second string“)
  18. “2” + “2”
  19. 1 + ‘2’ + 3 + ‘4’
  20. print(“spam” * 3)
  21. 4 * ‘2’
  22. ’17’ * ’87’
  23. ‘pythonisfun’ * 7.0
  24. int(“2”) + int(“3”)
  25. float(input(“Enter a number: “)) + float(input(“Enter another number: “))
  26. x = “This is a string
    >>> print(x + “!”)
  27. del foo
  28. x += 3
    >>> print(x)
  29. Control Structures
  30. my_boolean = True
  31. 7 > 5
    True
  32. 9 >= 9.0
    True
  33. if 10 > 5:
    print(“10 greater than 5”)
  34. num = 12
    if num > 5:
    print(“Bigger than 5”)
    if num <=47:
    print(“Between 5 and 47”)
  35. x = 4
    if x == 5:
    print(“Yes”)
    else:
    print(“No”)
  36. num = 7
    if num == 5:
    print(“Number is 5”)
    else:
    if num == 11:
    print(“Number is 11”)
    else:
    if num == 7:
    print(“Number is 7”)
    else:
    print(“Number isn’t 5, 11 or 7”)
  37. num = 7
    if num == 5:
    print(“Number is 5”)
    elif num == 11:
    print(“Number is 11”)
    elif num == 7:
    print(“Number is 7”)
    else:
    print(“Number isn’t 5, 11 or 7”)
  38. 1 != 1 and 2 == 2
    False
  39. 1 != 1 or 2 == 2
    True
  40. not 1 == 1
    False
  41. False == (False or True)
    False
  42. i = 1
    while i <=5:
    print(i)
    i = i + 1
  43. i = 0
    while 1==1:
    print(i)
    i = i + 1
    if i >= 5:
    print(“Breaking”)
    break
  44. i = 0
    while True:
    i = i +1
    if i == 2:
    print(“Skipping 2”)
    continue
    if i == 5:
    print(“Breaking”)
    break
    print(i)
  45. number = 3
    things = [“string“, 0, [1, 2, number], 4.56]
    print(things[1])
    print(things[2])
    print(things[2][2])
  46. str = “Hello world!”
    print(str[6])
  47. nums = [1, 2, 3]
    print(nums + [4, 5, 6])
    print(nums * 3)
    Try It Yourself

    Result:>>>
    [1, 2, 3, 4, 5, 6]
    [1, 2, 3, 1, 2, 3, 1, 2, 3]

  48. words = [“spam”, “egg”, “spam”, “sausage”]
    print(“spam” in words)
    print(“egg” in words)
    print(“tomato” in words)
  49. nums = [1, 2, 3]
    print(not 4 in nums)
    print(4 not in nums)
    print(not 3 in nums)
    print(3 not in nums)
  50. nums = [1, 2, 3]
    nums.append(4)
    print(nums)
  51. nums = [1, 3, 5, 2, 4]
    print(len(nums))
  52. words = [“Python”, “fun”]
    index = 1
    words.insert(index, “is”)
    print(words)
  53. letters = [‘p’, ‘q’, ‘r’, ‘s’, ‘p’, ‘u’]
    print(letters.index(‘r’))
    print(letters.index(‘p’))
    print(letters.index(‘z’))
    Try It Yourself

    Result:>>>
    2
    0
    ValueError: ‘z’ is not in list

  54. numbers = list(range(10))
    print(numbers)
  55. numbers = list(range(3, 8))
    print(numbers)
    print(range(20) == range(0, 20))Try It Yourself

    Result:>>>
    [3, 4, 5, 6, 7]

    True

  56. numbers = list(range(5, 20, 2))
    print(numbers)
    Try It Yourself

    Result:>>>
    [5, 7, 9, 11, 13, 15, 17, 19]

  57. words = [“hello”, “world”, “spam”, “eggs”]
    counter = 0
    max_index = len(words) – 1while counter <= max_index:
    word = words[counter]
    print(word + “!”)
    counter = counter + 1
  58. words = [“hello”, “world”, “spam”, “eggs”]
    for word in words:
    print(word + “!”)
  59. for i in range(5):
    print(“hello!”)
    Try It Yourself

    Result:>>>
    hello!
    hello!
    hello!
    hello!
    hello!
    >>>

  60. DRY
  61. def my_func():
    print(“spam”)
    print(“spam”)
    print(“spam”)my_func()
  62. def print_with_exclamation(word):
    print(word + “!”)print_with_exclamation(“spam”)
    print_with_exclamation(“eggs”)
    print_with_exclamation(“python”)
  63. def print_sum_twice(x, y):
    print(x + y)
    print(x + y)print_sum_twice(5, 8)
  64. def function(variable):
    variable += 1
    print(variable)function(7)
    print(variable)
  65. def max(x, y):
    if x >=y:
    return x
    else:
    return yprint(max(4, 7))
    z = max(8, 5)
    print(z)
  66. def add_numbers(x, y):
    total = x + y
    return total
    print(“This won’t be printed”)print(add_numbers(4, 5))
  67. x = 365
    y = 7
    # this is a commentprint(x % y) # find the remainder
    # print (x // y)
    # another comment
  68. def shout(word):
    “””
    Print a word with an
    exclamation mark following it.
    “””

    print(word + “!”)shout(“spam”)
  69. def multiply(x, y):
    return x * ya = 4
    b = 7
    operation = multiply
    print(operation(a, b))
  70. def add(x, y):
    return x + y
    def do_twice(func, x, y):
    return func(func(x, y), func(x, y))a = 5
    b = 10print(do_twice(add, a, b))
  71. import randomfor i in range(5):
    value = random.randint(1, 6)
    print(value)
  72. from math import piprint(pi)
  73. from math import sqrt as square_root
    print(square_root(100))
  74. Common exceptions:
    ImportError: an import fails;
    IndexError: a list is indexed with an out-of-range number;
    NameError: an unknown variable is used;
    SyntaxError: the code can’t be parsed properly;
    TypeError: a function is called on a value of an inappropriate type;
    ValueError: a function is called on a value of the correct type, but with an inappropriate value.
  75. try:
    num1 = 7
    num2 = 0
    print (num1 / num2)
    print(“Done calculation”)
    except ZeroDivisionError:
    print(“An error occurred”)
    print(“due to zero division”)
  76. try:
    variable = 10
    print(variable + “hello”)
    print(variable / 2)
    except ZeroDivisionError:
    print(“Divided by zero”)
    except (ValueError, TypeError):
    print(“Error occurred”)
  77. try:
    word = “spam”
    print(word / 0)
    except:
    print(“An error occurred”)
  78. try:
    print(1)
    print(10 / 0)
    except ZeroDivisionError:
    print(unknown_var)
    finally:
    print(“This is executed last”)
  79. name = “123”
    raise NameError(“Invalid name!”)
  80. try:
    num = 5 / 0
    except:
    print(“An error occurred”)
    raise
  81. print(1)
    assert 2 + 2 == 4
    print(2)
    assert 1 + 1 == 3
    print(3)
  82. temp = -10
    assert (temp >= 0), “Colder than absolute zero!”
  83. myfile = open(“filename.txt”)
  84. # write mode
    open(“filename.txt”, “w”)# read mode
    open(“filename.txt”, “r”)
    open(“filename.txt”)

    # binary write mode
    open(“filename.txt”, “wb”)

  85. file = open(“filename.txt”, “w”)
    # do stuff to the file
    file.close()
  86. file = open(“filename.txt”, “r”)
    cont = file.read()
    print(cont)
    file.close()
  87. file = open(“filename.txt”, “r”)
    file.read()
    print(“Re-reading”)
    print(file.read())
    print(“Finished”)
    file.close()
  88. file = open(“filename.txt”, “r”)
    print(file.readlines())
    file.close()
  89. file = open(“newfile.txt”, “w”)
    file.write(“This has been written to a file”)
    file.close()file = open(“newfile.txt”, “r”)
    print(file.read())
    file.close()
  90. msg = “Hello world!”
    file = open(“newfile.txt”, “w”)
    amount_written = file.write(msg)
    print(amount_written)
    file.close()
  91. try:
    f = open(“filename.txt”)
    print(f.read())
    finally:
    f.close()
  92. with open(“filename.txt”) as f:
    print(f.read())
  93. def some_func():
    print(“Hi!”)var = some_func()
    print(var)
  94. ages = {“Dave”: 24, “Mary”: 42, “John”: 58}
    print(ages[“Dave”])
    print(ages[“Mary”])
  95. primary = {
    “red”: [255, 0, 0],
    “green”: [0, 255, 0],
    “blue”: [0, 0, 255],
    }print(primary[“red”])
    print(primary[“yellow”])
  96. bad_dict = {
    [1, 2, 3]: “one two three”,
    }
  97. nums = {
    1: “one”,
    2: “two”,
    3: “three”,
    }
    print(1 in nums)
    print(“three” in nums)
    print(4 not in nums)
  98. pairs = {1: “apple”,
    “orange”: [2, 3, 4],
    True: False,
    None: “True”,
    }print(pairs.get(“orange”))
    print(pairs.get(7))
    print(pairs.get(12345, “not in dictionary“))
  99. words = (“spam”, “eggs”, “sausages”,)
  100. my_tuple = “one”, “two”, “three”
    print(my_tuple[0])
  101. squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    print(squares[2:6])
    print(squares[3:8])
    print(squares[0:1])
  102. squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    print(squares[:7])
    print(squares[7:])
  103. squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    print(squares[::2])
    print(squares[2:8:3])
  104. squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    print(squares[1:-1])
  105. cubes = [i**3 for i in range(5)]print(cubes)
  106. evens=[i**2 for i in range(10) if i**2 % 2 == 0]print(evens)
  107. even = [2*i for i in range(10**100)]
  108. nums = [4, 5, 6]
    msg = “Numbers: {0} {1} {2}”. format(nums[0], nums[1], nums[2])
    print(msg)
  109. a = “{x}, {y}”.format(x=5, y=12)
    print(a)
  110. print(“, “.join([“spam”, “eggs”, “ham”]))
    #prints “spam, eggs, ham”print(“Hello ME”.replace(“ME”, “world”))
    #prints “Hello world”

    print(“This is a sentence.”.startswith(“This”))
    # prints “True”

    print(“This is a sentence.”.endswith(“sentence.”))
    # prints “True”

    print(“This is a sentence.”.upper())
    # prints “THIS IS A SENTENCE.”

    print(“AN ALL CAPS SENTENCE”.lower())
    #prints “an all caps sentence”

    print(“spam, eggs, ham”.split(“, “))
    #prints “[‘spam’, ‘eggs’, ‘ham’]”

  111. print(min(1, 2, 3, 4, 0, 2, 1))
    print(max([1, 4, 9, 2, 5, 6, 8]))
    print(abs(-99))
    print(abs(42))
    print(sum([1, 2, 3, 4, 5]))
  112. nums = [55, 44, 33, 22, 11]if all([i > 5 for i in nums]):
    print(“All larger than 5”)

    if any([i % 2 == 0 for i in nums]):
    print(“At least one is even”)

    for v in enumerate(nums):
    print(v)

  113. for char in “abcdefghijklmnopqrstuvwxyz”:
    perc = 100 * count_char(text, char) / len(text)
    print(“{0} – {1}%”.format(char, round(perc, 2)))

Have any Question or Comment?

One comment on “Python Basics

Leave a Reply

Your email address will not be published. Required fields are marked *




Calender

October 2020
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031