🎧 New: AI-Generated Podcasts Turn your study notes into engaging audio conversations. Learn more

Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

Python Comments Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Creating a Comment Comments starts with a #, and Python will ignore them: #This is a comment print("Hello, World!") Comm...

Python Comments Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Creating a Comment Comments starts with a #, and Python will ignore them: #This is a comment print("Hello, World!") Comments can be placed at the end of a line, and Python will ignore the rest of the line: print("Hello, World!") #This is a comment A comment does not have to be text that explains the code, it can also be used to prevent Python from executing code: #print("Hello, World!") print("Cheers, Mate!") Multiline Comments Python does not really have a syntax for multiline comments. To add a multiline comment you could insert a # for each line: #This is a comment #written in #more than just one line print("Hello, World!") Or, not quite as intended, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it: """ This is a comment written in more than just one line """ print("Hello, World!") Python Variables Variables Variables are containers for storing data values. Creating Variables Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. x = 5 y = "John" print(x) print(y) Variables do not need to be declared with any particular type, and can even change type after they have been set. x = 4 # x is of type int x = "Sally" # x is now of type str print(x) Casting If you want to specify the data type of a variable, this can be done with casting. x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 Get the Type You can get the data type of a variable with the type() function. x = 5 y = "John" print(type(x)) print(type(y)) Single or Double Quotes? String variables can be declared either by using single or double quotes: x = "John" # is the same as x = 'John' Case-Sensitive Variable names are case-sensitive. a = 4 A = "Sally" #A will not overwrite a Random Number Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers: Example Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1, 10)) Strings are Arrays Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string. Example Get the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" print(a) Looping Through a String Since strings are arrays, we can loop through the characters in a string, with a for loop. Example Loop through the letters in the word "banana": for x in "banana": print(x) String Length To get the length of a string, use the len() function. Example The len() function returns the length of a string: a = "Hello, World!" print(len(a)) Check String To check if a certain phrase or character is present in a string, we can use the keyword in. Example Check if "free" is present in the following text: txt = "The best things in life are free!" print("free" in txt) Use it in an if statement: Example Print only if "free" is present: txt = "The best things in life are free!" if "free" in txt: print("Yes, 'free' is present.") Check if NOT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. Example Check if "expensive" is NOT present in the following text: txt = "The best things in life are free!" print("expensive" not in txt) Use it in an if statement: Example print only if "expensive" is NOT present: txt = "The best things in life are free!" if "expensive" not in txt: print("No, 'expensive' is NOT present.") Slicing You can return a range of characters by using the slice syntax. Specify the start index and the end index, separated by a colon, to return a part of the string. Example Get the characters from position 2 to position 5 (not included): b = "Hello, World!" print(b[2:5]) Slice From the Start By leaving out the start index, the range will start at the first character: Example Get the characters from the start to position 5 (not included): b = "Hello, World!" print(b[:5]) Upper Case Example The upper() method returns the string in upper case: a = "Hello, World!" print(a.upper()) Lower Case Example The lower() method returns the string in lower case: a = "Hello, World!" print(a.lower()) Remove Whitespace Whitespace is the space before and/or after the actual text, and very often you want to remove this space. Example The strip() method removes any whitespace from the beginning or the end: a = " Hello, World! " print(a.strip()) # returns "Hello, World!" String Concatenation To concatenate, or combine, two strings you can use the + operator. Example Merge variable a with variable b into variable c: a = "Hello" b = "World" c = a + b print(c) Example To add a space between them, add a " ": a = "Hello" b = "World" c = a + " " + b print(c) String Format As we learned in the Python Variables chapter, we cannot combine strings and numbers like this: Example age = 36 txt = "My name is John, I am " + age print(txt) F-Strings F-String was introduced in Python 3.6, and is now the preferred way of formatting strings. To specify a string as an f-string, simply put an f in front of the string literal, and add curly brackets {} as placeholders for variables and other operations. Example Create an f-string: age = 36 txt = f"My name is John, I am {age}" print(txt) Placeholders and Modifiers A placeholder can contain variables, operations, functions, and modifiers to format the value. Example Add a placeholder for the price variable: price = 59 txt = f"The price is {price} dollars" print(txt) A placeholder can include a modifier to format the value. A modifier is included by adding a colon : followed by a legal formatting type, like.2f which means fixed point number with 2 decimals: Example Display the price with 2 decimals: price = 59 txt = f"The price is {price:.2f} dollars" print(txt) A placeholder can contain Python code, like math operations: Example Perform a math operation in the placeholder, and return the result: txt = f"The price is {20 * 59} dollars" print(txt) Escape Character To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert. An example of an illegal character is a double quote inside a string that is surrounded by double quotes: Example You will get an error if you use double quotes inside a string that is surrounded by double quotes: txt = "We are the so-called "Vikings" from the north." To fix this problem, use the escape character \": Example The escape character allows you to use double quotes when you normally would not be allowed: txt = "We are the so-called \"Vikings\" from the north." String Methods Python has a set of built-in methods that you can use on strings. Note: All string methods return new values. They do not change the original string. Method Description capitalize() Converts the first character to upper case casefold() Converts string into lower case center() Returns a centered string count() Returns the number of times a specified value occurs in a string encode() Returns an encoded version of the string endswith() Returns true if the string ends with the specified value expandtabs() Sets the tab size of the string find() Searches the string for a specified value and returns the position of where it was found format() Formats specified values in a string format_map() Formats specified values in a string index() Searches the string for a specified value and returns the position of where it was found isalnum() Returns True if all characters in the string are alphanumeric isalpha() Returns True if all characters in the string are in the alphabet isascii() Returns True if all characters in the string are ascii characters isdecimal() Returns True if all characters in the string are decimals isdigit() Returns True if all characters in the string are digits isidentifier() Returns True if the string is an identifier islower() Returns True if all characters in the string are lower case isnumeric() Returns True if all characters in the string are numeric isprintable() Returns True if all characters in the string are printable isspace() Returns True if all characters in the string are whitespaces istitle() Returns True if the string follows the rules of a title isupper() Returns True if all characters in the string are upper case join() Joins the elements of an iterable to the end of the string ljust() Returns a left justified version of the string lower() Converts a string into lower case lstrip() Returns a left trim version of the string maketrans() Returns a translation table to be used in translations partition() Returns a tuple where the string is parted into three parts replace() Returns a string where a specified value is replaced with a specified value rfind() Searches the string for a specified value and returns the last position of where it was found rindex() Searches the string for a specified value and returns the last position of where it was found rjust() Returns a right justified version of the string rpartition() Returns a tuple where the string is parted into three parts rsplit() Splits the string at the specified separator, and returns a list rstrip() Returns a right trim version of the string split() Splits the string at the specified separator, and returns a list splitlines() Splits the string at line breaks and returns a list startswith() Returns true if the string starts with the specified value strip() Returns a trimmed version of the string swapcase() Swaps cases, lower case becomes upper case and vice versa title() Converts the first character of each word to upper case translate() Returns a translated string upper() Converts a string into upper case zfill() Fills the string with a specified number of 0 values at the beginning Python If... Else Python Conditions and If statements Python supports the usual logical conditions from mathematics: Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a b Greater than or equal to: a >= b These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword. Example If statement: a = 33 b = 200 if b > a: print("b is greater than a") In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a". Indentation Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly- brackets for this purpose. Example If statement, without indentation (will raise an error): a = 33 b = 200 if b > a: print("b is greater than a") # you will get an error Elif The elif keyword is Python's way of saying "if the previous conditions were not true, then try this condition". Example a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that "a and b are equal". Else The else keyword catches anything which isn't caught by the preceding conditions. Example a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that "a is greater than b". You can also have an else without the elif: Example a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") Short Hand If If you have only one statement to execute, you can put it on the same line as the if statement. Example One line if statement: if a > b: print("a is greater than b") Short Hand If... Else If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: Example One line if else statement: a = 2 b = 330 print("A") if a > b else print("B") This technique is known as Ternary Operators, or Conditional Expressions. You can also have multiple else statements on the same line: Example One line if else statement, with 3 conditions: a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B") And The and keyword is a logical operator, and is used to combine conditional statements: Example Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Or The or keyword is a logical operator, and is used to combine conditional statements: Example Test if a is greater than b, OR if a is greater than c: a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") Not The not keyword is a logical operator, and is used to reverse the result of the conditional statement: Example Test if a is NOT greater than b: a = 33 b = 200 if not a > b: print("a is NOT greater than b") Nested If You can have if statements inside if statements, this is called nested if statements. Example x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") The pass Statement if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Example a = 33 b = 200 if b > a: pass

Use Quizgecko on...
Browser
Browser