GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing www.tutorialspoint.com — Python Cheatsheet
Selected Reading
Python CheatsheetThis Python cheatsheet is helpful for students and developers as well to learn Python programming quickly. Printing Hello WorldPrinting "Hello, World!" is a basic program. To print "Hello, World," use the print() function. Here is the basic Python program − print("Hello, World!") # Output: Hello, World!
Printing OutputThe print() function can also be used to print the output, i.e., the value of the variables on the screen. name = "Kelly Hu"
print("Hi my name is: ", name)
To print multiple variables, you can use the following cascading form of the print() function − name = "Kelly Hu"
age = 27
city = "Brentwood"
print("I am", name, ". I'm", age, "years old and lives in", city)
Print Without NewlineThe print() method inserts a newline after printing the result. To print without a newline, use the end=' ' parameter as the last parameter in print() method. print("Hello", end=" ")
print("World")
You can specify any value to end parameter; the new assigned value will be printed after the result. print("Hello", end="####")
print("World")
CommentsPython provides three types of comments −
1. Single-line commentSingle-line comment is placed followed by the hash (#) single. # This is single-line comment 2. Multi-line commentMulti-line comment is written between the set of three single quotes ('''). Anything is written between ''' and ''' refers to a multi-line comment. '''
name = "Kelly Hu"
age = 30
city = "Brentwood"
'''
print("Hello, World!")
VariablesPython variables are created when you assign values to them. There is no keyword to declare a variable in Python. name = "Kelly Hu" age = 27 print(name) print(age) Specifying Variable's Data TypeThe data type of a variable can be specified using the type casting with the help of built-in functions such as str(), int(), float(), etc. a = str(123) b = int(123) c = float(123) # Printing type print(type(a)) print(type(b)) print(type(c)) Printing Type of Variable/ObjectThe type() function can be used to print the data type (object type) of a variable or an object. name = "Kelly Hu" print(name, "is the type of", type(name)) Variable NamesVariable names (or identifiers) must be started with a letter or the underscore character, and only alpha-numeric characters and underscores are allowed as the variable names. Some of the valid variable names are: name, _name, my_name, name2, MY_NAME Assign Multiple Values to VariablesYou can assign multiple values to variables by separating the variable names and values with commas. name, age, city = "Kelly Hu", 27, "Brentwood" print(name) print(age) print(city) Data TypesThe following are the Python data types − 1. Text Types: String (str)text = "Hello, World!" 2. Numeric Typesint num_int = 10 float num_float = 10.5 complex num_complex = 2 + 3j 3. Sequence Typeslist my_list = [1, 2, 3] tuple my_tuple = (1, 2, 3) range my_range = range(1, 10) 4. Mapping Type: Dictionary (dict)my_dict = {"name": "Kelly Hu", "age": 27}
5. Set Typesset my_set = {1, 2, 3}
frozenset my_frozenset = frozenset([1, 2, 3]) 6. Boolean Type: boolmy_bool = True 7. Binary Typesbytes my_bytes = b"Hello" bytearray my_bytearray = bytearray(5) memoryview my_memoryview = memoryview(b"Hello") 8. None Type: NoneTypemy_none = None OperatorsPython operators are used to perform various operations such as arithmetic, logical, etc. on operands. Arithmetic operatorsPython arithmetic operators are + (addition), - (subtraction), * (multiplication), / (division), // (floor division), % (modulus), and ** (exponentiation). Assignment operatorsPython assignment operators are used to assign values to variables, including =, +=, -=, *=, /=, %=, **=, //=, &=, |=, ^=, >>=, and <<=. Comparison operatorsPython comparison operators are used to compare two values, and include == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), and <= (less than or equal to). Logical operatorsPython logical operators are and, or, and not. Identity operatorsPython identity operators are is and is not, used to check if two variables refer to the same object in memory. Membership operatorsPython membership operators are in and not in. These operators are used to test whether a value is found in a sequence or not. Bitwise operatorsPython bitwise operators perform operations on binary values; these operators are AND (&), OR (|), NOT (~), XOR (^), left shift (<<), and right shift (>>). User InputPython allows you to take different types of input from the user. The input() function is used to take user input as a string from the user. You can use the following basic methods to convert input to the specific type −
Basic User Inputname = input("Enter your name: ")
print("Hello", name)
Integer Inputage = int(input("Enter your age: "))
print(f"You are {age} years old.")
Float Inputx = float(input("Enter any float value: "))
print(x)
Handling Invalid InputsYou can use the try and except to handle the invalid inputs. try:
x = int(input("Input an integer value: "))
print(x)
except ValueError:
print("Please enter a valid number.")
ConditionsPython conditional statements are written using the if, elif, and else keywords. a = 10
b = 20
if a > b:
print("a is greater than b")
elif b > a:
print("b is greater than a")
else:
print("a is greater than b")
LoopsThere are two types of Python loops − the for loop and the while loop. The for Loopstudents = ["Kelly Hu", "Akanksha", "Peter"] for s in students: print(s) The while Loopi = 1 while i <= 10: print(i) i += 1 StringsPython strings are the sequence of characters enclosed within single or double quotation marks. Printing Stringsprint("I'm Kelly Hu I live in Brentwood")
name, city = "Kelly Hu", "Brentwood"
# Printing string variables
print("I'm", name, "I live in", city)
Quotes Inside QuotesYou can print quotes as a string using the print() function. print("I'm Kelly Hu")
print("I am 'Kelly Hu'")
print("I am \"Kelly Hu\"")
Multiline StringsPython allows to assign multiline strings to a variable. Just place the multiline string using three single or doble quotes. a = """I am Kelly Hu I lives in Brentwood. I am 27 years old""" b = '''I am Kelly Hu I lives in Brentwood. I am 27 years old''' print(a) print(b) Slicing StringsString slicing can be done by using the start and the end index, separated by a colon inside square brackets. test = "Hello, World!" print(test[2:5]) print(test[0:]) print(test[:13]) print(test[:5]) String ConcatenationYou can concatenate two or more strings using the plus (+) operator. name = "Kelly Hu" city = "Brentwood" person = name + " " + city print(person) String FormatString formatting is done using the Python f-string. name = "Kelly Hu"
age = 27
person = f"My name is {name}, I am {age} years old"
print(person)
String MethodsThe following are the popular string methods −
Escape CharactersPython escape characters are the combination of escape (\) and a character that are used for performing specific tasks. The following are the escape characters with their meanings −
ListsPython lists are used to store comma-separated values. Creating Lists# Empty list my_list = [] # List with elements my_list = [1, 2, 3, 4, 5] Accessing ElementsAccessing elements of a list can be done using the index and list slicing. my_list = [1, 2, 3, 4, 5] print(my_list[0]) print(my_list[2]) print(my_list[-1]) print(my_list[2:4]) Appending and Inserting ElementsThe elements in a list can be appended and inserted using the list.append() and list.insert() methods, respectively. my_list = [1, 2, 3, 4, 5] print(my_list) my_list.append(6) my_list.insert(0, 0) print(my_list) Removing List ElementsThe remove() method is used to remove the elements of a list. my_list = [1, 2, 3, 4, 5] print(my_list) my_list.remove(3) print(my_list) Copying ListsThe list.copy() method is used to copy a list to another. my_list = [1, 2, 3, 4, 5] new_list = my_list.copy() print(my_list) print(new_list) Clearing a ListThe list.clear() method is used to clear list elements. my_list.clear() Nested ListsPython nested list refers to the list within a list. nested_list = [[1, 2], [3, 4], [5, 6]] print(nested_list) TuplesPython tuples are used to store multiple comma-separated values in a variable. Tuple values are given inside the round brackets. Creating Tuplesmy_tuple = (1, 2, 3) print(my_tuple) Creating Empty Tuplesmy_tuple = () print(my_tuple) Tuple Without Parentheses (Implicit Tuple)my_tuple = 1, 2, 3 print(my_tuple) Single Element Tuplemy_tuple = (1,) print(my_tuple) Accessing Tuple ElementsTuple elements can be accessed using the index and tuple slicing. my_tuple = (10, 20, 30) print(my_tuple[0]) print(my_tuple[1]) print(my_tuple[0:]) print(my_tuple[-1]) print(my_tuple[0:2]) Tuple ConcatenationTo concatenate tuple, use the plus (+) operator. tuple1 = (10, 20, 30) tuple2 = (40, 50) print(tuple1 + tuple2) Tuple Unpackingtuple1 = (10, 20, 30) a, b, c = tuple1 print(a) print(b) print(c) Nested Tuplesnested_tuple = ((10, 20), (30, 40), (50, 60)) print(nested_tuple) SetsPython sets are the collection of multiple items that are unordered, unchangeable*, and unindexed. Set values are comma-separated and enclosed within the curly braces. Creating Setsset1 = {10, 20, 30, 40, 50}
# Set from a list
set2 = set([10, 20, 30, 40, 50])
print(set1)
print(set2)
Adding and Removing ElementsThe following functions are used to add and remove elements from a set −
Example of Set Operationsset1 = {10, 20, 30, 40, 50}
set1.add(60)
print(set1)
set1.update([70, 80])
print(set1)
set1.remove(30)
print(set1)
set1.discard(10)
print(set1)
print(set1.pop(),"is removed!")
set1.clear()
print(set1)
DictionariesPython dictionaries are the collection of key and value pairs and are written with curly brackets. Creating Dictionarymy_dict = {'name': 'Kelly Hu', 'age': 27}
print(my_dict)
Creating Empty Dictionarymy_dict = {}
print(my_dict)
Creating Dictionary with Mixed Keysmy_dict = {1: 'Kelly', 'hair_color': 'Brown', (36, 24): 'lucky_numbers'}
print(my_dict)
Accessing ValuesYou can directly access the values of the specified keys by providing the key names inside the square brackets enclosed with quotes, and you can also use the dict.get() method to get the value of the specified key. person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'}
# Direct access
print(person['name'])
print(person['age'])
print(person['city'])
# Using method
print(person.get('name'))
print(person.get('age'))
print(person.get('city'))
Modifying DictionariesYou can directly update a value of the existing key, and you can also update the multiple values using the dict.update() method. person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'}
print(person)
# Updating single value
person['age'] = 18
print(person)
# Updating multiple values
person.update({'age': 21, 'city': 'New York'})
print(person)
Removing ElementsThe following methods can be used to remove elements from a dictionary −
Iterating Through a Dictionaryperson = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'}
# Iterate through keys
for key in person:
print(key)
# Iterate through values
for value in person.values():
print(value)
# Iterate through key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
Dictionary Comprehensionsdict1 = {x: x**2 for x in range(5)}
print(dict1)
LambdasPython lambda function can have only one expression. These are small anonymous functions that can take any number of arguments. value = lambda x : x * 3 print(value(5)) Classes and ObjectsPython is an object-oriented programming language and allows to create classes and objects. You can create a class in Python using the "class" keyword. class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
# Create objects
per1 = Person("Kelly Hu", 27)
per2 = Person("Adele", 25)
# Access object attributes
print(per1.name)
print(per1.age)
# Printing using method
per2.display_info()
InheritancePython inheritance allows you to inherit the properties of the parent class to the child class. Basic Inheritance Example# Base class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def get_details(self):
return f"Student: {self.name}, Grade: {self.grade}"
# Derived class
class Graduate(Student):
def get_details(self):
return f"Graduate: {self.name}, Grade: {self.grade}, Status: Graduated"
# Create an instance of the child class
grad = Graduate("Kelly Hu", "B+")
# Access inherited and overridden methods
print(grad.get_details())
super() with Method OverridingThe super() method is used to call a method from the parent (or base) class. # Base class
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def get_details(self):
return f"Student: {self.name}, Grade: {self.grade}"
# Derived class
class Graduate(Student):
def __init__(self, name, grade, graduation_year):
# Call the parent class's constructor using super()
super().__init__(name, grade)
self.graduation_year = graduation_year
def get_details(self):
# Call the parent class's get_details() method using super()
student_details = super().get_details()
return f"{student_details}, Graduation Year: {self.graduation_year}"
# Create an instance of the child class (Graduate)
grad = Graduate("Kelly Hu", "B+", 2011)
# Access inherited and overridden methods
print(grad.get_details())
Exception HandlingPython exception handling allows to handle exceptions during execution of the program. The follow keywords (blocks) are used with exception handling −
# Create function to divide two numbers
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
else:
print(f"The divide result is : {result}")
finally:
print("Execution complete.")
# Calling function
print("Test Case 1:")
divide_numbers(10, 2)
print("\nTest Case 2:")
divide_numbers(10, 0)
Advertisements
| ||||||||||||||||||||||||||||||||||||||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |