Text Size
Text Size
Exit Full Screen
Python3 Editor
Show
Source Code
View Source Code in Full Screen
# About variable names: # Variable names can only contain letters, numbers, and underscores # Variable names CANNOT start with a digit # No spaces are allowed in variable names. Use underscore instead. Example: first_name # In Python3 Editor, there are 4 main colors used to highlight the code: # yellow = reserved keyword or number literal # blue = built-in function, type, or True/False literal # green = string # orange = library names and user-defined variables/functions # Your variable names should be ORANGE. If the variable name is any other color, change it. #--------------------------------------------------- # NONE #--------------------------------------------------- # if you do not know what value to assign a variable but want to declare the variable anyway, set its value to None # this means the variable has no type (or is NoneType) and no operations can be done on it a = None #--------------------------------------------------------------------------- # NUMBER TYPES: Integer and Float #--------------------------------------------------------------------------- # integers = int type, whole numbers positive, negative, 0 # integer numbers written plainly in the code are considered "integer literals" a = -12 b = 104 c = 0 # with print statements, can use the comma to separate things being printed in the same statement # this allows you to have a string and an integer in the same statement (instead of using a plus sign) # the comma will also add a space before the next part that follows it prints print("a =", a) print("b =", b) print("c =", c) # floats = float type, numbers with decimals, can be positive or negative # floating-point numbers written plainly in the code are considered "float literals" d = 0.5 e = -1.67 print("d =", d) print("e =", e) # number operators f = a + b # addition g = a - b # subtraction h = a * b # multiplication i = a / b # division j = a // b # floor division (drops everything after the decimal, like rounding down) k = b % 5 # mod - returns the remainder after calculating 13/5 l = 2 ** 3 # exponent - returns the value of 2 ^ 3, a ** b = a^b print(a, "+", b, "=", f) print(a, "-", b, "=", g) print(a, "*", b, "=", h) print(a, "/", b, "=", i) print(a, "//", b, "=", j) print(b, "% 5 =", k) print("2**3 =", l) # there are also complex operators that are the same as Java, but there are no increment/decrement operators a += 5 # same as: a = a + 5 print("a += 5 =", a) a -= 10 # same as: a = a - 10 print("a -= 10 =", a) a *= 2 # same as: a = a * 2 print("a *= 2 =", a) a /= 3 # same as: a = a / 3 print("a /= 3 =", a) a //= 3 # same as: a = a // 3 print("a //= 3 =", a) a %= 3 # same as: a = a % 3 print("a %= 3 =", a) # can have a larger math expression on the right side of these operators as well a = 3 a += (10 + 5)/2 print("a =", a) # this is calculated with the following steps: # 1: (10 + 5) = 15 # 2: 15/2 = 7.5 # 3: a + 7.5 = 3 + 7.5 = 10.5 # 4: store 10.5 back in variable a # NOTE: all integer operators can be applied to floats since both are Number types print() #------------------------------------------------------------------------------- # BOOLEANS #------------------------------------------------------------------------------- # these are simple variables that can contain only True/False # The only 2 Boolean literal values are True and False isRaining = True isSunny = False print("isRaining =", isRaining) print("isSunny =", isSunny) print() # we'll go over these in more depth when we discuss conditions #------------------------------------------------------------------------------- # STRINGS #------------------------------------------------------------------------------- # Strings are lists of characters contained within quotes. Can use single-quotes ' or double-quotes ". # any string declared within quotes directly in the code is called a "String literal". s = "Hello" # there are 2 main operators for strings s2 = s + "World" # concatenation: adds the string on the right to the end of the string on the left print(s2) # Notice when the print statement above runs, it prints out "HelloWorld" with no space? This is because it concatenates the # string literals exactly as written. Since neither string contains a space that would separate the words, there is no space # in the output. # s2 = s + 5 # this line will cause an error to occur since integers cannot be concatenated to strings s3 = s * 5 # concatenates the value of the string s to the end of itself 5 times # this operator is commutative. s * 5 = 5 * s print(s3) # Both of these operators have compound assignment operators with them. s += "World" # will concatenate "World" to the end of "Hello" s *= 5 # will concatenate the current value of s to itself 5 times # same as integers, can do multiple operations on the right before the operation on the left occurs s = "Hello" s += " World" + "!!!" print(s) s *= 1 + 2 # first calculates that the right side is 3, then multiplies s by 3 print(s) print() #------------------------------------------------------------------------------------------------ # String indices #------------------------------------------------------------------------------------------------ # Again, strings are lists of characters. Each character has an index. # The first character in the string has an index of 0. # The length of the string is the number of characters in the string. s = "Hello World" print("There are", len(s), "characters in the string.") # You can access a specific character in the string using its index. # Write the name of the string variable, followed by the index in square brackets print(s[0]) # s[0] = 'H' print(s[6]) # s[6] = 'W' # Negative indices start counting at the end. The last character is at index -1. print(s[-1]) # s[-1] = 'd' print(s[-3]) # s[-3] = 'r' # if you try to access an index that is greater than or equal to the length of the string, you will get an IndexError # print(s[15]) # len(s) = 11 and 15 > 11, so this will cause an IndexError # Use the index() function to find the index of a specific character or set of characters. # It will return the index of the FIRST occurrence of the character/substring in the string. print(s.index('o')) # prints out 4, since the letter 'o' is first found at index 4 and ignores the one found at index 7 print(s.index('lo')) # prints out 3, since 'lo' starts at index 3 # be careful using this, since it will cause a ValueError when that character or substring is NOT in the string # print(s.index('z')) # Also using the indices, you can create substrings. # s[start: end] # s = string variable name # start = index of first character in substring # end = index of last character in substring + 1 # NOTE: the character at the end index IS NOT INCLUDED. In the example below, if it was included, the last character would be 'o'. print(s[3: 7]) # prints out 'lo W'. # You can leave out the start value if you want it to start at 0. print(s[:3]) # s[:3] = 'Hel' # Leaving out the end value will end it at the last character of the string print(s[7:]) # s[7:] = 'orld' # You can also use negative indices here as well. # REVERSE A STRING # You can reverse a string by simply writing: print(s[::-1]) # This will reverse the entire string. The order of this slice is # s[start:end:skip] # skip can be any value, positive or negative. # What prints out when you run this? print(s[1:10:2]) print() #----------------------------------------------------------------------------- # String Functions #----------------------------------------------------------------------------- s = "Hello" s_upper = s.upper() # sets all characters to uppercase letters, s_upper = "HELLO" s_lower = s.lower() # sets all characters to lowercase letters, s_lower = "hello" inp = input("Enter something: ") print("Is alpha?", inp.isalpha()) # returns True if all characters in string are letters print("Is digit?", inp.isdigit()) # returns True if all characters in string are digits print("Is alnum?", inp.isalnum()) # returns True if all characters in string are letters OR digits print("Is space?", inp.isspace()) # returns True if all characters in string are spaces print("Is upper?", inp.isupper()) # returns True if all characters in string are uppercase print("Is lower?", inp.islower()) # returns True if all characters in string are lowercase s2 = " Howdy all " print(s2) print(s2.strip()) s3 = "5, 4, 7, 12, 6" print(s3) print(s3.split(", ")) print() #---------------------------------------------------------------------------------- # INPUT #---------------------------------------------------------------------------------- x = input("Enter a number: ") print(x, type(x)) # Remember that input() ALWAYS returns a string. If you want the value entered to be an int, you need to convert it to an int. # Use the int() function to convert it x = int(x) print(x, type(x)) # If you want it to be a float, you need to use the float() function to convert it x = float(x) print(x, type(x)) print() # NOTE: if there is a non-numerical character in the string and you attempt to change it to an integer, it will cause an ERROR. #---------------------------------------------------------------------------------- # Formatting strings #---------------------------------------------------------------------------------- name = "Bob" name2 = "Mary" age = 34 num_kids = 2 pi = 3.1415926535 # Formatting using the deprecated method # %s = string # %d = integer # %f = float # can specify number of characters to include. Example %.2f will print out only 2 digits after the decimal print("Hi %s! My name is %s!" % (name, name2)) print("I am %d years old. I have %03d children." % (age, num_kids)) print("Pi with the first 5 values after the decimal point are %.5f." % (pi)) print() # Can also format with the .format() function. The number in the curly brackets is the index of the value in the list in format's parentheses print("Hi {0}! My name is {1}! I am {2} years old. I have {3} children.".format(name, name2, age, num_kids)) # can still specify things like number of digits after decimal print("Pi with 5 digits after the decimal is {0:.5f}.".format(pi))
CS110_L2_Notes.py
( around 211 lines Python3 code )
Published By:
Mentor Sabrina
Created on
2020-10-19T17:20:58Z
Python3 Editor
- an
OYOclass
application,
own your own class today
.
Run
Result
Status:
Program is not running