Python basic syntax

I'm a programming noob looking to memorize basic syntax. This doesn't follow the QnA format.

77 flashcards · Programming Languages · by Sai Teja

  1. Strings Find the length of a string.

    message="Hello World" print(len(message)) # Prints length

  2. Strings Access an individual character.

    message="Hello World" print(message[0]) # Prints the first character. print(message[-1]) # Prints the last character. print(message[-2]) # Prints the second to last character.

  3. Strings Slice a string.

    message="Hello World" print(message[2:4]) # Prints from index 2 to 3 # The ending index is non-inclusive. print(message[:4]) # Start to index 3 print(message[2:]) # index 2 to end print(message[::2]) # from start to end with step of 2

  4. Strings Escape characters

    print("\n") #prints a new line print("\t") #prints a tab space.

  5. Strings Change the string case.

    message="HeLlO WorLd" print(message.lower()) # Changes the string to lower case. print(message.upper()) # Changes the string to upper case. print(message.title()) # Changes the string to title case. # These methods don't change the original string.

  6. Strings Count the number of occurrences of a substring.

    message="Hello World" print(message.count("l")) print(message.count("Hello")) # Prints 1.

  7. Strings Find the index of a character or substring.

    message="Hello World" print(message.find("l")) # Prints the index of first occurence. print(message.find("Hel")) # Prints the index of first character. print(message.find("z")) # Prints -1 as the character is absent.

  8. Strings Replace a substring with another substring.

    message="Hello World" new_message=message.replace("World","Universe") print(new_message) # The original string remains unchanged.

  9. Strings Formatted strings

    greeting="Hi" language="Python" message="{}, welcome to {}.".format(greeting,language) print(message) # {} are called place holders. # Arguments in .format() should be in the order they appear in the string.

  10. Strings f strings

    greeting="Hi" language="Python" message=f"{greeting}, welcome to {language}" print(message)

  11. General Find the attributes and methods related to a variable of a particular class.

    message="Hello World" print(dir(message)) # Prints all the attributes and methods related to string objects.

  12. Integers and floats Floor division Exponent Remainder Finding absolute value Rounding off

    print(5//3) #Floor division:Prints 1 print(5**2) # Exponent print(5%2) # Remainder print(abs(-2)) # Absolute value print(round(-3.75)) # Rounds to the integer nearer on the number line. print(round(3.765,1)) # Rounds to one digit after decimal

  13. Comparison operators Equal Not equal Less than Less than or equal Greater than Greater than or equal

    # All comparison operators return booleans. print(5==3) # Equal print(5!=3) # Not equal print(5<3) # Less than print(5<=3) # Less than or equal print(5>3) # Greater than print(5>=3) # Greater than or equal

  14. List Define a list

    subjects=["History","Math","Science"] # Remember lists are ordered.

  15. List Access an element

    subjects=["History","Math","Science"] print(subjects[0]) print(subjects[-1]) # The last element.

  16. List Slice

    subjects=["History","Math","Science","Geography"] print(subjects[:3]) # Elements 0, 1 & 2 are printed. # The end index is non-inclusive. print(subjects[2:]) # From 2nd index to last. print(subjects[0:2])

  17. List Number of elements in a list

    subjects=["History","Math","Science","Geography"] print(len(subjects)) # Same as strings.

  18. List Find the index of an element

    subjects=["History","Math","Science","Geography"] print(subjects.index("Math"))

  19. List Count the number of occurrences of an element

    subjects=["History","Math","Science","Geography","Math"] print(subjects.count("Math"))

  20. List Append an element

    subjects=["History","Math","Science","Geography"] subjects.append("CompSci")

  21. List Insert an element at a particular index

    subjects=["History","Math","Science","Geography"] subjects.insert(1,"CompSci")

  22. List To append the elements of another list/tuple/set

    subjects=["History","Math","Science","Geography"] optionals=["French","Mechanics"] subjects.extend(optionals) # Using append for this would've included the entire list as a single element.

  23. List Remove an known element (value)

    subjects=["History","Math","Science","Geography"] subjects.remove("Math")

  24. List Remove an element at a particular index and hold the removed element in a variable.

    subjects=["History","Math","Science","Geography"] popped_subject=subjects.pop(2) # If no index is mentioned the last element is popped. print(subjects) print(popped_subject)

  25. List Reverse the order of elements in a list

    subjects=["History","Math","Science","Geography"] subjects.reverse() # Changes the original list

  26. List Sort the original list.

    subjects=["History","Math","Science","Geography"] subjects.sort() print(subjects) subjects.sort(reverse=True) print(subjects) # Changes the original list.

  27. List Create a sorted list leaving the original list unchanged.

    subjects=["History","Math","Science","Geography"] asc_subjects=sorted(subjects) des_subjects=sorted(subjects,reverse=True) print(subjects) print(asc_subjects) print(des_subjects)

  28. List Maximum, Minimum and Sum of elements

    numbers=[2,1,4,3,5] print(min(numbers)) print(max(numbers)) print(sum(numbers))

  29. List Check if an element is present in a list

    subjects=["History","Math","Science","Geography"] if "History" in subjects: print("You have History today!") # This works on tuples and sets also.

  30. List Return the index of element along with the element

    subjects=["History","Math","Science","Geography"] for index,subject in enumerate(subjects): print(index,subject) for index,subject in enumerate(subjects,start=1): print(index,subject)

  31. List Convert list into string

    subjects=["History","Math","Science","Geography"] subject_string=", ".join(subjects)

  32. List Convert string to list

    subjects=["History","Math","Science","Geography"] subject_string=", ".join(subjects) new_subjects=subject_string.split(", ")

  33. Tuples Definition

    sub_tuple=("History","Math","Science") # Unlike lists tuples are immutable. # Tuples are ordered.

  34. Sets Definition

    new_subjects={"History","Math","Geo","Math","History"} # Sets are unordered # No duplicates in sets. # The above list has only 3 elements.

  35. Sets Add elements

    new_subjects={"History","Math","Geo","Math","History"} new_subjects.add("CompSci")

  36. Sets Check for an element

    new_subjects={"History","Math","Geo","Math","History"} print("History" in new_subjects) # Sets are better optimized for this operation compared to lists.

  37. Sets Set operations.

    cs_courses = {"History", "Math", "Physics", "CompSci", "Math"} art_courses = {"History", "Math", "Art", "Design"} print(cs_courses.intersection(art_courses)) # Elements in cs_courses and not in art_courses. print(cs_courses.difference(art_courses)) print(cs_courses.union(art_courses))

  38. General Create new list, tuple, set and dictionary.

    my_list=list() my_tuple=tuple() my_set=set() my_dict=dict()

  39. Dictionary Create a dictionary

    student={"Name":"John","Age":25,"Courses":["Math","CompSci"]} # key-value pairs

  40. Dictionary Access a particular key

    student={"Name":"John","Age":25,"Courses":["Math","CompSci"]} print(student["Name"]) # KeyError if no such key

  41. Dictionary Access a particular key and return something if key not found.

    student={"Name":"John","Age":25,"Courses":["Math","CompSci"]} print(student.get("Name")) print(student.get("Phone")) # Prints None print(student.get("Phone","Key not found!")) # Prints the message given as argument.

  42. Dictionary Add new key-value pair or update existing one.

    student={"Name":"John","Age":25,"Courses":["Math","CompSci"]} student["Phone"]="1234567890" # Adding new pair student["Name"]="Varun" # Updating the name.

  43. Dictionary Update/Add multiple keys at a time

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student) # .update() takes a dictionary as an argument. student.update({"Name": "Varun", "Age": 21, "Phone": "1234567890"}) # Updates "Name" and "Age", adds "Phone" print(student)

  44. Dictionary Delete a key

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} del student["Age"] # Removes key-value pair.

  45. Dictionary Delete a key and hold the value corresponding to deleted key.

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} age=student.pop("Age") # Only the value is stored.

  46. Dictionary Number of key-value pairs

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(len(students))

  47. Dictionary List of all keys

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student.keys()) # Prints list containing all the keys.

  48. Dictionary List of all values

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student.values()) # Prints list containing only values.

  49. Dictionary List of tuples having key-value pairs

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student.items())

  50. Dictionary Loop through the key-value pairs

    student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} for key,value in student.items(): print(key ,value) for key in student: # Loops through keys only. print(key)

  51. General Leave a function to define later.

    def my_func(): pass # Can be executed with no error.

  52. Function Definition

    def hello_func(): # No parameters. return "Hello Function" def greet_name(greeting, name): # Two positional arguments. return f"{greeting}, {name}" def greet_name_1(name, greeting="Hello"): # Default value return f"{greeting}, {name}" # The parameters with default values must come after the ones with no default value.

  53. Function Types of arguments.

    # Positional arguments have to come before keyword arguments. # Arguments before / are positional-only # Arguments between / and * are regular arguments. # Regular keywords can be mentioned in order without keywords or with keywords in any order. # Arguments after * are keyword-only # The order of regular arguments can be changed using keywords. def greet_name_2(rollcall, /, name, *, greeting): return f"Roll number: {rollcall}. {greeting}, {name}" print(greet_name_2(23, "AB", greeting="Hello"))…

  54. Function *args and **kwargs

    # To accept arbitrary number of positional and keyword arguments. # Positional arguments are stored in a tuple # Keyword arguments are stored in a dictionary def student_info(*args, **kwargs): print(args) print(kwargs) student_info("Math", "Biology", "Civics", favourite_game="Volley ball", favourite_color="Black")

  55. Function Use * and ** in function arguments.

    # Unpack a sequence or dictionary and passes the values into the function individually. courses = ["Math", "Art"] info = {"name": "John", "age": 22} student_info(courses, info) # The above line takes courses and info as positional arguments. # And combines them in a tuple. student_info(*courses, **info) # This statement unpacks courses and info into positional and keyword arguments respectively.

  56. Modules Import a module

    import my_module import my_module as mm # To shorten the name when using. print(my_module.my_func()) print(mm.my_func())

  57. Modules Import a particular function from a module

    from my_module import find_index from my_module import find_index as fi print(find_index()) print(fi()) # no need for the module name

  58. Modules Import multiple functions/ variables from a module

    from my_module import find_index as fi, test as t

  59. Modules Import all the elements from a module

    from my_module import * # To be avoided as it is difficult to identify the source of defective function when multiple modules are imported.

  60. Modules List of paths in which modules are searched.

    from sys import path print(path) # Present working directory, elements in PYTHONPATH environment variable, standard library directory, 3rd party package directory.

  61. Modules Include directory for module search

    sys.path.append("D:\CoreySchafer_Python\my_modules") # This works but is only temporary. # To include permanently include it in PYTHONPATH

  62. Modules Directory of .py file of module

    import os print(os.__file__)

  63. Comprehensions List Comprehension

    my_list = [] for n in nums: my_list.append(n**2) print(my_list) my_list = [n**2 for n in nums] print(my_list)

  64. Comprehensions List Comprehension with condition.

    my_list=[] for n in nums: if n%2==0: my_list.append(n) print(my_list) my_list=[n for n in nums if n%2==0] print(my_list)

  65. Comprehensions List Comprehension for nested loop

    my_list=[] for letter in "abcd": for number in range(4): my_list.append((letter,number)) print(my_list) my_list=[(letter,number) for letter in "abcd" for number in range(4)] print(my_list)

  66. Comprehensions Dictionary comprehension

    names=["Bruce","Clark","Peter","Logan","Wade"] heroes=["Batman","Superman","Spiderman","Wolverine","Deadpool"] print(list(zip(names,heroes))) # I want a dictionary with {"name":"hero"} for each name,hero in zip(names,heroes) my_dict=dict() for name,hero in zip(names,heroes): my_dict[name]=hero print(my_dict) my_dict={name:hero for name,hero in zip(names,heroes)} print(my_dict)

  67. Comprehensions Dictionary comprehension with condition

    names=["Bruce","Clark","Peter","Logan","Wade"] heroes=["Batman","Superman","Spiderman","Wolverine","Deadpool"] my_dict=dict() for name,hero in zip(names,heroes): if name.title()!="Peter": my_dict[name]=hero print(my_dict) my_dict={name:hero for name,hero in zip(names,heroes) if name.title()!="Peter"} print(my_dict)

  68. Comprehensions Set comprehension

    nums=[1,1,2,1,3,4,3,4,5,5,6,7,8,7,9,9] my_set=set() for n in nums: my_set.add(n) print(my_set) my_set={n for n in nums} print(my_set)

  69. Generators Definition and comprehension

    nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # I want to yield "n*n" for each n in nums def gen_func(nums): for n in nums: yield(n*n) my_gen=gen_func(nums) print(my_gen) for i in my_gen: print(i) my_gen=(n*n for n in nums) # Generator comprehension

  70. Generators Difference between list and generator

    Generators don't hold all the values in the memory. They yield one at a time and hence are memory efficient. Generator definition is more readable. Lists can be used again and again. Generator doesn't yield any value after it's last element.

  71. Generators Access the next element

    my_gen=(n**2 for n in range(1,6)) print(next(my_gen)) print(next(my_gen)) print(next(my_gen)) print(next(my_gen)) print(next(my_gen)) # print(next(my_gen)) # This won't work StopIteration as the values are exhausted.

  72. General Type of object

    greeting="Hello" print(type(greeting))

  73. if-elif-else block Definition

    height=int(input("Enter your height: ")) if height < 1: print("You can't ride. Height < 1m.") elif height > 2: print("You can't ride, Height > 2m.") else: print("You can ride.") # Only one of the if,elif and else statements are executed.

  74. Chained conditionals Definition

    x,y=2,3 if y==x and x+y==5: print("Condition:1 true") if y==x or x+y==5: print("Condition:2 true") if y==3 and x+y==5: print("Condition:3 true") if not(y==x or y+x==5): # not() changes the boolean to the opposite value. print("Condition:4 true")

  75. Strings Removing spaces and tabs

    text=input("Type something: ") print("@",text,"@") print("@",text.strip(),"@") print("@",text.lstrip(),"@") print("@",text.rstrip(),"@")

  76. List Insert an element using slicing operator

    fruits=["apples","bananas","grapes","oranges"] print(fruits) fruits[2:2]=["strawberries"] print(fruits)

  77. General Get the unique id assigned to a variable

    greeting="Hello" print(id(greeting))