Ошибка runtime error python

A runtime error is a type of error that occurs during program execution. The Python interpreter executes a script if it is syntactically correct. However, if it encounters an issue at runtime, which is not detected when the script is parsed, script execution may halt unexpectedly.

What Causes Runtime Errors

Some of the most common examples of runtime errors in Python are:

  • Division by zero.
  • Using an undefined variable or function name.
  • Performing an operation on incompatible types.
  • Accessing a list element, dictionary key or object attribute that does not exist.
  • Accessing a file that does not exist.

Python Runtime Error Examples

Here’s a few examples of runtime errors in Python:

Division by zero

If a number is divided by zero in Python, a runtime error is raised:

print(100/0)

In the above example, a number is attempted to be divided by zero. Running the above code raises a ZeroDivisionError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(100/0)
ZeroDivisionError: division by zero

Using an undefined variable or function name

A runtime error is raised if an attempt is made to access an identifier, such as a variable or function name, that is not declared previously:

print(myString)

In the above example, an undefined identifier myString is attempted to be accessed. Running the above code raises a NameError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(myString)
NameError: name 'myString' is not defined

Performing an operation on incompatible types

If an operation, such as addition, multiplication etc., is performed between incompatible data types, a runtime error is raised:

myString = "Hello World"
myNumber = 100
print(myString + myNumber)

In the above example, a string is attempted to be concatenated with a number. Since these types are incompatible, a TypeError is raised when the above code is executed:

File "main.py", line 3, in <module>
    print(myString + myNumber)
TypeError: can only concatenate str (not "int") to str

Accessing a non-existent list element, dictionary key or object attribute

If an attempt is made to access a non-existent index or element in a list, dictionary or   object, a runtime error is raised.

numbers = [1, 2, 3]
print(numbers[3])

In the above example, an attempt is made to access an item in a list using an out-of-range index, which raises an IndexError:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(numbers[3])
IndexError: list index out of range.

Accessing a file that does not exist

If a file that does not exist is attempted to be accessed, a runtime error is raised:

open("myFile.txt", "r")

In the above example, a non-existent file myFile.txt is attempted to be opened in read-only mode, which raises a FileNotFoundError:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    open("myFile.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'myFile.txt'

How to Fix Runtime Errors in Python

To fix runtime errors in Python, the following steps can be taken:

  1. Identify the error message and note the specific problem being reported.
  2. Check the code for logical, mathematical or typographical errors.
  3. Ensure all identifiers are defined properly before being used.
  4. Make sure the correct data types are being used and are being used correctly.
  5. Verify that list items, dictionary keys, and other objects are being accessed using valid indices or keys.
  6. If necessary, consult the documentation for the relevant library or module.

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Обработка ошибок увеличивает отказоустойчивость кода, защищая его от потенциальных сбоев, которые могут привести к преждевременному завершению работы.

Синтаксис обработки исключений

Прежде чем переходить к обсуждению того, почему обработка исключений так важна, и рассматривать встроенные в Python исключения, важно понять, что есть тонкая грань между понятиями ошибки и исключения.

Ошибку нельзя обработать, а исключения Python обрабатываются при выполнении программы. Ошибка может быть синтаксической, но существует и много видов исключений, которые возникают при выполнении и не останавливают программу сразу же. Ошибка может указывать на критические проблемы, которые приложение и не должно перехватывать, а исключения — состояния, которые стоит попробовать перехватить. Ошибки — вид непроверяемых и невозвратимых ошибок, таких как OutOfMemoryError, которые не стоит пытаться обработать.

Обработка исключений делает код более отказоустойчивым и помогает предотвращать потенциальные проблемы, которые могут привести к преждевременной остановке выполнения. Представьте код, который готов к развертыванию, но все равно прекращает работу из-за исключения. Клиент такой не примет, поэтому стоит заранее обработать конкретные исключения, чтобы избежать неразберихи.

Ошибки могут быть разных видов:

  • Синтаксические
  • Недостаточно памяти
  • Ошибки рекурсии
  • Исключения

Разберем их по очереди.

Синтаксические ошибки (SyntaxError)

Синтаксические ошибки часто называют ошибками разбора. Они возникают, когда интерпретатор обнаруживает синтаксическую проблему в коде.

Рассмотрим на примере.

a = 8
b = 10
c = a b
File "", line 3
 c = a b
       ^
SyntaxError: invalid syntax

Стрелка вверху указывает на место, где интерпретатор получил ошибку при попытке исполнения. Знак перед стрелкой указывает на причину проблемы. Для устранения таких фундаментальных ошибок Python будет делать большую часть работы за программиста, выводя название файла и номер строки, где была обнаружена ошибка.

Недостаточно памяти (OutofMemoryError)

Ошибки памяти чаще всего связаны с оперативной памятью компьютера и относятся к структуре данных под названием “Куча” (heap). Если есть крупные объекты (или) ссылки на подобные, то с большой долей вероятности возникнет ошибка OutofMemory. Она может появиться по нескольким причинам:

  • Использование 32-битной архитектуры Python (максимальный объем выделенной памяти невысокий, между 2 и 4 ГБ);
  • Загрузка файла большого размера;
  • Запуск модели машинного обучения/глубокого обучения и много другое;

Обработать ошибку памяти можно с помощью обработки исключений — резервного исключения. Оно используется, когда у интерпретатора заканчивается память и он должен немедленно остановить текущее исполнение. В редких случаях Python вызывает OutofMemoryError, позволяя скрипту каким-то образом перехватить самого себя, остановить ошибку памяти и восстановиться.

Но поскольку Python использует архитектуру управления памятью из языка C (функция malloc()), не факт, что все процессы восстановятся — в некоторых случаях MemoryError приведет к остановке. Следовательно, обрабатывать такие ошибки не рекомендуется, и это не считается хорошей практикой.

Ошибка рекурсии (RecursionError)

Эта ошибка связана со стеком и происходит при вызове функций. Как и предполагает название, ошибка рекурсии возникает, когда внутри друг друга исполняется много методов (один из которых — с бесконечной рекурсией), но это ограничено размером стека.

Все локальные переменные и методы размещаются в стеке. Для каждого вызова метода создается стековый кадр (фрейм), внутрь которого помещаются данные переменной или результат вызова метода. Когда исполнение метода завершается, его элемент удаляется.

Чтобы воспроизвести эту ошибку, определим функцию recursion, которая будет рекурсивной — вызывать сама себя в бесконечном цикле. В результате появится ошибка StackOverflow или ошибка рекурсии, потому что стековый кадр будет заполняться данными метода из каждого вызова, но они не будут освобождаться.

def recursion():
    return recursion()

recursion()
---------------------------------------------------------------------------

RecursionError                            Traceback (most recent call last)

 in 
----> 1 recursion()


 in recursion()
      1 def recursion():
----> 2     return recursion()


... last 1 frames repeated, from the frame below ...


 in recursion()
      1 def recursion():
----> 2     return recursion()


RecursionError: maximum recursion depth exceeded

Ошибка отступа (IndentationError)

Эта ошибка похожа по духу на синтаксическую и является ее подвидом. Тем не менее она возникает только в случае проблем с отступами.

Пример:

for i in range(10):
    print('Привет Мир!')
  File "", line 2
    print('Привет Мир!')
        ^
IndentationError: expected an indented block

Исключения

Даже если синтаксис в инструкции или само выражение верны, они все равно могут вызывать ошибки при исполнении. Исключения Python — это ошибки, обнаруживаемые при исполнении, но не являющиеся критическими. Скоро вы узнаете, как справляться с ними в программах Python. Объект исключения создается при вызове исключения Python. Если скрипт не обрабатывает исключение явно, программа будет остановлена принудительно.

Программы обычно не обрабатывают исключения, что приводит к подобным сообщениям об ошибке:

Ошибка типа (TypeError)

a = 2
b = 'PythonRu'
a + b
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

 in 
      1 a = 2
      2 b = 'PythonRu'
----> 3 a + b


TypeError: unsupported operand type(s) for +: 'int' and 'str'

Ошибка деления на ноль (ZeroDivisionError)

10 / 0
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

 in 
----> 1 10 / 0


ZeroDivisionError: division by zero

Есть разные типы исключений в Python и их тип выводится в сообщении: вверху примеры TypeError и ZeroDivisionError. Обе строки в сообщениях об ошибке представляют собой имена встроенных исключений Python.

Оставшаяся часть строки с ошибкой предлагает подробности о причине ошибки на основе ее типа.

Теперь рассмотрим встроенные исключения Python.

Встроенные исключения

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- LookupError
      |    +-- IndexError
      |    +-- KeyError
      +-- MemoryError
      +-- NameError
      |    +-- UnboundLocalError
      +-- OSError
      |    +-- BlockingIOError
      |    +-- ChildProcessError
      |    +-- ConnectionError
      |    |    +-- BrokenPipeError
      |    |    +-- ConnectionAbortedError
      |    |    +-- ConnectionRefusedError
      |    |    +-- ConnectionResetError
      |    +-- FileExistsError
      |    +-- FileNotFoundError
      |    +-- InterruptedError
      |    +-- IsADirectoryError
      |    +-- NotADirectoryError
      |    +-- PermissionError
      |    +-- ProcessLookupError
      |    +-- TimeoutError
      +-- ReferenceError
      +-- RuntimeError
      |    +-- NotImplementedError
      |    +-- RecursionError
      +-- SyntaxError
      |    +-- IndentationError
      |         +-- TabError
      +-- SystemError
      +-- TypeError
      +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError
      +-- Warning
           +-- DeprecationWarning
           +-- PendingDeprecationWarning
           +-- RuntimeWarning
           +-- SyntaxWarning
           +-- UserWarning
           +-- FutureWarning
           +-- ImportWarning
           +-- UnicodeWarning
           +-- BytesWarning
           +-- ResourceWarning

Прежде чем переходить к разбору встроенных исключений быстро вспомним 4 основных компонента обработки исключения, как показано на этой схеме.

  • Try: он запускает блок кода, в котором ожидается ошибка.
  • Except: здесь определяется тип исключения, который ожидается в блоке try (встроенный или созданный).
  • Else: если исключений нет, тогда исполняется этот блок (его можно воспринимать как средство для запуска кода в том случае, если ожидается, что часть кода приведет к исключению).
  • Finally: вне зависимости от того, будет ли исключение или нет, этот блок кода исполняется всегда.

В следующем разделе руководства больше узнаете об общих типах исключений и научитесь обрабатывать их с помощью инструмента обработки исключения.

Ошибка прерывания с клавиатуры (KeyboardInterrupt)

Исключение KeyboardInterrupt вызывается при попытке остановить программу с помощью сочетания Ctrl + C или Ctrl + Z в командной строке или ядре в Jupyter Notebook. Иногда это происходит неумышленно и подобная обработка поможет избежать подобных ситуаций.

В примере ниже если запустить ячейку и прервать ядро, программа вызовет исключение KeyboardInterrupt. Теперь обработаем исключение KeyboardInterrupt.

try:
    inp = input()
    print('Нажмите Ctrl+C и прервите Kernel:')
except KeyboardInterrupt:
    print('Исключение KeyboardInterrupt')
else:
    print('Исключений не произошло')

Исключение KeyboardInterrupt

Стандартные ошибки (StandardError)

Рассмотрим некоторые базовые ошибки в программировании.

Арифметические ошибки (ArithmeticError)

  • Ошибка деления на ноль (Zero Division);
  • Ошибка переполнения (OverFlow);
  • Ошибка плавающей точки (Floating Point);

Все перечисленные выше исключения относятся к классу Arithmetic и вызываются при ошибках в арифметических операциях.

Деление на ноль (ZeroDivisionError)

Когда делитель (второй аргумент операции деления) или знаменатель равны нулю, тогда результатом будет ошибка деления на ноль.

try:  
    a = 100 / 0
    print(a)
except ZeroDivisionError:  
    print("Исключение ZeroDivisionError." )
else:  
    print("Успех, нет ошибок!")
Исключение ZeroDivisionError.

Переполнение (OverflowError)

Ошибка переполнение вызывается, когда результат операции выходил за пределы диапазона. Она характерна для целых чисел вне диапазона.

try:  
    import math
    print(math.exp(1000))
except OverflowError:  
    print("Исключение OverFlow.")
else:  
    print("Успех, нет ошибок!")
Исключение OverFlow.

Ошибка утверждения (AssertionError)

Когда инструкция утверждения не верна, вызывается ошибка утверждения.

Рассмотрим пример. Предположим, есть две переменные: a и b. Их нужно сравнить. Чтобы проверить, равны ли они, необходимо использовать ключевое слово assert, что приведет к вызову исключения Assertion в том случае, если выражение будет ложным.

try:  
    a = 100
    b = "PythonRu"
    assert a == b
except AssertionError:  
    print("Исключение AssertionError.")
else:  
    print("Успех, нет ошибок!")

Исключение AssertionError.

Ошибка атрибута (AttributeError)

При попытке сослаться на несуществующий атрибут программа вернет ошибку атрибута. В следующем примере можно увидеть, что у объекта класса Attributes нет атрибута с именем attribute.

class Attributes(obj):
    a = 2
    print(a)

try:
    obj = Attributes()
    print(obj.attribute)
except AttributeError:
    print("Исключение AttributeError.")

2
Исключение AttributeError.

Ошибка импорта (ModuleNotFoundError)

Ошибка импорта вызывается при попытке импортировать несуществующий (или неспособный загрузиться) модуль в стандартном пути или даже при допущенной ошибке в имени.

import nibabel
---------------------------------------------------------------------------

ModuleNotFoundError                       Traceback (most recent call last)

 in 
----> 1 import nibabel


ModuleNotFoundError: No module named 'nibabel'

Ошибка поиска (LookupError)

LockupError выступает базовым классом для исключений, которые происходят, когда key или index используются для связывания или последовательность списка/словаря неверна или не существует.

Здесь есть два вида исключений:

  • Ошибка индекса (IndexError);
  • Ошибка ключа (KeyError);

Ошибка ключа

Если ключа, к которому нужно получить доступ, не оказывается в словаре, вызывается исключение KeyError.

try:  
    a = {1:'a', 2:'b', 3:'c'}  
    print(a[4])  
except LookupError:  
    print("Исключение KeyError.")
else:  
    print("Успех, нет ошибок!")

Исключение KeyError.

Ошибка индекса

Если пытаться получить доступ к индексу (последовательности) списка, которого не существует в этом списке или находится вне его диапазона, будет вызвана ошибка индекса (IndexError: list index out of range python).

try:
    a = ['a', 'b', 'c']  
    print(a[4])  
except LookupError:  
    print("Исключение IndexError, индекс списка вне диапазона.")
else:  
    print("Успех, нет ошибок!")
Исключение IndexError, индекс списка вне диапазона.

Ошибка памяти (MemoryError)

Как уже упоминалось, ошибка памяти вызывается, когда операции не хватает памяти для выполнения.

Ошибка имени (NameError)

Ошибка имени возникает, когда локальное или глобальное имя не находится.

В следующем примере переменная ans не определена. Результатом будет ошибка NameError.

try:
    print(ans)
except NameError:  
    print("NameError: переменная 'ans' не определена")
else:  
    print("Успех, нет ошибок!")
NameError: переменная 'ans' не определена

Ошибка выполнения (Runtime Error)

Ошибка «NotImplementedError»
Ошибка выполнения служит базовым классом для ошибки NotImplemented. Абстрактные методы определенного пользователем класса вызывают это исключение, когда производные методы перезаписывают оригинальный.

class BaseClass(object):
    """Опередляем класс"""
    def __init__(self):
        super(BaseClass, self).__init__()
    def do_something(self):
	# функция ничего не делает
        raise NotImplementedError(self.__class__.__name__ + '.do_something')

class SubClass(BaseClass):
    """Реализует функцию"""
    def do_something(self):
        # действительно что-то делает
        print(self.__class__.__name__ + ' что-то делает!')

SubClass().do_something()
BaseClass().do_something()

SubClass что-то делает!



---------------------------------------------------------------------------

NotImplementedError                       Traceback (most recent call last)

 in 
     14
     15 SubClass().do_something()
---> 16 BaseClass().do_something()


 in do_something(self)
      5     def do_something(self):
      6         # функция ничего не делает
----> 7         raise NotImplementedError(self.__class__.__name__ + '.do_something')
      8
      9 class SubClass(BaseClass):


NotImplementedError: BaseClass.do_something

Ошибка типа (TypeError)

Ошибка типа вызывается при попытке объединить два несовместимых операнда или объекта.

В примере ниже целое число пытаются добавить к строке, что приводит к ошибке типа.

try:
    a = 5
    b = "PythonRu"
    c = a + b
except TypeError:
    print('Исключение TypeError')
else:
    print('Успех, нет ошибок!')

Исключение TypeError

Ошибка значения (ValueError)

Ошибка значения вызывается, когда встроенная операция или функция получают аргумент с корректным типом, но недопустимым значением.

В этом примере встроенная операция float получат аргумент, представляющий собой последовательность символов (значение), что является недопустимым значением для типа: число с плавающей точкой.

try:
    print(float('PythonRu'))
except ValueError:
    print('ValueError: не удалось преобразовать строку в float: 'PythonRu'')
else:
    print('Успех, нет ошибок!')
ValueError: не удалось преобразовать строку в float: 'PythonRu'

Пользовательские исключения в Python

В Python есть много встроенных исключений для использования в программе. Но иногда нужно создавать собственные со своими сообщениями для конкретных целей.

Это можно сделать, создав новый класс, который будет наследовать из класса Exception в Python.

class UnAcceptedValueError(Exception):   
    def __init__(self, data):    
        self.data = data
    def __str__(self):
        return repr(self.data)

Total_Marks = int(input("Введите общее количество баллов: "))
try:
    Num_of_Sections = int(input("Введите количество разделов: "))
    if(Num_of_Sections < 1):
        raise UnAcceptedValueError("Количество секций не может быть меньше 1")
except UnAcceptedValueError as e:
    print("Полученная ошибка:", e.data)

Введите общее количество баллов: 10
Введите количество разделов: 0
Полученная ошибка: Количество секций не может быть меньше 1

В предыдущем примере если ввести что-либо меньше 1, будет вызвано исключение. Многие стандартные исключения имеют собственные исключения, которые вызываются при возникновении проблем в работе их функций.

Недостатки обработки исключений в Python

У использования исключений есть свои побочные эффекты, как, например, то, что программы с блоками try-except работают медленнее, а количество кода возрастает.

Дальше пример, где модуль Python timeit используется для проверки времени исполнения 2 разных инструкций. В stmt1 для обработки ZeroDivisionError используется try-except, а в stmt2if. Затем они выполняются 10000 раз с переменной a=0. Суть в том, чтобы показать разницу во времени исполнения инструкций. Так, stmt1 с обработкой исключений занимает больше времени чем stmt2, который просто проверяет значение и не делает ничего, если условие не выполнено.

Поэтому стоит ограничить использование обработки исключений в Python и применять его в редких случаях. Например, когда вы не уверены, что будет вводом: целое или число с плавающей точкой, или не уверены, существует ли файл, который нужно открыть.

import timeit
setup="a=0"
stmt1 = '''
try:
    b=10/a
except ZeroDivisionError:
    pass'''

stmt2 = '''
if a!=0:
    b=10/a'''

print("time=",timeit.timeit(stmt1,setup,number=10000))
print("time=",timeit.timeit(stmt2,setup,number=10000))

time= 0.003897680000136461
time= 0.0002797570000439009

Выводы!

Как вы могли увидеть, обработка исключений помогает прервать типичный поток программы с помощью специального механизма, который делает код более отказоустойчивым.

Обработка исключений — один из основных факторов, который делает код готовым к развертыванию. Это простая концепция, построенная всего на 4 блоках: try выискивает исключения, а except их обрабатывает.

Очень важно поупражняться в их использовании, чтобы сделать свой код более отказоустойчивым.

Image of Python RuntimeError (Examples & Use Cases) | Initial Commit

Table of Contents

  • Introduction
  • What is a Runtimeerror error?
  • What causes run time error message in Python?
  • How do you handle a runtime error?
  • What is runtime error message example?
  • Zero Division Error raised
  • Index Error
  • How do I fix a built-in exception value error in Python?
  • What causes the built-in exception overflow error?
  • Summary
  • Next steps
  • References

Introduction

There are several types of errors in Python that help you debug your program. When you run your program, Python first checks for any syntax errors, and then runs the program. Errors thrown during syntax checking are called syntax errors. Errors that are thrown once the code is run are under the class of runtime errors. These errors will always include an error message printed to the interpreter. In this tutorial, you will learn several different types of runtime errors in python, what their error messages are, and how to fix them.

What is a Runtimeerror error?

A python run-time error is a class of python built-in exceptions that are thrown at run-time. There are many different types of run-time errors, we will cover them in this article. Some examples include type errors and name errors. run-time attribute errors fall under a larger group of concrete built-in exceptions in Python.

What causes run time error message in Python?

There are many things that can raise a runtime errors in python depending on the type of error that is thrown. Some questions you can ask yourself to debug including, are you:

  • dividing by zero?
  • using incorrect types in operations?
  • indexing past the length of a list?
  • accessing a key in dictionary that doesn’t exist?
  • using variables that haven’t been defined yet?
  • trying to import or access a file that does not exist?

If you checked for all of these things and you are still getting an error, then it may be caused by something else. We will cover some examples of causes and fixes of certain errors in the following sections.

How do you handle a runtime error?

How you handle a run-time error in python depends on the specific error that was thrown. Once way to generally handle run-time errors is by using a try/except block. You include the code that may cause a runtime error in the try clause. You can then specify how you want to handle the code in the case of an error in the except clause. Here is an example:

>>> y = 12
>>> x = 0
>>> try:
... z = y / x
>>> except:
...print("An error occurred")
...z = 0

This way you are alerted of the error without causing a raised exception and stopping your program.

What is runtime error message example?

Every run-time error in python prints a message to the interpreter indicating what caused raised error and what line it was on. Let’s take a look at some examples of common run-time errors and how to fix them.

Zero Division Error raised

A ZeroDivisionError is thrown when you try to divide or modulo by zero in your code, for example:

>>> x = 0
>>> y = 2
>>> if y % x == 0:
... print(y, :is divisible by", x)
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
ZeroDivisionError: integer division or modulo by zero

Note that the error message idicates the error is happening on line 3. We can avoid this by adding a check to make sure the number we’re modding by isn’t 0 before we perform the operation:

>>> x = 0
>>> y = 2
>>> if (x != 0) and (y % x == 0):
... print(y, "is divisible by", x)

Type Error

A TypeError is thrown when you try to perform an operation with incorrect types. For example, if you tried to concatenate an int and a string, you get a type error:

>>> x = "1"
>>> y = 2
>>> z = x + y
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The error will also specify which operation is throwing the error and what types you’re trying to use. In this case we can resolve this error by casting all the variables to integers to make sure we are only adding integers:

>>> x = "1"
>>> y = 2
>>> z = int(x) + int(y)
>>> print(x+y)
3

Another common cause for type errors is attempting to loop through an incorrect type. For example, attempting to iterate through an integer:

>>> for i in 10:
... print(i)
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: 'int' object is not iterable

In this case the error tells us that we are attempting to iterate through an integer on line 3, which is not a type we can iterate through. Instead we want to use a for-range loop:

>>> for i in range(10):
... print(i)
0
1

One example of a library function that can throw a type error is the pandas.head() method from the Pandas library. The head function throws a type error if you provide an argument that is not an integer:

>>>df.head(2.5)
TypeError: cannot do positional indexing on RangeIndex with these indexers [2.5] of type float

You can learn more about the pandas head function here.

Key Error

A KeyError is thrown when you are trying to access a key in a dictionary that doesn’t exist. For example:

>>> d = {1: ["a"], 2: ["b"]}
>>> print(d[3])
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyError: 3

The error will specify which key you are trying to access that does not exist. You can fix this by making sure to check if the key is in the dictionary before trying to access that specific key. You can check if a key exists in a dictionary by using the in function, which returns a boolean:

>>> d = {1: ["a"], 2: ["b"]}
>>> if 3 in d:
... print(d[3])

Index Error

An index error is caused by indexing into a list with an out of bounds index:

>>> L = [1,2,3]
>>> for i in range(10):
... print(L[i])

We can fix this by either adjusting the for loop to only loop over the range of the list, or adding a check before we index into the list to make sure the index is in range:

>>> L = [1,2,3]
>>> for i in range(len(L)):
... print(L[i])

or

>>> L = [1,2,3]
>>> for i in range(10):
... if i < len(L):
... print(L[i])

Name Error

A NameError is thrown when you try to use a variable that is not defined yet in the file. For example:

>>>print(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

You can fix this by defining the variable on a line before the line it is called on:

>>>x = 5
>>>print(x)
5

Name errors can also be thrown if you try to use a variable that is already defined but out of scope. For example, if you try to use a local variable defined inside of a function globally:

>>>def foo(x,y):
             print(x + y)
>>>
>>>print(x)
Traceback (most recent call last):
  File "<string>", line 4, in <module>
NameError: name 'x' is not defined

To fix this, make sure you are only trying to access variables that are within scope.

File not found error

A FileNotFoundError is thrown when you try to access a file that does not exist in the directory you specified:

>>> open("file", "r")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'file'

There are a couple ways to resolve the error. First you should check to make sure that the file you are trying to access is in your current directory. If not, make sure to specify the full filepath when trying to access that file, for example:

>>> open("/C:/folder1/folder2/file", "r")

How do I fix a built-in exception value error in Python?

A value error is caused by giving a function an input that is of the correct type, but an incorrect value. For example:

>>>import math
>>>math.sqrt(-100)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: math domain error

Here we get an error because the math.sqrt function only works with positive integers or zero as input. We can prevent this error by making sure that anything passed into the function is greater than or equal to zero.

What causes the built-in exception overflow error?

An overflow error is caused by an arithmetic operation that is too large for Python to represent.

For example:

>>>math.exp(5000)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: math range error

You can prevent overflow errors by making sure that the numbers you pass into functions are not too large.

Summary

In this tutorial, you learned that run-time errors are, when they occur in your program, and several ways to fix them. First, you learned that run-time errors are a type of built-in exceptions thrown at run-time. Next, you learned some common causes of run-time errors like dividing by zero and using incorrect types in operations. Then, you learned how to generally handle run-time errors using a try-except block. Last, you looked at several examples of things that can raise run-time errors and how to resolve them, including some less common errors like overflow errors and value errors.

Next steps

If you’re interested in learning more about the basics of Python, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you’ll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

References

  1. Concrete Exceptions
  2. Built-in Exceptions

Final Notes

by Radu Tyrsina

Radu Tyrsina has been a Windows fan ever since he got his first PC, a Pentium III (a monster at that time). For most of the kids of… read more


Updated on March 4, 2021

  • A run-time error happens when Python understands what you are saying, but runs into trouble when following your instructions.
  • You need to know that Python runs the program in two steps.
  • Not only Python features runtime errors and if you stumble across one, check our Runtime Errors Hub.
  • We wrote extensively about developer tools like Python. Go to our Developer tools Hub.

How to fix Python runtime error

XINSTALL BY CLICKING THE DOWNLOAD FILE

Try Outbyte Driver Updater to resolve driver issues entirely:
This software will simplify the process by both searching and updating your drivers to prevent various malfunctions and enhance your PC stability. Check all your drivers now in 3 easy steps:

  1. Download Outbyte Driver Updater.
  2. Launch it on your PC to find all the problematic drivers.
  3. Afterward, Click Update & Apply Selected to get the latest driver versions.
  • OutByte Driver Updater has been downloaded by 0 readers this month.

Programming is pretty fun but at some point, when you try to run the program, unfortunately, and inevitably, errors will show up. So, causing, understanding, and fixing errors is an important part of programming.

There are three major types of error that you can get in Python but here we will talk about how to solve Python runtime errors.

A run-time error happens when Python understands what you are saying, but runs into trouble when following your instructions.


How can I fix Python runtime error?

So you’ve written everything correctly, in other words, your syntax is correct, but Python still doesn’t understand what you’re saying. Let’s have a simple example of a Python runtime error:

  • print(solution)

If you try to run this simple line, you will receive a runtime error simply because you didn’t define the solution variable. The line doesn’t have sense.

To understand better that conundrum, let’s make an association with English grammar. Let’s take this sentence for instance.

  • Please eat the door.

Grammatically, there is absolutely no problem with this sentence. Everything is there, we have all the syntax elements correct.

But when you are trying to understand the sentence, when you piece up the words, it doesn’t make sense because you know you can open and close the door, even shut it or taking it out but eating it?

In programming, this will be called a run-time error because it shows up before you start the program. There are a few types of runtime errors. In this article, you will learn how to solve them.

1. Use an undefined variable or function.

This can also occur if you use capital letters inconsistently in a variable name:

callMe = “Brad”
print(callme)

Traceback (most recent call last):
  In line 2 of the code you submitted:
    print(callme)
NameError: name 'callme' is not defined

In this case, the program returned the undefined variable error. You defined the variable callMe, but you try to print another variable, callme. You have to use the variables exactly as you define them, case sensitive.


2. Dividing by zero

Guess what? Python cares about math, and in math, dividing by zero makes no sense. 

print(1/0)

Traceback (most recent call last):
  In line 1 of the code you submitted:
    print(1/0)
ZeroDivisionError: division by zero

So this line returns a runtime error as Python can read it properly, but when it comes to executing it, he refuses to do so as it has no mathematical sense.


3. Use operators on the wrong type of data

print(“you are trying to add text and numbers” + 20)

Traceback (most recent call last):
  In line 1 of the code you submitted:
    print("you are trying to add text and numbers" + 20)
TypeError: can only concatenate str (not "int") to str

This line returns the runtime error because you try to add text with numbers, crayons, and oranges, chairs with pigeons, etc. It just doesn’t make sense to perform operations with different types of variables.

You also need to know that Python runs the program in two steps. It first checks the syntax and if the syntax is correct, it goes to the second step of executing the program. That’s where he stumbles on possible runtime errors.

We hope this guide answers all your questions but if you have any others or you run into other problems, please throw them down into the comments section below and we will get back at you ASAP.


newsletter icon

I made a game with Python 2.6. I also made it into an executable with cx_Freeze 4.3. When I run the executable on my computer it came up with this:

Microsoft Visual C++ Runtime Library

Program: C:UserssmmDesktopasteroid shower 1.4.5asteroid.exe


This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

I don’t understand what happened here. I tried solving the problem but with no luck. Then I searched the runtime error on google and it said it might be the compatibility. I wrote the original script on windows vista with the downloaded version of the windows 7 python 2.6. I did this because the windows vista had no internet so I downloaded the python, pygame and cx_freeze .msi files on my windows 7 laptop. Then I transferred the files to the desktop windows vista. Is this the problem? Or maybe the script? I don’t think its the script as I can play the game when it is still a python script. Its a bit long though… I running windows 7 with python 2.6, pygame 2.6 and cx_freeze 4.3. Thanks if you can help me :).

    # By Sandy Goetjens
# Asteroid Shower V1.4.5

import pygame, random, sys, time
from pygame.locals import *

WINDOWWIDTH = 600
WINDOWHEIGHT = 600
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 0, 255)
TEXTCOLOR = WHITE
BACKGROUNDCOLOR = BLACK
FPS = 40
ASTEROIDCIRCLESPEED = 1
ASTEROIDMINSIZE = 10
ASTEROIDMAXSIZE = 40
ASTEROIDMINSPEED = 1
ASTEROIDMAXSPEED = 8
ADDNEWASTEROIDRATE = 10
PLAYERMOVERATE = 5
TOKENSIZE = 20
TOKENSPEED = 8
ADDNEWTOKENRATE = 6
BULLETSPEED = 3
BULLETFIRETIME = 1000
BULLETSIZE = 20
GHOSTSIZE = 20
GHOSTSPEED = 5
ADDNEWGHOSTRATE = 8
HEALTHSIZE = 20
HEALTHSPEED = 10
ADDNEWHEALTHRATE = 9
EYEBALLSIZE = 20
EYEBALLSPEED = 15
ADDNEWARROWRATE = 5
ARROWSIZE = 10
ARROWSPEED = 18
ADDNEWDUSTRATE = 8
DUSTSIZE = 12
DUSTSPEED = 16
ADDNEWEYEBALLRATE = 10
GHOSTSIZE = 20
GHOSTSPEED = 10
ADDNEWGHOSTRATE = 15
NEWASTEROIDSPEED = 30

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: # pressing escape quits
                    terminate()
                return

def playerHasHitHealth(playerRect, healths):
    for h in healths:
        if playerRect.colliderect(h['rect']):
            return True
    return False

def drawAsteroidRotation(ASTEROIDCIRCLESPEED, rotation, asteroids):
    for a in asteroids:
        left = leftCordinOfAsteroid
        pygame.draw.rect(windowSurface, WHITE, (left, ASTEROIDSIZE, ASTEROIDSIZE))
        pygame.display.update()

def asteroidAnimation(asteroids):
    for rotation in asteroids(ASTEROIDCIRCLESPEED):
        drawAsteroidRotation(ASTEROIDCIRCLESPEED, rotation, asteroids)

def bulletHasHitAsteroid(bulletRect, asteroids):
    for b in bullets:
        if bulletRect.colliderect(b['rect']):
            bombExplosion.play()
            return True
            bombExplosion.stop()
    return False

def playerHasHitToken(playerRect, tokens):
    for t in tokens:
        if playerRect.colliderect(t['rect']):
            return True
    return False

def playerHasHitBaddie(playerRect, asteroids):
    for a in asteroids:
        if playerRect.colliderect(a['rect']):
            return True
    return False

def playerHasHitGhost(playerRect, ghosts):
    for g in ghosts:
        if playerRect.colliderect(g['rect']):
            return True
    return False

def playerHasHitEyeball(playerRect, eyeballs):
    for e in eyeballs:
        if playerRect.colliderect(e['rect']):
            return True
    return False

def playerHasHitArrow(playerRect, arrows):
    for r in arrows:
        if playerRect.colliderect(r['rect']):
            return True
    return False

def playerHasHitDust(playerRect, dusts):
    for d in dusts:
        if playerRect.colliderect(d['rect']):
            return True
    return False

def asteroidHasHitBullet(baddieRect, bullets):
    for a in asteroids:
        if asteroidRect.collierect(a['rect']):
            return True
    return False

def drawText(text, font, surface, x, y):
    font = pygame.font.Font(None, 48)
    textobj = font.render(text, 10, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

def version(font, windowSurface, versionbackgroundImage):
    while True:
        windowSurface.blit(versionBackgroundImage, (0, 0))
        drawText('Buy the full game to play more', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 200)
        drawText('levels!! Plus bonus', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 150)
        drawText('updates and new game', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 100)
        drawText('releases!! Presented', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 50)
        drawText('by Desert Labotories', font, windowSurface, (WINDOWWIDTH / 3) - 200, (WINDOWHEIGHT / 3) - 0)
        pygame.display.update()
        waitForPlayerToPressKey()
        return

def Credits(font, windowSurface, creditbackgroundImage):
    while True:
        windowSurface.blit(creditBackgroundImage, (0, 0))
        drawText('Created by Sandy Goetjens', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 50)
        drawText('Presented by Desert Labortories', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 100)
        pygame.display.update()
        waitForPlayerToPressKey()
        return

def waitForPlayerToEnterKeys():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: # pressing escapes quits
                    terminate()
                if event.key == K_c:
                    Credits(font, windowSurface, creditBackgroundImage)
                if event.key == K_x:
                    version(font, windowSurface, versionBackgroundImage)
                return

def Level3(font, windowSurface, level):
    while True:
        drawText('Buy the full version to', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3))
        drawText('continue playing!', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3) + 50)
        drawText('8 new and challenging levels!', font, windowSurface, (WINDOWWIDTH / 3) - 150, (WINDOWHEIGHT / 3 + 100))
        pygame.display.update()
        waitForPlayerToPressKey()
        return

def Level1(font, windowSurface, level, applauseSound):
    while True:
        applauseSound.play()
        drawText('LEVEL 1 completed!', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3))
        drawText('Press a key to continue.', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 50)
        drawText('By Sandy Goetjens.', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 150)
        drawText('RATE US ON FACEBOOK', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 200)
        drawText('Entering BLUE LANDS', font, windowSurface, (WINDOWWIDTH / 3) - 100, (WINDOWHEIGHT / 3) + 250)
        pygame.display.update()
        applauseSound.stop()
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    terminate()
                if True:
                    level = 2
                    kilometres = 3000
                    return


# set up pygame, the window, and the mouse cursor
pygame.init()
global level, kilometres
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_icon(pygame.image.load('asteroid.icon'))
pygame.display.set_caption('Asteroid Shower Demo V1.4.5')
pygame.mouse.set_visible(False)

# set up fonts
font = pygame.font.SysFont(None, 48)

# set up sounds
gameOverSound = pygame.mixer.Sound('gameover.wav')
pygame.mixer.music.load('background.mid')
bombExplosion = pygame.mixer.Sound('explosion-01.wav')
warnSound = pygame.mixer.Sound('alarm02.wav')
applauseSound = pygame.mixer.Sound('applause2.wav')

# set up images
playerImage = pygame.image.load('player.png')
playerRect = playerImage.get_rect()
baddieImage = pygame.image.load('asteroid.png')
baddieRect = baddieImage.get_rect()
tokenImage = pygame.image.load('tokens.png')
bulletImage = pygame.image.load('bullet.png')
bulletRect = bulletImage.get_rect()
ghostImage = pygame.image.load('ghosts.png')
healthImage = pygame.image.load('health.png')
eyeballImage = pygame.image.load('eyeball.png')
arrowImage = pygame.image.load('arrow.png')
dustImage = pygame.image.load('dust.png')
versionBackgroundImage = pygame.image.load('background.png')
creditBackgroundImage = pygame.image.load('creditsbackground.png')

creditsPage = pygame.image.load('credits.png')
desertLabs = pygame.image.load('desert labs.png')

# show the "Start" screen
windowSurface.blit(creditsPage, (0, 0))
pygame.time.wait(1000)
drawText('Asteroid Shower ', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 4 - 100))
drawText('Press a key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 4 - 50))
pygame.display.update()
waitForPlayerToEnterKeys()

level = 0
bullet = 50
token = 0
topScore = 0
while True:
    # set up the start of the game
    tokens = []
    asteroids = []
    bullets = []
    eyeballs = []
    arrows = []
    dusts = []
    ghosts = []
    healths = []
    score = 0
    health = 100
    kilometres = 2500
    playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
    moveLeft = moveRight = moveUp = moveDown = False
    reverseCheat = slowCheat = False
    asteroidAddCounter = 0
    ghostAddCounter = 0
    tokenAddCounter = 0
    healthAddCounter = 0
    eyeballAddCounter = 0
    arrowAddCounter = 0
    dustAddCounter = 0
    pygame.mixer.music.play(-1, 0.0)

    while True: # the game loop runs while the game part is playing
        score += 1 # increase score
        kilometres -= 1 # decrease kilomteres

        if level == 0:
            if kilometres == 0:
                level = 2
                kilometres = 3000
                Level1(font, windowSurface, level, applauseSound)

        # Go to level 3 title
        if level == 2 and kilometres == 0:
            Level3(font, windowSurface, level)

        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()

            if event.type == KEYDOWN:
                if event.key == ord('z'):
                    reverseCheat = True
                if event.key == ord('x'):
                    slowCheat = True
                if event.key == K_LEFT or event.key == ord('a'):
                    moveRight = False
                    moveLeft = True
                if event.key == K_RIGHT or event.key == ord('d'):
                    moveLeft = False
                    moveRight = True
                if event.key == K_UP or event.key == ord('w'):
                    moveDown = False
                    moveUp = True
                if event.key == K_DOWN or event.key == ord('s'):
                    moveUp = False
                    moveDown = True
                if event.key == K_z:
                    if token > 500:
                        token -= 500
                        if bullet < 200:
                            bullet += 50
                if event.key == K_x:
                    if token > 600:
                        token -= 600

            if event.type == KEYUP:
                if event.key == ord('z'):
                    reverseCheat = False
                    score = 0
                if event.key == ord('x'):
                    slowCheat = False
                    score = 0
                if event.key == K_ESCAPE:
                    terminate()

                if event.key == K_LEFT or event.key == ord('a'):
                    moveLeft = False
                if event.key == K_RIGHT or event.key == ord('d'):
                    moveRight = False
                if event.key == K_UP or event.key == ord('w'):
                    moveUp = False
                if event.key == K_DOWN or event.key == ord('s'):
                    moveDown = False

            if event.type == MOUSEMOTION:
                # If the mouse moves, move the player where the cursor is.
                playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)

            if token > 0:
                if event.type == MOUSEBUTTONUP:
                    # If player clicks mouse bullets will fire
                    if bullet > 0:
                        bullet -= 1
                        newBullet = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-BULLETSIZE), 0 - BULLETSIZE, BULLETSIZE, BULLETSIZE),
                                     'speed': (BULLETSPEED),
                                     'surface':pygame.transform.scale(bulletImage, (BULLETSIZE, BULLETSIZE)),
                                     }

                        bullets.append(newBullet)

        # Add new tokens at the top of the screen, if needed
        if not reverseCheat and not slowCheat:
            tokenAddCounter += 1
        if tokenAddCounter == ADDNEWTOKENRATE:
            tokenAddCounter = 0
            newToken = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-TOKENSIZE), 0 - TOKENSIZE, TOKENSIZE, TOKENSIZE),
                        'speed': (TOKENSPEED),
                        'surface':pygame.transform.scale(tokenImage, (TOKENSIZE, TOKENSIZE)),
                        }

            tokens.append(newToken)

        if level == 0:
            # Add new baddies at the top of the screen, if needed.
            if not reverseCheat and not slowCheat:
                asteroidAddCounter += 1
            if asteroidAddCounter == ADDNEWASTEROIDRATE:
                asteroidAddCounter = 0
                asteroidSize = random.randint(ASTEROIDMINSIZE, ASTEROIDMAXSIZE)
                newAsteroid = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-asteroidSize), 0 - asteroidSize, asteroidSize, asteroidSize),
                               'speed': random.randint(ASTEROIDMINSPEED, ASTEROIDMAXSPEED),
                               'surface':pygame.transform.scale(baddieImage, (asteroidSize, asteroidSize)),
                               }

                asteroids.append(newAsteroid)

        if level == 0:
            if not reverseCheat and not slowCheat:
                ghostAddCounter += 1
            if ghostAddCounter == ADDNEWGHOSTRATE:
                ghostAddCounter = 0
                newGhost = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-GHOSTSIZE), 0 - GHOSTSIZE, GHOSTSIZE, GHOSTSIZE),
                            'speed': (GHOSTSPEED),
                            'surface': pygame.transform.scale(ghostImage, (GHOSTSIZE, GHOSTSIZE)),
                            }

                ghosts.append(newGhost)

        if health < 50:
            if not reverseCheat and not slowCheat:
                healthAddCounter += 1
            if healthAddCounter == ADDNEWHEALTHRATE:
                healthAddCounter = 0
                newHealth = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-HEALTHSIZE), 0 - HEALTHSIZE, HEALTHSIZE, HEALTHSIZE),
                             'speed': (HEALTHSPEED),
                             'surface': pygame.transform.scale(healthImage, (HEALTHSIZE, HEALTHSIZE)),
                             }

                healths.append(newHealth)

        if level == 2:
            if not reverseCheat and not slowCheat:
                eyeballAddCounter += 1
            if eyeballAddCounter == ADDNEWEYEBALLRATE:
                eyeballAddCounter = 0
                newEyeball = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-EYEBALLSIZE), 0 - EYEBALLSIZE, EYEBALLSIZE, EYEBALLSIZE),
                              'speed': (EYEBALLSPEED),
                              'surface': pygame.transform.scale(eyeballImage, (EYEBALLSIZE, EYEBALLSIZE)),
                              }

                eyeballs.append(newEyeball)

        if level == 2:
            if not reverseCheat and not slowCheat:
                arrowAddCounter += 1
            if arrowAddCounter == ADDNEWARROWRATE:
                arrowAddCounter = 0
                newArrow = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-ARROWSIZE), 0 - ARROWSIZE, ARROWSIZE, ARROWSIZE),
                            'speed': (ARROWSPEED),
                            'surface': pygame.transform.scale(arrowImage, (ARROWSIZE, ARROWSIZE)),
                            }

                arrows.append(newArrow)

        if level == 2:
            if not reverseCheat and not slowCheat:
                dustAddCounter += 1
            if dustAddCounter == ADDNEWDUSTRATE:
                dustAddCounter = 0
                newDust = {'rect': pygame.Rect(random.randint(0, WINDOWWIDTH-DUSTSIZE), 0 - DUSTSIZE, DUSTSIZE, DUSTSIZE),
                           'speed': (DUSTSPEED),
                           'surface': pygame.transform.scale(dustImage, (DUSTSIZE, DUSTSIZE)),
                           }

                dusts.append(newDust)

        # Move the player around.
        if moveLeft and playerRect.left > 0:
            playerRect.move_ip(-1 * PLAYERMOVERATE, 0)
        if moveRight and playerRect.right < WINDOWWIDTH:
            playerRect.move_ip(PLAYERMOVERATE, 0)
        if moveUp and playerRect.top > 0:
            playerRect.move_ip(0, -1 * PLAYERMOVERATE)
        if moveDown and playerRect.bottom < WINDOWHEIGHT:
            playerRect.move_ip(0, PLAYERMOVERATE)

        # Move the mouse cursor to match the player.
        pygame.mouse.set_pos(playerRect.centerx, playerRect.centery)

        # Move the baddies down.
        for a in asteroids:
            if not reverseCheat and not slowCheat:
                a['rect'].move_ip(0, a['speed'])
            elif reverseCheat:
                a['rect'].move_ip(0, -5)
            elif slowCheat:
                a['rect'].move_ip(0, 1)

         # Delete baddies that have fallen past the bottom.
        for a in asteroids[:]:
            if a['rect'].top > WINDOWHEIGHT:
                asteroids.remove(a)

        for g in ghosts:
            if not reverseCheat and not slowCheat:
                g['rect'].move_ip(0, g['speed'])
            elif reverseCheat:
                g['rect'].move_ip(0, -5)
            elif slowCheat:
                g['rect'].move_ip(0, 1)

        # Delete each ghost that have fallen past the bottom
        for g in ghosts[:]:
            if g['rect'].top > WINDOWHEIGHT:
                ghosts.remove(g)

        # Move the tokens down
        for t in tokens:
            if not reverseCheat and not slowCheat:
                t['rect'].move_ip(0, t['speed'])
            elif reverseCheat:
                t['rect'].move_ip(0, -5)
            elif slowCheat:
                t['rect'].move_ip(0, 1)

        # Delete each token that have fallen past the bottom
        for t in tokens[:]:
            if t['rect'].top > WINDOWHEIGHT:
                tokens.remove(t)

        # Move bullets down
        for b in bullets:
            if not reverseCheat and not slowCheat: 
                b['rect'].move_ip(0, b['speed'])
            elif reverseCheat:
                b['rect'].move_ip(0, -5)
            elif slowCheat:
                b['rect'].move_ip(0, 1)

        for b in bullets[:]:
            if b['rect'].top > WINDOWHEIGHT:
                bullets.remove(b)

        # Move health down
        for h in healths:
            if not reverseCheat and not slowCheat:
                h['rect'].move_ip(0, h['speed'])
            elif reverseCheat:
                h['rect'].move_ip(0, -5)
            elif slowCheat:
                h['rect'].move_ip(0, -1)

        for h in healths[:]:
            if h['rect'].top > WINDOWHEIGHT:
                healths.remove(h)

        # Move eyeballs down
        for e in eyeballs:
            if not reverseCheat and not slowCheat:
                e['rect'].move_ip(0, e['speed'])
            elif reverseCheat:
                e['rect'].move_ip(0, -5)
            elif slowCheat:
                e['rect'].move_ip(0, -1)

        for e in eyeballs[:]:
            if e['rect'].top > WINDOWHEIGHT:
                eyeballs.remove(e)

        for r in arrows:
            if not reverseCheat and not slowCheat:
                r['rect'].move_ip(0, r['speed'])
            elif reverseCheat:
                r['rect'].move_ip(0, -5)
            elif slowCheat:
                r['rect'].move_ip(0, -1)

        for r in arrows[:]:
            if r['rect'].top > WINDOWHEIGHT:
                arrows.remove(r)

        for d in dusts:
            if not reverseCheat and not slowCheat:
                d['rect'].move_ip(0, d['speed'])
            elif reverseCheat:
                d['rect'].move_ip(0, -5)
            elif slowCheat:
                d['rect'].move_ip(0, -1)

        for d in dusts[:]:
            if d['rect'].top > WINDOWHEIGHT:
                dusts.remove(d)

        # Draw the game world on the window.
        windowSurface.fill(BACKGROUNDCOLOR)

        if level == 2:
            windowSurface.fill(BLUE)

        # Draw the score top score, token, how many bombs, health and how much boss life
        drawText('Score: %s' % (score), font, windowSurface, 10, 0)
        drawText('Top Score: %s' % (topScore), font, windowSurface, 10, 40)
        drawText('Token: %s' % (token), font, windowSurface, 10, 80)
        drawText('Bombs: %s' % (bullet), font, windowSurface, 10, 120)
        drawText('Km: %s' % (kilometres), font, windowSurface, 10, 160)
        drawText('Health: %s' % (health), font, windowSurface, 10, 560)

        # Draw the player's rectangle
        windowSurface.blit(playerImage, playerRect)

        # Check the score to enter the next level

        # Draw each asteroid
        for a in asteroids:
            windowSurface.blit(a['surface'], a['rect'])

        for g in ghosts:
            windowSurface.blit(g['surface'], g['rect'])

        # Draw each token
        for t in tokens:
            windowSurface.blit(t['surface'], t['rect'])

        # Draw each bullet
        for b in bullets:
            windowSurface.blit(b['surface'], b['rect'])

        # Draw each health
        for h in healths:
            windowSurface.blit(h['surface'], h['rect'])

        # Draw each eyeball
        for e in eyeballs:
            windowSurface.blit(e['surface'], e['rect'])

        # Draw each arrow
        for r in arrows:
            windowSurface.blit(r['surface'], r['rect'])

        # Draw each dust
        for d in dusts:
            windowSurface.blit(d['surface'], d['rect'])

        pygame.display.update()

        # Check if any of the health have hit the player
        if playerHasHitHealth(playerRect, healths):
            health += 5
            if health < 100:
                health -= 0
            healths.remove(h)

        # Cheack if any of the eyeballs have hit the player
        if playerHasHitEyeball(playerRect, eyeballs):
            health -= 10
            if health == 0:
                if score > topScore:
                    topScore = score
                break

        # Check if any of the arrows have hit the player
        if playerHasHitArrow(playerRect, arrows):
            health -= 15
            if health == 0:
                if score > topScore:
                    topScore = score
                break

        # Check if any of the dusts have hit the player
        if playerHasHitDust(playerRect, dusts):
            health -= 5
            if health == 0:
                if score > topScore:
                    topScore = score
                break

        # Check if any of the bullets have hit asteroids.
        if bulletHasHitAsteroid(bulletRect, asteroids):
            score += 1000
            if True:
                for a in asteroids:
                    if a['rect'].colliderect:
                        asteroids.remove(a)

        # Check if any of the tokens have hit the player.
        if playerHasHitToken(playerRect, tokens):
            score += 10
            token += 1

        # Check if any of the baddies have hit the player.
        if playerHasHitBaddie(playerRect, asteroids):
                health -= 5
                if health == 0:
                    if score > topScore:
                        topScore = score # set new top score
                    break

        if playerHasHitGhost(playerRect, ghosts):
                health -= 10
                if health == 0:
                    if score > topScore:
                        topScore = score # set new top score
                    break

        if health == 0:
            if score > topScore:
                topScore = score
            break

        mainClock.tick(FPS)

    # Stop the game and show the "Game Over" screen.
    pygame.mixer.music.stop()
    gameOverSound.play()

    drawText('GAME OVER', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
    drawText('Press a key to play again.', font, windowSurface, (WINDOWWIDTH / 3) - 80, (WINDOWHEIGHT / 3) + 50)
    pygame.display.update()
    waitForPlayerToPressKey()

    gameOverSound.stop()

  • Ошибка runtime error program this application has requested the runtime
  • Ошибка sc 401 ricoh
  • Ошибка sc 332 ricoh
  • Ошибка sbc мерседес 211
  • Ошибка safe на духовке bosch как снять