Найти - Пользователи
Полная версия: Вопросы от новичков.
Начало » Python для новичков » Вопросы от новичков.
1 2 3 4 5 6 7 8 9 None 28 29 30 31
PEHDOM
О боже, пора уже гдето закрепить(может в названии ветки?), что код нужно заключать в теги
[code python]
Тут пишем код
[/code]
citizen404
Доброго времени суток, форумчане!
Сейчас изучаю операции над множествами по книге Марка Саммерфилда и в процессе столкнулся с такой проблемкой, что фактический результат выполнения кода интерпретатором отличается от ожидаемого. Не пойму, в чем дело. Подскажите, где я накосячил.


 set_1 = {'pecan'}
set_2 = {'pie'}
print(type(set_1))
print(type(set_2))
print('Исходное множество set_1: {0}'.format(set_1))
print('Исходное множество set_2: {0}'.format(set_2))
union = set_1 | set_2  # Объединение
intersection = set_1 & set_2 # Пересечение
difference = set_1 - set_2  # Разность
symmetric_difference = set_1 ^ set_2   # Строгая дизъюнкция (исключающее ИЛИ)
print('Объединение: ', union) 
print('Пересечение: ', intersection) 
print('Разность: ', difference) 
print('Исключающее ИЛИ: ', symmetric_difference)
print(set_1.difference(set_2))

Результат работы интерпретатора и то, как должно быть
krok64
Попробуй так
 set_1 = set('pecan')
set_2 = set('pie')
citizen404
krok64
Попробуй так

Вот я алень !!! На такой элементарщине споткнулся. Спасибо, впредь буду внимательнее.
И главное прочел же, что с помощью {} нельзя создать пустое множество, т.к. эти скобки зарезервированы для словарей. Но, я вроде бы и не пустое создал…Странно немного.
FishHook
citizen404
Дело не в пустом множестве, а в том, что если вам нужно множество, состоящее из одного СЛОВА, вы делаете так
 {"СЛОВО"}
но вам нужно множество БУКВ слова, поэтому вам нужно передать слово в функцию set(), которая создает множество из других структур.
 set("abc")  == set(["a", "b", "c"])
Lamptop
Всем привет!
 import telebot
TOKEN = 'пример токена'
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start'])
def start(message):
    sent = bot.send_message(message.chat.id, 'Привет, как тебя зовут?')
    bot.register_next_step_handler(sent, hello)
def hello(message):
    bot.send_message(
        message.chat.id,
        'Привет, {name}. Как ты?'.format(name=message.text)
bot.polling()


Выдает ошибку SyntaxError: multiple statements found while compiling a single statement. Что делать?

P.S. перед import нету отступа.
FishHook
     bot.send_message(
        message.chat.id,
        'Привет, {name}. Как ты?'.format(name=message.text)

не хватает закрывающей скобки
ПС. Юзайте современные IDE и такого тупняка случатся не будет
Lamptop
Все та же ошибка. SyntaxError: multiple statements found while compiling a single statement. После import telebot красная полоса в IDLE
FishHook
Lamptop
Дайте догадаюсь. Вы взяли чей-то код, скопировали его и вставили в IDLE?

Тут только один совет может быть - не используйте IDLE, это не настоящая ИДЕ. На вопрос “а что же использовать?” - идите в гугл.
Ivanchgeek
Попытался установить модуль, вылез вот-такой кульверштукас. Заранее спасибо за помощь

sudo pip install pyaudio
sudo: unable to resolve host hatifnat
password for ivan:
The directory ‘/home/ivan/.cache/pip/http’ or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory ‘/home/ivan/.cache/pip’ or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pyaudio
Downloading PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
Running setup.py install for pyaudio … error
Complete output from command /usr/bin/python -u -c “import setuptools, tokenize;__file__='/tmp/pip-build-nqaQ2r/pyaudio/setup.py';f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace('\r\n', ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))” install –record /tmp/pip-k_99RO-record/install-record.txt –single-version-externally-managed –compile:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
copying src/pyaudio.py -> build/lib.linux-x86_64-2.7
running build_ext
building ‘_portaudio’ extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/src
x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/include/python2.7 -c src/_portaudiomodule.c -o build/temp.linux-x86_64-2.7/src/_portaudiomodule.o
src/_portaudiomodule.c:29:23: fatal error: portaudio.h: No such file or directory
compilation terminated.
error: command ‘x86_64-linux-gnu-gcc’ failed with exit status 1

—————————————-
Command “/usr/bin/python -u -c ”import setuptools, tokenize;__file__='/tmp/pip-build-nqaQ2r/pyaudio/setup.py';f=getattr(tokenize, ‘open’, open)(__file__);code=f.read().replace('\r\n', ‘\n’);f.close();exec(compile(code, __file__, ‘exec’))“ install –record /tmp/pip-k_99RO-record/install-record.txt –single-version-externally-managed –compile” failed with error code 1 in /tmp/pip-build-nqaQ2r/pyaudio/
ivan@hatifnat:~$
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB