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
Strings Find the length of a string.
message="Hello World" print(len(message)) # Prints length
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.
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
Strings Escape characters
print("\n") #prints a new line print("\t") #prints a tab space.
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.
Strings Count the number of occurrences of a substring.
message="Hello World" print(message.count("l")) print(message.count("Hello")) # Prints 1.
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.
Strings Replace a substring with another substring.
message="Hello World" new_message=message.replace("World","Universe") print(new_message) # The original string remains unchanged.
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.
Strings f strings
greeting="Hi" language="Python" message=f"{greeting}, welcome to {language}" print(message)
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.
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
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
List Define a list
subjects=["History","Math","Science"] # Remember lists are ordered.
List Access an element
subjects=["History","Math","Science"] print(subjects[0]) print(subjects[-1]) # The last element.
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])
List Number of elements in a list
subjects=["History","Math","Science","Geography"] print(len(subjects)) # Same as strings.
List Find the index of an element
subjects=["History","Math","Science","Geography"] print(subjects.index("Math"))
List Count the number of occurrences of an element
subjects=["History","Math","Science","Geography","Math"] print(subjects.count("Math"))
List Append an element
subjects=["History","Math","Science","Geography"] subjects.append("CompSci")
List Insert an element at a particular index
subjects=["History","Math","Science","Geography"] subjects.insert(1,"CompSci")
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.
List Remove an known element (value)
subjects=["History","Math","Science","Geography"] subjects.remove("Math")
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)
List Reverse the order of elements in a list
subjects=["History","Math","Science","Geography"] subjects.reverse() # Changes the original list
List Sort the original list.
subjects=["History","Math","Science","Geography"] subjects.sort() print(subjects) subjects.sort(reverse=True) print(subjects) # Changes the original list.
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)
List Maximum, Minimum and Sum of elements
numbers=[2,1,4,3,5] print(min(numbers)) print(max(numbers)) print(sum(numbers))
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.
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)
List Convert list into string
subjects=["History","Math","Science","Geography"] subject_string=", ".join(subjects)
List Convert string to list
subjects=["History","Math","Science","Geography"] subject_string=", ".join(subjects) new_subjects=subject_string.split(", ")
Tuples Definition
sub_tuple=("History","Math","Science") # Unlike lists tuples are immutable. # Tuples are ordered.
Sets Definition
new_subjects={"History","Math","Geo","Math","History"} # Sets are unordered # No duplicates in sets. # The above list has only 3 elements.
Sets Add elements
new_subjects={"History","Math","Geo","Math","History"} new_subjects.add("CompSci")
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.
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))
General Create new list, tuple, set and dictionary.
my_list=list() my_tuple=tuple() my_set=set() my_dict=dict()
Dictionary Create a dictionary
student={"Name":"John","Age":25,"Courses":["Math","CompSci"]} # key-value pairs
Dictionary Access a particular key
student={"Name":"John","Age":25,"Courses":["Math","CompSci"]} print(student["Name"]) # KeyError if no such key
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.
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.
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)
Dictionary Delete a key
student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} del student["Age"] # Removes key-value pair.
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.
Dictionary Number of key-value pairs
student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(len(students))
Dictionary List of all keys
student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student.keys()) # Prints list containing all the keys.
Dictionary List of all values
student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student.values()) # Prints list containing only values.
Dictionary List of tuples having key-value pairs
student = {"Name": "John", "Age": 25, "Courses": ["Math", "CompSci"]} print(student.items())
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)
General Leave a function to define later.
def my_func(): pass # Can be executed with no error.
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.
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"))…
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")
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.
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())
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
Modules Import multiple functions/ variables from a module
from my_module import find_index as fi, test as t
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.
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.
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
Modules Directory of .py file of module
import os print(os.__file__)
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)
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)
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)
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)
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)
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)
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
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.
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.
General Type of object
greeting="Hello" print(type(greeting))
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.
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")
Strings Removing spaces and tabs
text=input("Type something: ") print("@",text,"@") print("@",text.strip(),"@") print("@",text.lstrip(),"@") print("@",text.rstrip(),"@")
List Insert an element using slicing operator
fruits=["apples","bananas","grapes","oranges"] print(fruits) fruits[2:2]=["strawberries"] print(fruits)
General Get the unique id assigned to a variable
greeting="Hello" print(id(greeting))