Python Basics: Variables, Operators & Conditionals

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

Questions and Answers

Qual é a maneira correta de declarar uma variável em Python?

  • #nome = "João"
  • var nome = "João"
  • string nome = "João"
  • nome = "João" (correct)
  • define nome = "João"

Qual tipo de dado é usado para armazenar números inteiros em Python?

  • integer
  • num
  • float
  • decimal
  • int (correct)

Considere o código: x = 5.0. Qual é o tipo da variável x?

  • float (correct)
  • str
  • decimal
  • int
  • number

Em Python, qual é o resultado da expressão type("42")?

<p>str (A)</p> Signup and view all the answers

Como transformar o número inteiro 10 em um número decimal (float)?

<p>float(10) (C)</p> Signup and view all the answers

Qual é o resultado da expressão 10 % 3 em Python?

<p>1 (B)</p> Signup and view all the answers

Qual operador é usado para calcular o resto da divisão em Python?

<p>% (A)</p> Signup and view all the answers

O que o operador ** faz em Python?

<p>Calcula a potência (B)</p> Signup and view all the answers

Qual é o resultado da expressão 2 + 3 * 4 em Python?

<p>14 (C)</p> Signup and view all the answers

Qual é o resultado da expressão "Python" + " " + "é legal"?

<p>&quot;Python é legal&quot; (C)</p> Signup and view all the answers

Qual palavra-chave é usada para definir uma condição em Python?

<p>if (C)</p> Signup and view all the answers

O que representa o símbolo == em Python?

<p>Igualdade (D)</p> Signup and view all the answers

Qual a estrutura correta de um bloco condicional em Python?

<p>if condição: comandos (E)</p> Signup and view all the answers

Como escrever um bloco if-else em Python?

<p>if condição: comandos else: comandos (D)</p> Signup and view all the answers

O que é um operador lógico?

<p>Operador que combina condições booleanas (B)</p> Signup and view all the answers

Qual estrutura é usada para repetir um código um número específico de vezes em Python?

<p>for (C)</p> Signup and view all the answers

Como escrever um loop que percorre os números de 1 a 10 em Python?

<p>for i in range(1, 11): (D)</p> Signup and view all the answers

O que o comando break faz dentro de um loop?

<p>Encerra o loop imediatamente (C)</p> Signup and view all the answers

Qual é a diferença entre while e for em Python?

<p><code>for</code> é usado para percorrer sequências, enquanto <code>while</code> executa enquanto uma condição é verdadeira (A)</p> Signup and view all the answers

O que faz o comando continue em um loop?

<p>Pula para a próxima iteração (D)</p> Signup and view all the answers

Como criar uma lista vazia em Python?

<p>Tanto a quanto b estão corretas (D)</p> Signup and view all the answers

Como acessar o terceiro elemento de uma lista chamada frutas?

<p>frutas[2] (D)</p> Signup and view all the answers

Qual método é usado para adicionar um elemento ao final de uma lista?

<p>append() (C)</p> Signup and view all the answers

Como obter o comprimento de uma lista chamada alunos?

<p>len(alunos) (E)</p> Signup and view all the answers

Qual o resultado de [1, 2, 3] + [4, 5]?

<p>[1, 2, 3, 4, 5] (C)</p> Signup and view all the answers

Como definir uma função em Python?

<p>def minhaFuncao(): (C)</p> Signup and view all the answers

O que é um parâmetro de função?

<p>É um valor enviado para a função quando ela é chamada (C)</p> Signup and view all the answers

Como chamar uma função chamada calcular que recebe dois argumentos?

<p>calcular(arg1, arg2) (A)</p> Signup and view all the answers

Qual palavra-chave é usada para retornar um valor de uma função?

<p>return (D)</p> Signup and view all the answers

O que acontece se uma função não tiver a instrução return?

<p>A função retorna None (D)</p> Signup and view all the answers

Como acessar o primeiro caractere de uma string chamada texto?

<p>texto[0] (E)</p> Signup and view all the answers

Qual método é usado para converter uma string para letras maiúsculas?

<p>upper() (C)</p> Signup and view all the answers

O que faz o método split() em uma string?

<p>Divide a string em uma lista de substrings (D)</p> Signup and view all the answers

Como verificar se uma string contém uma determinada substring?

<p>&quot;string&quot; in &quot;substring&quot; (C)</p> Signup and view all the answers

O que é uma f-string em Python?

<p>Uma string que permite incluir expressões Python dentro de chaves {} (C)</p> Signup and view all the answers

Qual função é usada para obter entrada do usuário em Python?

<p>input() (E)</p> Signup and view all the answers

Como exibir uma mensagem na tela em Python?

<p>print(&quot;Mensagem&quot;) (E)</p> Signup and view all the answers

Qual a maneira correta de formatar a saída para exibir o valor da variável idade?

<p>Todas as alternativas acima estão corretas (C)</p> Signup and view all the answers

Como ler um número inteiro da entrada do usuário?

<p>int(input()) (E)</p> Signup and view all the answers

O que acontece se você usar input() sem converter o resultado?

<p>O programa sempre retorna uma string (C)</p> Signup and view all the answers

Como criar um dicionário vazio em Python?

<p>Tanto a quanto b estão corretas (D)</p> Signup and view all the answers

Como acessar o valor associado à chave "nome" em um dicionário chamado pessoa?

<p>Tanto a quanto c estão corretas (B)</p> Signup and view all the answers

Qual método é usado para adicionar um novo par chave-valor a um dicionário?

<p>dicionario[chave] = valor (B)</p> Signup and view all the answers

Como verificar se uma chave existe em um dicionário chamado config?

<p>&quot;chave&quot; in config (C)</p> Signup and view all the answers

O que acontece se você tentar acessar uma chave inexistente em um dicionário?

<p>Gera um KeyError (C)</p> Signup and view all the answers

Como tratar exceções em Python?

<p>try: ... except: ... (A)</p> Signup and view all the answers

O que é um ValueError em Python?

<p>Um erro que ocorre quando uma função recebe um argumento com tipo correto, mas valor inadequado (E)</p> Signup and view all the answers

O que a cláusula finally faz em um bloco try-except?

<p>Executa sempre, independentemente de ocorrer uma exceção (A)</p> Signup and view all the answers

Como importar um módulo chamado math em Python?

<p>import math (C)</p> Signup and view all the answers

Qual a função do módulo random em Python?

<p>Gerar números aleatórios (B)</p> Signup and view all the answers

Flashcards

What is variable?

A named storage location that holds a value.

Integer data type

The 'int' type stores whole numbers.

Modulo Operator (%)

Finds the remainder of a division.

What does ** do?

Calculates a number raised to a power.

Signup and view all the flashcards

String Concatenation

Joins strings together.

Signup and view all the flashcards

What is 'if'?

Keyword to define a conditional statement.

Signup and view all the flashcards

What is == ?

Tests for equality.

Signup and view all the flashcards

What is while loop?

Repeats a block of code while a condition is true.

Signup and view all the flashcards

What does continue do?

Skips the rest of the current loop iteration.

Signup and view all the flashcards

What is a list?

An ordered, mutable collection of items.

Signup and view all the flashcards

Study Notes

Variables and Data Types

  • To correctly declare a variable, assign the value "João" directly to the variable name: nome = "João".
  • The int data type stores integer numbers
  • Given the code x = 5.0, the type of the variable x is float.
  • The expression type("42") results in str, indicating the data type is string
  • To transform the integer 10 into a decimal (float), use float(10).

Operators and Expressions

  • The result of the expression 10 % 3 is 1 because it calculates the remainder of the division.
  • The % operator calculates the remainder of a division.
  • The ** operator calculates the power of a number.
  • The expression 2 + 3 * 4 results in 14 because multiplication is performed before addition.
  • The result of "Python" + " " + "é legal" is "Python é legal".

Conditional Structures

  • The keyword if defines a condition in Python.
  • The symbol == represents equality.
  • The correct structure for a conditional block is if condition: commands.
  • The correct way to write an if-else block is if condition: commands else: commands.
  • A logical operator combines boolean conditions.

Repetition Structures

  • The for structure repeats a code a specific number of times.
  • A loop that goes through the numbers 1 to 10 uses for i in range(1, 11):.
  • The command break immediately ends a loop.
  • for is used to traverse sequences, while while executes as long as a condition is true; this is the primary difference between them
  • The command continue jumps to the next iteration in a loop.

Lists and Collections

  • An empty list can be created using list() or [].
  • To access the third element of a list called frutas, use frutas[2].
  • The append() method adds an element to the end of a list.
  • The length of a list called alunos is obtained using len(alunos).
  • The result of [1, 2, 3] + [4, 5] is [1, 2, 3, 4, 5].

Functions

  • A function is defined in Python using def minhaFuncao():.
  • A function parameter is a value sent to a function when it is called.
  • To call a function named calcular that takes two arguments, use calcular(arg1, arg2).
  • The keyword return returns a value from a function.
  • If a function doesn't have a return instruction, it returns None.

Strings

  • The first character of a string called texto is accessed using texto[0].
  • To convert a string to uppercase, use the upper() method.
  • The split() method divides a string into a list of substrings.
  • To verify if a string contains a substring, use "string" in "substring".
  • An f-string is a string that allows including Python expressions inside curly braces {}.

Input and Output

  • The input() function obtains user input.
  • To display a message on the screen, use print("Mensagem").
  • The correct way to format the output to display the value of the variable idade is print(f"Idade: {idade}").
  • To read an integer number from user input, use int(input()).
  • If you use input() without converting the result, the program returns a string.

Dictionaries

  • An empty dictionary is created using dict() or {}.
  • To access the value associated with the key "nome" in a dictionary called pessoa, use pessoa["nome"] or pessoa.get("nome").
  • A new key-value pair is added to a dictionary using dicionario[chave] = valor.
  • To check if a key exists in a dictionary called config, use "chave" in config.
  • If you try to access a non-existent key in a dictionary, a KeyError is raised.

Errors and Exceptions

  • Exceptions in Python are handled using try: ... except: ....
  • A ValueError occurs when a function receives an argument with the correct type but an inappropriate value.
  • The finally clause in a try-except block always executes, regardless of whether an exception occurs or not.

Modules and Libraries

  • To import a module called math, use import math.
  • The random module generates random numbers.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser