Intro to py Flashcards
(18 cards)
What is a variable in Python?
A variable is a name that refers to a value stored in memory.
```python
x = 42
name = “"”Alice”””
~~~
How does assignment work?
=
binds the object on the right to the variable name on the left. Re‑assigning changes the reference.
What is dynamic typing?
A variable can refer to objects of different types at runtime.
```python
n = 10 # int
n = “"”ten””” # now str
~~~
Which built-in function shows an object’s type?
type(obj)
returns the class of the object.
```python
print(type(3.14)) # <class ‘float’>
~~~
List the core arithmetic operators introduced in Chapter 2.
+ - * / ** // %
Which operator has the highest arithmetic precedence?
Exponentiation **
; parentheses override all precedence rules.
Show an example mixing //
and %
.
```python
minutes = 143
hours = minutes // 60 # 2
left = minutes % 60 # 23
~~~
How do you print text and variables together?
Use commas in print()
or f‑strings.
```python
age = 30
print(““Age:””, age) # comma style
print(f”“Age: {age}””) # f‑string
~~~
What are triple-quoted strings used for?
Multiline text or docstrings.
```python
doc = “””"”Line 1
Line 2”””””
How do you read keyboard input?
input(prompt)
returns a str; convert if needed.
```python
age = int(input(““Age? “”))
~~~
Write an if–else
that checks if a number is positive.
```python
n = int(input(““Number: “”))
if n > 0:
print(““Positive””)
else:
print(““Zero or negative””)
~~~
List all comparison operators covered.
== != < <= > >=
What does indentation signify in Python?
Indentation defines code blocks; all lines in the same block must align consistently.
Give a one-line conditional expression (ternary).
```python
parity = ““even”” if n % 2 == 0 else ““odd””
~~~
Which standard‑library module provides basic statistics?
statistics
.
```python
from statistics import mean, median
nums = [10, 3, 8]
print(mean(nums)) # 7.0
print(median(nums)) # 8
~~~
Coding Exercise ① – simple calculator
Write a script that asks for two numbers and prints their sum, difference, product, and quotient.
Sample solution:
```python
a = float(input(““First number: “”))
b = float(input(““Second number: “”))
print(““Sum:””, a + b)
print(““Difference:””, a - b)
print(““Product:””, a * b)
if b != 0:
print(““Quotient:””, a / b)
else:
print(““Cannot divide by zero””)
~~~
Coding Exercise ② – temperature classifier
Ask the user for a Celsius temperature. Print “Cold” if below 10 °C, “Warm” if 10–25 °C, otherwise “Hot.”
Sample solution:
```python
temp = float(input(““Temperature °C: “”))
if temp < 10:
print(““Cold””)
elif temp <= 25:
print(““Warm””)
else:
print(““Hot””)
~~~