BWCha

CS50's Introduction to Programming with Python: Lesson 0

May 14th, 2023 (edited)
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.44 KB | None | 0 0
  1. LECTURE 0
  2.  
  3. >Creating Code with Python<
  4. *VS Code - Special type of text editor, a compiler
  5.          - Top: Text Editor
  6.          - Bottom: Terminal
  7. *In terminal: Execute ``code hello.py`` to start coding
  8. *In text editor: Type ``print("hello world")`` - Famous canonical program that nearly all coders write during the learning process
  9. *In terminal window: Can execute commands
  10.                      To run the program, cursor needs to be moved to the bottom of the screen. Type ``python hello.py`` next to the dollar sign to type a second command in the terminal and press the enter key
  11. *Result of running ``python hello.py`` program: ``hello, world``
  12.  
  13. >Functions<
  14. *Functions - Verbs or actions that the computer will already know how to perform
  15. *``Print`` function - Knows how to print to the terminal program
  16.                     - Takes arguments
  17.  
  18. >Bugs<
  19. *Bugs - Natural part of coding
  20.  
  21. >Improving Your First Python Program<
  22. *``input`` - Function that takes a prompt as an argument
  23.  
  24.         input("What's your name? ")
  25.         print("hello, world")
  26.  
  27. >Variables<
  28. *Variable - Container for a value within your own program
  29.  
  30.     *To introduce the variable in the program:
  31.  
  32.     name = input("What's your name? ")
  33.     print ("hello, world")
  34.  
  35.         ``=`` - Assigns what is on the right to what is on the left
  36.               - Value returned by ``input("What's your name? ")`` is assigned to ``name``
  37.  
  38.     *Further editing of the code:
  39.  
  40.     name = input("What's your name? ")
  41.     print("hello,")
  42.     print(name)
  43.  
  44.         >Result of the terminal window:
  45.             What's your name? |David|
  46.             |hello|
  47.             |David|
  48.  
  49. >Comments<
  50. *Comments - Way for programmers to track what they're doing in their programs; Notes
  51.  
  52.     # Insert comment here
  53.  
  54. >Pseudocode<
  55. *Pseudocode - Important type of comment that becomes a special type of to-do list, especially when you don't understand how to accomplish a coding task
  56.  
  57.     # Ask the user for their name
  58.     name = input("What's your name? ")
  59.  
  60.     # Print hello
  61.     print("hello,")
  62.  
  63.     # Print the name inputted
  64.     print(name)
  65.  
  66. >Further Improving Your First Python Program<
  67.  
  68.     *Can further edit the code as follows:
  69.  
  70.     # Ask the user for their name
  71.     name = input("What's your name? ")
  72.  
  73.     # Print hello and the inputted name
  74.     print("hello, " + name)
  75.  
  76.     *Can use a comma ``,`` to pass in multiple arguments by editing the code as follows:
  77.  
  78.     # Ask the user for their name
  79.     name = input("What's your name? ")
  80.  
  81.     # Print hello and the inputted name
  82.     print("hello, ", name)
  83.  
  84. >Strings and Parameters<
  85. *String ``str`` - Sequence of text
  86. *``print`` function - Automatically include a piece of code ``end='\n'``
  87.                     - Takes an argument called  ``end`` and the default is to create a new line
  88. *``\n`` - Indicates that the print function will automatically create a line break when run
  89. *Can also provide an argument for ``end`` such that a new line isn't created
  90.  
  91.     *Can modify the code as follows:
  92.  
  93.     # Ask the user for their name
  94.     name = input("What's your name? ")
  95.     print("hello, ", end="")
  96.  
  97. *``end=""`` - Over-writes the default value of ``end``, making it not create a new line after this first print statement
  98. *Parameters - Arguments that can be taken by a function
  99.  
  100. >A Small Problem with Quotation Marks<
  101. *Adding quotation marks as part of the string is challenging as ``print("hello,"friend"")`` won't work and compiler will throw an error
  102.     >2 Approaches to Fix the Issue:
  103.         1. Change the quotes to single quote marks
  104.         2. Code as ``print("hello, \"friend\"")``
  105.             ->Backslashes tell the compiler that the following character should be considered a quotation mark in the string
  106.  
  107. >Formatting Strings<
  108.     *Possibly the most elegant way to use strings would be as follows:
  109.  
  110.     # Ask the user for their name
  111.     name = input("What's your name? ")
  112.     print(f"hello, {name}")
  113.  
  114.         ->``f`` - Special indicator to Python to treat this string a special way, different than previous approaches
  115.  
  116. >More on Strings<
  117. *Built into strings is the ability to remove whitespace from a string
  118. *Method ``strip`` on ``name`` as ``name = name.strip()`` - Strips all the whitespace on the left and right of the user's input:
  119.  
  120.     # Ask the user for their name
  121.     name = input("What's your name? ")
  122.  
  123.     # Remove whitespace from the str
  124.     name = name.strip()
  125.  
  126.     # Print the output
  127.     print(f"hello, {name}")
  128.  
  129. *``title`` method - Title case the user's name:
  130.  
  131.     # Ask the user for their name
  132.     name = input("What's your name? ")
  133.  
  134.     # Remove whitespace from the str
  135.     name = name.strip()
  136.  
  137.     # Capitalize the first letter of each word
  138.     name = name.title()
  139.  
  140.     # Print the output
  141.     print(f"hello, {name}")
  142.  
  143. *Can up arrow to recall the most recent terminal commands that was made
  144.     *Code can be more efficient:
  145.  
  146.     # Ask the user for their name
  147.     name = input("What's your name? ")
  148.  
  149.     # Remove whitespace from the str and capitalize the first letter of each word
  150.     name = name.strip().title()
  151.  
  152.     # Print the output
  153.     print(f"hello, {name}")
  154.  
  155. *An even more efficient way:
  156.  
  157.     # Ask the user for their name, remove whitespace from the str, and capitalize the first letter of each word
  158.     name = input("What's your name? ").strip().title()
  159.  
  160.     # Print the output
  161.     print(f"hello, {name}")
  162.  
  163. >Intergers or int<
  164. *``int``  - Interger
  165.  
  166.     x = 1
  167.     y = 2
  168.  
  169.     z = x + y
  170.  
  171.     print(z)
  172.  
  173.     *Can make it more interactive using the ``input`` function:
  174.  
  175.     x = input("What's x? ")
  176.     y = input("What's y? ")
  177.  
  178.     z = x + y
  179.  
  180.     print(z)
  181.  
  182.     *Needs to convert this input from a string into an integer:
  183.  
  184.     x = input("What's x? ")
  185.     y = input("What's y? ")
  186.  
  187.     z = int(x) + int(y)
  188.  
  189.     print(z)
  190.  
  191. *Using int(x) is "Casting" - Where a value is temporarily changed from one type of variable [string] to another [interger]
  192.  
  193.     *Can further improve the program:
  194.  
  195.     x = int(input("What's x? "))
  196.     y = int(input("What's y? "))
  197.  
  198.     print (x + y)
  199.  
  200.     *Most inner function is run first, then the outer one is run
  201.  
  202. >Float Basics<
  203. *Floating Point Value - Real number that has a decimal point in it
  204.     *Can change the code to support floats:
  205.  
  206.     x = float(input("What's x? "))
  207.     y = float(input("What's y? "))
  208.  
  209.     print (x + y)
  210.  
  211. *``round`` - Available argument: ``round(number[n, digits])``
  212.                                     - Square brackets indicate that something optional can be specified
  213.                                     - Could do ``round(n)`` to round a digit to its nearest interger
  214.     *Alternatively, code can be as follows:
  215.  
  216.     # Get the user's input
  217.     x = float(input("What's x? "))
  218.     y = float(input("What's y? "))
  219.  
  220.     # Create a rounded result
  221.     z = round(x + y)
  222.  
  223.     # Print the result
  224.     print(z)
  225.  
  226.     *Formatting the output of long numbers, from 1000 to 1,000:
  227.  
  228.     # Get the user's input
  229.     x = float(input("What's x? "))
  230.     y = float(input("What's y? "))
  231.  
  232.     # Create a rounded result
  233.     z = round(x + y)
  234.  
  235.     # Print the result
  236.     print(f"{z:,}")
  237.  
  238. >More on Floats<
  239.     *To round floating point values:
  240.  
  241.     # Get the user's input
  242.     x = float(input("What's x? "))
  243.     y = float(input("What's y? "))
  244.  
  245.     # Create a rounded result [to the nearest 2 decimal points]
  246.     z = (x / y, 2)
  247.  
  248.     # Print the result
  249.     print(z)
  250.  
  251.     *Can use ``fstring`` to format the output below:
  252.  
  253.     # Get the user's input
  254.     x = float(input("What's x? "))
  255.     y = float(input("What's y? "))
  256.  
  257.     # Calculate the result
  258.     z = x / y
  259.  
  260.     # Print the result
  261.     print(f"{z:.2f}")
  262.  
  263.         *``fstring`` - Displays the same as the prior strategy
  264.  
  265. >Def<
  266.     *Starting from scratch:
  267.  
  268.     name = input("What's your name? ")
  269.     hello()
  270.     print(name)
  271.  
  272.         >Compiler will error because ``hello`` has no defined function
  273.  
  274.     *Creating own function called ``hello``:
  275.  
  276.     def hello():
  277.         print("hello")
  278.  
  279.     name = input("What's your name? ")
  280.     hello()
  281.     print(name)
  282.  
  283.         >Python is an idented language - Uses idention to understand what is part of the above function
  284.                                        - Everything in the ``hello`` function must be idented
  285.  
  286.     *Can further improve code:
  287.  
  288.     # Create own function
  289.     def hello(to):
  290.         print("hello,", to)
  291.  
  292.     # Output using own function
  293.     name = input("What's your name? ")
  294.     hello(name)
  295.  
  296.         >First lines: Creating ``hello` function; however, compiler is being told that this function takes a single parameter: a variable called ``to``
  297.             -> How values are passed into functions
  298.  
  299.     *Can add a default value to ``hello``:
  300.  
  301.     # Create or own function
  302.     def hello():
  303.         print("hello,", to)
  304.  
  305.     # Output using own function
  306.     name = input("What's your name? ")
  307.     hello(name)
  308.  
  309.     # Output without passing expected arguments
  310.     hello()
  311.  
  312.     *Functions don't need to be at the start of the program; they can be moved down but compiler needs to be told that there's a ``main`` function and a separate ``hello`` function:
  313.  
  314.     def main():
  315.        
  316.         # Output using own function
  317.         name = input("What's your name? ")
  318.         hello (name)
  319.  
  320.         # Output without passing expected arguments
  321.         hello ()
  322.  
  323.     # Create own function
  324.     def hello(to="world"):
  325.         print("hello,",to)
  326.  
  327.         >However, this alone will create an error as nothing in the code is actually running the ``main`` function
  328.  
  329.     *To call the main function:
  330.  
  331.     def main():
  332.  
  333.         # Output using own function
  334.         name = input("What's your name? ")
  335.         hello (name)
  336.  
  337.         # Output without passing expected arguments
  338.         hello ()
  339.  
  340.     # Create own function
  341.     def hello(to="world"):
  342.         print("hello,",to)
  343.  
  344.     main()
  345.  
  346. >Returning Values<
  347. *``return`` value   - "Passing back" of a value
  348.                     - Function to return the calculation's value back to another part of the program
  349.  
  350.     *Calculator.py; rework the code as follows:
  351.  
  352.     def main():
  353.         x = int(input("What's x? "))
  354.         print("x squared is", square(x))
  355.  
  356.     def square(n):
  357.         return n * n
  358.  
  359.     main()
  360.  
  361.         >``x`` is passed to ``square``; Calculation of ``x * x`` is returned back to the main function
Advertisement
Add Comment
Please, Sign In to add comment