¡Descarga Python Cheat Sheet Mosh Hamedani y más Apuntes en PDF de Programación Informática solo en Docsity!
Python
Cheat Sheet
Mosh Hamedani
Code with Mosh (codewithmosh.com)
1st Edition
About this Cheat Sheet
This cheat sheet includes the materials I’ve covered in my Python tutorial for
Beginners on YouTube. Both the YouTube tutorial and this cheat cover the core
language constructs but they are not complete by any means.
If you want to learn everything Python has to offer and become a Python expert,
check out my Complete Python Programming Course:
http://bit.ly/complete-python-course
- Variables
- Comments
- Receiving Input
- Strings
- Arithmetic Operations
- If Statements
- Comparison operators
- While loops
- For loops
- Lists
- Tuples
- Dictionaries
- Functions
- Exceptions
- Classes
- Inheritance
- Modules
- Packages
- Python Standard Library
- Pypi
- Want to Become a Python Expert?
Variables
We use variables to temporarily store data in computer’s memory.
price = 10 rating = 4. course_name = ‘Python for Beginners’ is_published = True
In the above example,
- price is an integer (a whole number without a decimal point)
- rating is a float (a number with a decimal point)
- course_name is a string (a sequence of characters)
- is_published is a boolean. Boolean values can be True or False. Comments
We use comments to add notes to our code. Good comments explain the hows and
whys, not what the code does. That should be reflected in the code itself. Use
comments to add reminders to yourself or other developers, or also explain your
assumptions and the reasons you’ve written code in a certain way.
This is a comment and it won’t get executed.
Our comments can be multiple lines.
Receiving Input
We can receive input from the user by calling the input() function.
birth_year = int(input(‘Birth year: ‘))
The input() function always returns data as a string. So, we’re converting the
result into an integer by calling the built-in int() function.
To check if a string contains a character (or a sequence of characters), we use the in
operator:
contains = ‘Python’ in course Arithmetic Operations
/ # returns a float // # returns an int % # returns the remainder of division ** # exponentiation - x ** y = x to the power of y
Augmented assignment operator:
x = x + 10 x += 10
Operator precedence:
1. parenthesis
2. exponentiation
3. multiplication / division
4. addition / subtraction
If Statements if is_hot: print(“hot day”) elif is_cold: print(“cold day”) else: print(“beautiful day”)
Logical operators:
if has_high_income and has_good_credit: ... if has_high_income or has_good_credit: ... is_day = True is_night = not is_day Comparison operators a > b a >= b (greater than or equal to) a < b a <= b a == b (equals) a != b (not equals) While loops i = 1 while i < 5 : print(i) i += 1
Dictionaries
We use dictionaries to store key/value pairs.
customer = { “name”: “John Smith”, “age”: 30 , “is_verified”: True }
We can use strings or numbers to define keys. They should be unique. We can use
any types for the values.
customer[“name”] # returns “John Smith” customer[“type”] # throws an error customer.get(“type”, “silver”) # returns “silver” customer[“name”] = “new name” Functions
We use functions to break up our code into small chunks. These chunks are easier
to read, understand and maintain. If there are bugs, it’s easier to find bugs in a
small chunk than the entire program. We can also re-use these chunks.
def greet_user(name): print(f”Hi {name}”) greet_user(“John”)
Parameters are placeholders for the data we can pass to functions. Arguments
are the actual values we pass.
We have two types of arguments:
- Positional arguments: their position (order) matters
- Keyword arguments: position doesn’t matter - we prefix them with the parameter
name.
Two positional arguments
greet_user(“John”, “Smith”)
Keyword arguments
calculate_total(order= 50 , shipping= 5 , tax=0.1)
Our functions can return values. If we don’t use the return statement, by default
None is returned. None is an object that represents the absence of a value.
def square(number): return number * number result = square(2) print(result) # prints 4 Exceptions
Exceptions are errors that crash our programs. They often happen because of bad
input or programming errors. It’s our job to anticipate and handle these exceptions
to prevent our programs from cashing.
try: age = int(input(‘Age: ‘)) income = 20000 risk = income / age print(age) except ValueError: print(‘Not a valid number’) except ZeroDivisionError: print(‘Age cannot be 0’) Classes
We use classes to define new types.
class Point: def init(self, x, y): self.x = x self.y = y def move(self): print(“move”)
importing the entire converters module
import converters converters.kg_to_lbs(5)
importing one function in the converters module
from converters import kg_to_lbs kg_to_lbs(5) Packages
A package is a directory with init.py in it. It can contain one or more
modules.
importing the entire sales module
from ecommerce import sales sales.calc_shipping()
importing one function in the sales module
from ecommerce.sales import calc_shipping calc_shipping() Python Standard Library
Python comes with a huge library of modules for performing common tasks such as
sending emails, working with date/time, generating random values, etc.
Random Module import random random.random() # returns a float between 0 to 1 random.randint(1, 6 ) # returns an int between 1 to 6 members = [‘John’, ‘Bob’, ‘Mary’] leader = random.choice(members) # randomly picks an item
Pypi
Python Package Index (pypi.org) is a directory of Python packages published by
Python developers around the world. We use pip to install or uninstall these
packages.
pip install openpyxl pip uninstall openpyxl Want to Become a Python Expert?
If you’re serious about learning Python and getting a job as a Python developer, I
highly encourage you to enroll in my Complete Python Course. Don’t waste your
time following disconnected, outdated tutorials. My Complete Python Course has
everything you need in one place:
- 12 hours of HD video
- Unlimited access - watch it as many times as you want
- Self-paced learning - take your time if you prefer
- Watch it online or download and watch offline
- Certificate of completion - add it to your resume to stand out
- 30-day money-back guarantee - no questions asked
The price for this course is $149 but the first 200 people who have downloaded this
cheat sheet can get it for $14.99 using the coupon code CHEATSHEET :
http://bit.ly/complete-python-course