Основы Python — изучаем базовые концепции языка
Эта статья рассчитана как на новичков в программировании, так и на программистов, которые уже владеют каким-либо языком, но хотят освоить еще и Python. Также она пригодится тем, кто хочет освежить свои знания.
Мы разберем самые основы Python. Начнем с типов данных, а ближе к концу статьи затронем приведение типов и срезы. Также мы познакомимся с некоторыми основными концепциями программирования.
Переменные
Переменные — это именованные участки памяти компьютера, в которых хранятся некоторые значения. Переменные могут хранить любой тип данных. Например, у нас есть пара значений — 10 и 20. Мы хотим их сложить и сохранить сумму для дальнейших операций. Давайте посмотрим, что нам нужно для этого сделать:
a = 10 # переменная a b = 20 # переменная b c = a + b # сумма а и b
Примечание редакции Pythonist: рекомендуем очень подробную статью об именах и присваивании значений — «Факты и мифы об именах и значениях в Python».
Типы данных
Тип данных — это атрибут, позволяющий компилятору понять, какие действия можно производить с переменной. В Python есть шесть основных типов данных — числа, строки, списки, кортежи, множества и словари.
Числа
В эту категорию попадают любые числа: целые, с плавающей точкой и комплексные. Чтобы узнать, к какому типу принадлежит число, мы можем воспользоваться функцией type() .
a = 5 print(type(a)) # b = 1+4j print(type(b)) # c = 4.5 print(type(c)) #
Посмотрите на вывод внимательно: класс int переменной a = 5 — предопределенный. Это значит, что его не нужно определять вручную, это уже сделано за нас. Целые числа (int) могут быть любой длины, но есть ограничение — объем вашей памяти. Числа с плавающей точкой (float) имеют ограничение точности — 15 знаков после точки. Если попытаетесь ввести больше — лишние будут отброшены.
a = 1.12345678912345678912 print(a) # 1.1234567891234568
Строки
Строка (str) — это набор символов Юникод. Для определения строки мы используем одинарные или двойные кавычки.
Пример:
a = ‘c’ print(type(a)) # b = «hello» print(type(b)) # c = ‘hello python’ print(type(c)) #
Списки
Списки (list) — упорядоченная последовательность элементов. Это один из самых часто используемых типов данных в Python. Списки очень похожи на массивы, но в списках мы можем хранить элементы разного типа.
Списки изменяемы. Это означает, что мы можем изменить любое их значение при помощи индексов.
lst = [1,2,3,4,5.3] print(type(lst)) # lst = [1,'hello',3,4,5.3,'pythonist'] print(type(lst)) # lst = ['hello','pythonist'] print(type(lst)) # lst = [1,'hello',3,4,5.3,'pythonist'] print(lst[0]) # 1 lst = [1,'hello',3,4,5.3,'pythonist'] lst[0]=10 print(lst) # [10, 'hello', 3, 4, 5.3, 'pythonist']
Кортежи
Кортежи (tuple) — это также упорядоченные наборы элементов. От списков их отличает одно: кортежи неизменяемы. То есть, после объявления кортежа изменить его элементы мы не сможем.
Кортежи намного быстрее списков. Для получения доступа к элементам кортежа мы можем использовать индексы и срезы.
t = (1,2,3) print(type(t)) # t = (1,'hello',3.2) print(type(t)) # t = (1,'hello',3.2) print(t[0]) # 1
Множества
Множество (set) — неупорядоченный набор элементов. Определяется множество с помощью фигурных скобок — <> . Все элементы разделяются запятыми.
В множестве не может быть дубликатов. Это значит, что порой их можно использовать для того, чтобы избавиться от повторяющихся элементов списке. С множествами мы можем производить самые разные операции, например, объединение (union), пересечение (intersection).
Обратите внимание: получить доступ к элементу множества по индексу невозможно — они не упорядочены!
a = print(type(a)) # a = print(a[0]) # TypeError: ‘set’ object is not subscriptable a = b = print(a.union(b)) # a = b = print(a.intersection(b)) #
Словари
Словарь (dict) — набор элементов, в котором элементы хранятся в виде пар ключ-значение. Такая система оптимизирована под поиск значений, из-за чего словари часто используют для хранения огромных массивов данных. Определяются словари с помощью фигурных скобок в следующем виде — . Пары элементов отделяются запятыми.
dict = print(dict) # print(dict.keys()) # dict_keys(['name', 'number', 'address']) print(dict.values()) # dict_values(['ivan', '99029922', 'Moskva'])
Операторы
Операторы нужны для проведения операций между двумя элементами. Например, в a + b оператором является + . Он указывает компилятору на то, что нужно сложить две переменные.
В Python есть 7 типов операторов:
- Арифметические операторы: *, +, /, **, %, —
- Операторы присваивания: =, +=, =+, -=, -=, !=
- Операторы сравнения: , !, ==, ==
- Логические операторы: and, or, not
- Операторы идентичности: is, is not
- Операторы членства: in, not in
- Битовые операторы: &, ^, ~, <>
Индексы
Индексы используются для получения доступа к элементам коллекций (например, строк или списков). В Python есть два типа индексов — положительные и отрицательные. Положительные начинаются с 0, а отрицательные — с последнего элемента коллекции.
Пример:
# Положительные индексы a = 56 print(a[0]) # TypeError: 'int' object is not subscriptable b = 'python' print(b[0]) # 'p' c = 3.14 print(c[0]) # TypeError: 'float' object is not subscriptable d = [1,2,'hello',4] print(d[2]) # hello print(d[2][1]) # e print(d[2][4]) # o d = [1,2,'hello',4] print(d[-1]) # 4 print(d[2][-4]) # e print(d[2][-1]) # o str = "hello python" print(str[-3]) # h
Срезы
Срезы используются для получения доступа к последовательности элементов коллекции. Внимание: верхняя граница всегда отбрасывается. То есть, a[0:3] — это элементы с индексами 0, 1 и 2, а вот элемент с индексом 3 в срез уже не войдет.
b = 'python' print(b[0:2]) # py d = [1,2,'hello',4] print(d[0:2]) # [1,2] print(d[2][1:4]) # 'ell' print(d[2][1:-1]) # 'ell'
Функционал среза можно расширить, добавив третий параметр — шаг.
lst = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] print(lst[0:20:2]) # выводим все нечетные числа в промежутке от 0 до 20 print(lst[1:20:2]) # выводим все четные числа в промежутке от 0 до 20 strr = "hello python" print(strr[0:8:4]) # ho
Приведение типов
Приведение типов позволяет сконвертировать один тип данных в другой. Это может оказаться полезным во многих ситуациях.
a = 10 print(type(a)) # a = str(a) print(type(a)) # a = float(a) print(type(a)) # a = list(str(a)) print(type(a)) # print(a) # ['1', '0', '.', '0'] lst = [1, 2, 3, 4, 5, 1, 2] lst = set(lst) print(type(lst)) # print(lst) # lst = tuple(lst) print(type(lst)) # print(lst) # (1, 2, 3, 4, 5)
Выводы
В этой статье мы разобрали основы Python — самый необходимый минимум. Обратите внимание, что все в статье — обязательно к изучению, если вы новичок.
Solving Python Error: ‘float’ Object Is Not Subscriptable
Encountering a ‘float’ object is not subscriptable error in Python can be a stumbling block for many developers, from beginners to experienced ones. This comprehensive guide aims to demystify this error, discussing its causes, how to resolve it, and best practices to avoid it in the future. Whether you’re debugging your code or refining your Python skills, understanding this error is crucial for smoother coding experiences.
Key Highlights
- Understanding the ‘float’ object is not subscriptable error in Python
- Common causes and scenarios leading to this error
- Step-by-step solutions to resolve the error
- Best practices to prevent the error in future projects
- Real-world examples and tips for effective debugging
Understanding Python’s ‘float’ Object Is Not Subscriptable Error
Grasping the nuances of Python’s error messages is essential for both new and seasoned developers. The ‘float’ object is not subscriptable error is one such message that often confounds programmers. This section aims to demystify this error, providing a foundational understanding of subscriptability in Python, focusing specifically on why floats fall outside this category. With examples and practical insights, we’ll explore the nature of this error and its implications for your code.
Decoding Subscriptability in Python
In Python, subscriptability refers to an object’s ability to support indexing or slicing operations, typically through square brackets ( [] ). For instance, lists, tuples, and dictionaries are subscriptable, allowing you to access elements using an index or key.
A common misconception is that any object can be subscripted, which is not the case. Only objects that implement the __getitem__ method are considered subscriptable. This method is what Python internally calls when you use the square bracket notation.
Consider the following example:
my_list = [1, 2, 3] print(my_list[0]) # Outputs: 1
Here, my_list is a list object, which is inherently subscriptable, allowing you to access its first element using my_list[0] .
The Nature of Floats: Why They’re Not Subscriptable
Floats in Python represent real numbers and, unlike lists or dictionaries, do not contain a sequence of elements. Since floats are single values without components like items in a list or key-value pairs in a dictionary, they do not support the __getitem__ method, rendering them non-subscriptable.
Attempting to subscript a float, as in the misguided endeavor 3.14[0] , results in the unequivocal error: ‘float’ object is not subscriptable. This error signifies a fundamental misunderstanding of a float’s nature and its capabilities within Python.
Here’s an illustrative example:
pi = 3.14159 try: print(pi[0]) except TypeError as e: print(e) # This will print: 'float' object is not subscriptable
This snippet highlights the error’s root cause: treating a non-sequence type (float) as if it were a sequence type, which is a common pitfall for many developers.
Understanding Common Causes of ‘float’ Object Not Subscriptable Error in Python
In the realm of Python programming, encountering errors is a part of the development process. The ‘float’ object is not subscriptable error often perplexes beginners and experienced developers alike. This section delves into the typical scenarios and coding patterns leading to this error, aiming to equip you with the knowledge to identify and resolve it efficiently.
Decoding Misuse of Indexing with Float Objects
Understanding the Indexing Misuse
When Python programmers refer to objects being subscriptable, they mean the object can be accessed via indexing or slicing. Lists, tuples, and strings are common examples. However, a float object, representing floating-point numbers, does not support this because it represents a single value, not a sequence of items.
Examples of incorrect indexing with float objects:
- Attempting to index a float directly: python my_float = 3.14 print(my_float[0]) # This will raise an error
- Misinterpretation after arithmetic operations: Sometimes, operations result in a float, which a programmer might unknowingly try to index: python result = 10 / 2 # This results in a float, 5.0 try: print(result[2]) # Error because ‘result’ is a float except TypeError as e: print(f»Error: «)
Addressing this misconception by recognizing that floats are singular values and not iterable sequences is crucial for avoiding this error.
Navigating Type Conversion Errors Leading to Not Subscriptable Issues
Unintentional Type Conversions: A Pitfall
Unintended type conversion to float can be a sneaky source of the ‘float’ object is not subscriptable error. This often occurs when performing operations that inherently produce floating-point numbers, or when parsing data without explicit type checking.
How unintentional type conversions happen:
- Automatic conversion during arithmetic operations: Python automatically converts integers to floats in certain operations, leading to unexpected float types: python result = 10 / 4 # Results in a float, 2.5, not an integer
- Parsing numeric strings into floats instead of integers: When using functions like float() to parse numbers, ensure you’re using the correct type for your use case: python num = float(«3″) # Intentionally or unintentionally creating a float if isinstance(num, float): print(f» is a float, be careful with indexing!»)
Preventing such errors involves explicit type checking and being mindful of Python’s type conversion rules. Recognizing when a float is created and understanding its non-subscriptable nature are key steps in avoiding this common pitfall.
Solving Python Error: ‘float’ Object Is Not Subscriptable
Encountering a ‘float’ object is not subscriptable error can be a stumbling block in your Python journey. This section offers effective solutions to overcome this common issue, ensuring your coding process is smoother and more efficient. By understanding the root causes and applying the right fixes, you can quickly move past this hurdle and continue developing your Python projects with confidence.
Correcting Indexing Misuse
Understanding the proper use of indexing is crucial in Python, as it prevents common errors when dealing with various data types. Indexing is primarily used with lists, tuples, or dictionaries, allowing you to access specific elements within these collections. However, attempting to use indexing on a float leads to the ‘float’ object is not subscriptable error.
For example, consider the following incorrect use of indexing with a float:
my_float = 12.34 print(my_float[0]) # This will raise an error
To correct this misuse, ensure you’re applying indexing to the appropriate data types. If you need to manipulate a float in a way that resembles indexing, consider converting it into a string or a different suitable format first:
my_float = 12.34 my_str = str(my_float) print(my_str[0]) # Outputs '1'
By adjusting your approach to indexing, you can avoid this error and work with floats effectively in Python.
Ensuring Proper Type Conversion
In Python, type conversion plays a pivotal role in preventing the ‘float’ object is not subscriptable error. Unintentional type conversions can lead to this issue, especially when you expect a list or a tuple but end up with a float. Being vigilant about the data types your variables hold is key to avoiding such pitfalls.
Consider an example where a variable’s type is inadvertently changed:
result = 10 / 5 # This results in a float, not an integer # An attempt to index 'result' below will fail # print(result[0]) # Uncommenting this will raise an error
To ensure proper type conversion, explicitly convert your data to the intended type before performing operations that might lead to errors:
result = 10 / 5 result_list = [result] # Convert to a list if indexing is needed later print(result_list[0]) # This will work as expected
By consciously managing type conversions, especially when dealing with operations that might result in floats, you can prevent errors and maintain the integrity of your code.
Preventing the ‘float’ Object Is Not Subscriptable Error in Python
In the realm of Python programming, encountering errors is a common part of the development process. However, understanding and implementing best practices can significantly reduce these occurrences, especially with the ‘float’ object is not subscriptable error. This section delves into strategies and coding habits aimed at preempting such errors, ensuring smoother coding experiences.
Leveraging Type Checking to Avoid Incompatibilities
Type checking is an essential practice in Python programming that allows developers to ensure variables are of the expected data type before performing operations on them. This proactive approach can significantly reduce runtime errors, including the ‘float’ object is not subscriptable error.
For example, before indexing a variable, confirming its type can prevent inadvertent operations on a float:
# Assuming 'data' could be of any data type if isinstance(data, list): print(data[0]) else: print('Data is not a list')
This simple check ensures that indexing operations are only performed on data types that support them, such as lists or tuples, thereby averting potential errors. Utilizing isinstance() alongside custom functions for more complex type validations can further enhance this safeguarding mechanism, making your code more robust and error-resistant.
Harnessing Linters and IDE Tools for Early Error Detection
In the quest to minimize programming errors, linters and Integrated Development Environments (IDEs) emerge as indispensable allies. These tools scrutinize code for potential issues during the development phase, long before runtime.
For instance, PyLint is a popular Python linter that can flag instances where a float might be incorrectly treated as subscriptable. Similarly, IDEs like PyCharm or Visual Studio Code offer real-time feedback and suggestions, highlighting problematic code segments.
Integrating these tools into your development workflow allows for an earlier and thus more manageable resolution of errors. Additionally, they often provide suggestions for code optimization and adherence to Pythonic conventions, further enhancing code quality and maintainability.
Configuring your IDE to use specific linters and setting up custom rules tailored to your project’s needs can make this process even more effective, ensuring a smoother and more error-free coding experience. Here’s a resource to get started with PyLint: PyLint User Guide.
Real-world Examples and Debugging Tips for Python Developers
In the realm of Python development, encountering errors is a rite of passage that offers invaluable learning opportunities. Among these, the ‘float’ object is not subscriptable error often perplexes newcomers and seasoned coders alike. This section aims to demystify this error through real-world examples and equip you with practical debugging tips to efficiently resolve it.
Dissecting Code Snippets to Understand Common Mistakes
Real-world scenarios often illuminate the path to understanding complex errors. Consider the following snippet:
values = 3.142 print(values[2])
At first glance, one might expect to access the third character of a string, but values is a float, triggering a ‘float object is not subscriptable’ error. This mistake typically arises from:
- Misunderstanding variable types: Assuming values is a list or string when it’s a float.
- Overlooking prior transformations: Perhaps values was once a list or string earlier in the code.
Understanding that floats cannot be indexed like lists or strings is crucial. They represent numerical values, not collections of items.
For an in-depth exploration of Python types, the Python official documentation is an excellent resource.
Debugging Strategies to Swiftly Rectify Errors
Efficient debugging is an art that transforms frustrating errors into lessons in proficiency. When faced with a ‘float’ object is not subscriptable error, consider the following debugging strategies:
- Review variable assignments: Trace back to where the problematic variable was first assigned or modified. Ensure its type aligns with your current operation.
- Utilize Python’s built-in type() function: Before the line causing the error, add print(type(variable_name)) to confirm the variable’s type.
- Leverage IDEs and linters: Tools like PyCharm and Pylint can preemptively identify type mismatches.
- Incremental testing: Regularly run your code after each significant modification to pinpoint errors more accurately.
Adopting a methodical approach to debugging not only resolves current issues but also enhances your problem-solving skills for future challenges.
Conclusion
The ‘float’ object is not subscriptable error in Python is a common yet easily avoidable mistake with a proper understanding of Python’s data types and careful coding practices. By learning from the solutions and best practices outlined in this guide, developers can significantly reduce the occurrence of this error and enhance their problem-solving skills in Python programming.
FAQ
Q: What does the error ‘float’ object is not subscriptable mean in Python?
A: This error means that you’re attempting to access an index or key on a float value, which is not possible in Python. Floats are not collections like lists or dictionaries, so they can’t be subscripted.
Q: Can you give an example of a scenario that leads to the ‘float’ object is not subscriptable error?
A: A common scenario is when a variable expected to be a list or a dictionary is accidentally assigned a float value. For instance, attempting to access my_var[0] when my_var is a float will trigger this error.
Q: How can I solve the ‘float’ object is not subscriptable error?
A: Identify the variable causing the error and verify its data type. Ensure that any indexing operations are performed on collections like lists or dictionaries, not on floats. If necessary, correct the data type or the operation.
Q: What are some best practices to avoid the ‘float’ object is not subscriptable error in the future?
A: Use type checking to ensure variables are of the expected data type before performing operations. Additionally, leveraging linters and IDE tools can help catch these errors early in the development process.
Q: Is the ‘float’ object is not subscriptable error common, and how critical is it to fix?
A: It’s a common error, especially among beginners, but easy to fix once understood. While not critical in terms of security, it’s crucial for the correct execution of your program and data manipulation.
- Introduction
- Key Highlights
- Understanding Python’s ‘float’ Object Is Not Subscriptable Error
- Understanding Common Causes of ‘float’ Object Not Subscriptable Error in Python
- Solving Python Error: ‘float’ Object Is Not Subscriptable
- Preventing the ‘float’ Object Is Not Subscriptable Error in Python
- Real-world Examples and Debugging Tips for Python Developers
- Conclusion
- FAQ
From the founder of SQLPad
Nervous about your SQL Interview? Anxiety ends here.
Get Your Dream Job Offer Today
SQLPad transforms your data career by boosting your productivity tenfold as a data scientist, data engineer, or data analyst. Master essential skills like R, SQL and Python, or confidently ace your job interviews. Join SQLPad Free today!
Python typeerror: ‘float’ object is not subscriptable Solution
Values inside a float cannot be accessed using indexing syntax. This means that you cannot retrieve an individual number from a float. Otherwise, you’ll encounter a “typeerror: ‘float’ object is not subscriptable” in your program.
In this guide, we talk about what this error means and why you may see it. We walk through two example scenarios so you can figure out how to fix this problem.
Find your bootcamp match
Select Your Interest
Your experience
Time to start
GET MATCHED
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
typeerror: ‘float’ object is not subscriptable
You can retrieve individual items from an iterable object. For instance, you can get one item from a Python list, or one item from a dictionary. This is because iterable objects contain a list of objects. These objects are accessed using indexing.
You cannot retrieve a particular value from inside a float. Floating-point numbers, like integers, are not iterable objects.
The “typeerror: ‘float’ object is not subscriptable” is commonly caused by:
- Trying to access a particular value from a floating-point number
- Using the wrong syntax to replace multiple items in a list
Let’s walk through each of these scenarios.
Scenario #1: Accessing an Item from a Float
We’re building a program that checks if a ticket holder in a raffle is a winner. If a user’s ticket number starts with 1 and ends in 7, they are a winner.
Let’s start by asking a user to insert a ticket number that should be checked:
ticket_number = float(input("Enter a ticket number: "))
We’ve converted this value to a float because it is a number.
Next, we use indexing syntax to retrieve the first and last numbers on a ticket:
first = ticket_number[0] last = ticket_number[-1]
The first item in our ticket number is at the index position 0; the last item is at the index position -1. Next, we use an “if” statement to check if a user is a winner:
if first == "1" and last == "7": print("You are a winner!") else: print("You are not a winner.")
If the value of “first” is equal to “1” and the value of “last” is equal to “7”, our “if” statement will run and inform a user they have won. Otherwise, our “else” statement will run, which will inform a user that they are not a winner.
Let’s run our code:
Enter a ticket number: 23 Traceback (most recent call last): File "main.py", line 3, in first = ticket_number[0] TypeError: 'float' object is not subscriptable
Our code does not work. This is because ticket numbers are stored as a float. We cannot use indexing syntax to retrieve individual values from a float.
To solve this error, we remove the float() conversion from our first line of code:
ticket_number = input("Enter a ticket number: ")
The input() method returns a string. We can manipulate a string using indexing, unlike a floating-point value. Let’s run our code again:
Enter a ticket number: 23 You are not a winner.
Our code appears to work successfully. Let’s test our code on a winning ticket:
Enter a ticket number: 117 You are a winner!
Our code works whether a ticket is a winner or not.
Scenario #2: Replacing Multiple Items
List slicing allows you to replace multiple items in a list. Slicing is where you specify a list of items in an iterable that you want to access or change.
Let’s build a program that resets the prices of all products in a list of donuts. We must build this program because a store is doing a “Donut Day” promotion where every donut is a particular price. We start by asking the user for the new price of donuts:
price = input("Enter the price of the donuts: ")
Next, we define a list of the current prices of donuts that we must change:
donuts = [2.50, 2.75, 1.80, 1.75, 2.60]
Now that we have these values, we’re ready to change our list. We can do this using indexing:
donuts[0][1][2][3][4] = [float(price)] * 5 print(donuts)
This code resets the values in the “donuts” list at the index positions 0, 1, 2, 3, and 4 to the value of “price”. We’ve converted the value of “price” to a floating point number.
We’ve then enclosed the price in square brackets and multiplied it by five. This creates a list of values which we can assign to our “donuts” list.
Finally, we print the new list of prices to the console. Let’s run our code:
Enter the price of the donuts: 2.50 Traceback (most recent call last): File "main.py", line 3, in donuts[0][1][2][3][4] = [float(price)] * 5 TypeError: 'float' object is not subscriptable
When our code tries to change the values in the “donuts” list, an error is returned. Our code tries to retrieve the item at the index position [0][1][2][3][4]. This does not exist in our list because our list only contains floats. To solve this error, use slicing syntax to update our list.
donuts[0:5] = [float(price)] * 5
This code retrieves all the items in our list from the range of 0 to 5 (exclusive of 5). Then, we assign each value the value of “price”. Let’s try our new code:
«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
Find Your Bootcamp Match
Enter the price of the donuts: 2.50 [2.5, 2.5, 2.5, 2.5, 2.5]
Our code successfully replaces all the items in our list.
Conclusion
The “typeerror: ‘float’ object is not subscriptable” error occurs when you try to access items from a floating point number as if the number is indexed.
To solve this error, make sure you only use indexing or slicing syntax on a list of iterable objects. If you are trying to change multiple values in a list, make sure you use slicing to do so instead of specifying a list of index numbers whose values you want to change.
Now you’re ready to solve this error in your own code.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.
What’s Next?
Want to take action?
Get matched with top bootcamps
Want to dive deeper?
Ask a question to our community
Want to explore tech careers?
Take our careers quiz
About the Author
Technical Content Manager at Career Karma
James Gallagher is a self-taught programmer and the technical content manager at Career Karma. He has experience in range of programming languages and extensive expertise in Python, HTML, CSS, and JavaScript. James has written hundreds of programming tuto. read more about the author
Share This
Aug 25, 2020 —>
Leave a Reply Cancel reply
Apply to top tech training programs in one click
Get Matched
© 2024 Career Karma
Best Coding Bootcamps
Best Online Bootcamps
Best Web Design Bootcamps
Best Data Science Bootcamps
Best Data Analytics Bootcamps
Best Cyber Security Bootcamps
Best ISA Bootcamps 2020
Comparisons
Flatiron School vs Fullstack Academy
Hack Reactor vs App Academy
Fullstack Academy vs Hack Reactor
Thinkful vs General Assembly
Flatiron School vs Thinkful
General Assembly vs Flatiron School
App Academy vs Lambda School
General Assembly vs Hack Reactor
Springboard vs Thinkful
San Francisco Bootcamps
New York Bootcamps
Los Angeles Bootcamps
Chicago Bootcamps
Seattle Bootcamps
Atlanta Bootcamps
Austin Bootcamps
Coding Temple
Flatiron School
General Assembly
Springboard
Hack Reactor
App Academy
Software Engineering
UX/UI Design
Data Science
Web Development
Mobile Development
Cybersecurity
Product Management
JavaScript
At Career Karma, our mission is to empower users to make confident decisions by providing a trustworthy and free directory of bootcamps and career resources. We believe in transparency and want to ensure that our users are aware of how we generate revenue to support our platform.
Career Karma recieves compensation from our bootcamp partners who are thoroughly vetted before being featured on our website. This commission is reinvested into growing the community to provide coaching at zero cost to their members.
It is important to note that our partnership agreements have no influence on our reviews, recommendations, or the rankings of the programs and services we feature. We remain committed to delivering objective and unbiased information to our users.
In our bootcamp directory, reviews are purely user-generated, based on the experiences and feedback shared by individuals who have attended the bootcamps. We believe that user-generated reviews offer valuable insights and diverse perspectives, helping our users make informed decisions about their educational and career journeys.
Find the right bootcamp for you
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
Find a top-rated training program
Не извлекается значение из массива. Нужно исправить ошибку
Надо построить график с помощью черепашки и взять по оси У значения из массива.
У меня есть массив data, из которого извлекается строка N. В итоге надо построить график, используя значения этой троки.
1 2 3 4 5 6 7
turtle.down() x=1 y=float(N[1]) coords=str(x)+","+str(y) turtle.goto(x,y) turtle.write(coords) turtle.up()
Текст ошибки:
Traceback (most recent call last):
File «E:\Математические пакеты\6 лабораторная работа\1.py», line 54, in
y=float(N[1])
TypeError: ‘int’ object is not subscriptable
Лучшие ответы ( 1 )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Вылетает программа после написания массива. Не знаю, где допустил ошибку. Нужно исправить код. Заранее спасибо!
Ввести целочисленный массив состоящий из 17 элементов. Заменить элементы кратные трем на сумму.
Нужно исправить ошибку «Индекс находился вне границ массива»
Выдает ошибку "Сообщение = Индекс находился вне границ массива.", не знаю как исправить. Нужно.
Нужно исправить код, выдаёт ошибку и не запускает форму, нужно привязать базу данных Access
Мне нужно вставить ссылку на базу данных Access, но я не пойму, он ее не видит что ли, либо я не.
Автоматизируй это!
7107 / 4611 / 1215
Регистрация: 30.03.2015
Сообщений: 13,243
Записей в блоге: 29
судя по ошибке N -не массив а целое число
Регистрация: 23.10.2017
Сообщений: 29
Да, N -не массив. Массив здесь data, а N — это номер строки массива:
1 2 3 4 5 6 7 8 9 10 11
import turtle from itertools import* data = [] N = "" N = input('Введите номер строки N=') N = int(N) with open("massiv.txt") as file: for line in file: data.append([float(x)for x in line.split()]) print(data[N])
Добавлено через 3 минуты
В другом варианте тоже выдаёт эту ошибку:
y=float(data[N[1]]) TypeError: 'int' object is not subscriptable
что делать?
Автоматизируй это!
7107 / 4611 / 1215
Регистрация: 30.03.2015
Сообщений: 13,243
Записей в блоге: 29
Nastya2599, ау, прочти еще раз — N это не массив, тогда что означает N[1]. Целые числа не поддерживают индексации, говоря просто к ним не применим синтаксис [1]
он будет выдавать тебе эту ошибку пока до тебя не дойдет вышенаписанное
вот тут y=float(data[N[1]]) нужно или y=float(data[N]) или возможно какое то еще число вместо N
Регистрация: 23.10.2017
Сообщений: 29
Welemir1, если я ставлю простое число, то всё нормально выводится и строится, но вот с «y=float(data[N])» не работает. Там тоже выдаёт ошибку, но другую:
y=float(data[N]) TypeError: float() argument must be a string or a number, not 'list'
Добавлено через 1 минуту
Вот весь код программы, если надо:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
import turtle from itertools import* data = [] N = "" N = input('Введите номер строки N=') N = int(N) with open("massiv.txt") as file: for line in file: data.append([float(x)for x in line.split()]) print(data[N]) # turtle.reset() turtle.tracer(0) turtle.color('#800000') # turtle.write('0,0') # x=0 y=-100 coords=str(x)+","+str(y) turtle.goto(x,y) turtle.write(coords) # turtle.down() x=0 y=100 coords=str(x)+","+str(y) turtle.goto(x,y) turtle.write(coords) # turtle.up() dx = 1 x=-100 y=0 coords=str(x)+","+str(y) turtle.goto(x,y) turtle.write(coords) # turtle.down() x=100 y=0 coords=str(x)+","+str(y) turtle.goto(x,y) turtle.write(coords) # turtle.up() # turtle.down() x=1 y=float(data[N]) coords=str(x)+","+str(y) turtle.goto(x,y) turtle.write(coords) turtle.up() # turtle.mainloop()