The purpose of this Python 3 cheat sheet is to help beginners remember Python syntax.
# The primitive data types are integer, float, boolean and string# assigning values to primitivesint_var = 2print("integer:", int_var)float_var = 1.9print("float:", float_var)bool_var = Trueprint("boolean:", bool_var)string_var = 'Hello world'print("string:", string_var)# icrementing a variable's valueint_var += 1print("integer:", int_var)# x, y and z all get the value 0.1x = y = z = 0.1print("x:", x, "y:", y, "z:", z)# u gets the value 100 and v gets the value 12u, v = 100, 12print("u:", v, "v:", v)
country = 'South Korea'if country == 'South Korea':print('Anneyong')elif country == 'France':print('Bonjour')else:print('Hello')
# printing the 0, 1print("Example 1:")for i in range(2):print(i)# printing numbers from 0 to 2 in the reverse orderprint("Example 2:")i = 2while i >= 0:print(i)i -= 1# printing all the characters in a string until a# space is encountered is encounteredprint("Example 3:")s = 'Hey World'for character in s:if character == ' ':# The break keyword is used to exit the loop.breakelse:print(character)# printing all the characters in a string except for any space.print("Example 4:")s = 'Tic Tac'for character in s:if character == ' ':# The continue keyword is used to ignore the subsequent# lines of code in the loop for this iteration and start the# next iteration.continueprint(character)
# a function may or may not return anythingdef multiply(num1, num2):return num1 * num2print(multiply(3, 4))# a function can accept variable number of arguments as welldef multipleargs(*args):print(args)multipleargs('a', 'b', 'c', 'd')
class Fruit:#__init__() is always executed when the class is being initiateddef __init__(self, name, weight):self.name = nameself.weight = weight# a method of the classdef print_fruit(self):print("Name:", self.name, "Weight(g):", self.weight)# Creating an objectfruit1 = Fruit("Kiwi", 60)# calling the print_fruit() methodfruit1.print_fruit()
l = [1, 2 ,3]# adding an element to the end of the listl.append(4)print(l)# adding element -1 at index 3l.insert(3,-1)print(l)# adding element -1 at index 1l.insert(1,-1)print(l)# removing first item with value -1l.remove(-1)print(l)# remove and return the element at index 2elem = l.pop(2)print("element popped:", elem)print(l)# sorting a listl.sort()print(l)# printing the list starting from index 0 and ending at index 2print(l[0:3])# printing the second last element of the listprint(l[-2])# List comprehension.# converting all the elements of the list to uppercaseprint([x.upper() for x in ["x","y","z"]])# List of listsm = [['kiwi','watermelon'],['20','30','40']]print(m)
fruit = {"name": "Mango","weight": 60,"origin": "Pakistan"}# Printing the dictionaryprint(fruit)# Using a key to look up valueprint(fruit["name"])# Changing the value of an itemfruit["name"] = "Banana"print(fruit["name"])# Adding a new keyfruit["color"] = "Yellow"print(fruit)
Free Resources