Python Exam 1: Variables, Types, and Operators (10 mixed exercises)

Python Exam 1: Language Basics

Test your skills in Python fundamentals, including variables, printing, and working with strings and numbers.

Exercise 1 Print & Comments

Write a simple Python script:

  1. Use `print` to output "Hello, World!".
  2. Add a single-line comment that explains the code.
Solution
# This prints a greeting
print("Hello, World!")
Exercise 2 Variables

Define the following variables:

  1. A variable `x` with the value 5.
  2. A variable `y` with the value "John".
  3. Print the value of each variable.
Solution
x = 5
y = "John"
print(x)
print(y)
Exercise 3 Data Types

Identify data types:

  1. Define `x = 5`.
  2. Define `y = 2.8`.
  3. Define `z = "Hello"`.
  4. Use `type()` to print the type of each variable.
Solution
x = 5
y = 2.8
z = "Hello"

print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'str'>
Exercise 4 Casting

Convert between data types:

  1. Convert `2.8` to an integer.
  2. Convert `3` to a float.
  3. Convert `5` to a string.
Solution
x = int(2.8)   # 2
y = float(3)   # 3.0
z = str(5)     # "5"
Exercise 5 Strings

Manipulate strings:

  1. You have `txt = " Hello World "`.
  2. Remove leading/trailing spaces with `strip`.
  3. Convert the text to uppercase with `upper`.
  4. Replace "H" with "J" using `replace`.
Solution
txt = " Hello World "

print(txt.strip())        # "Hello World"
print(txt.upper())        # " HELLO WORLD "
print(txt.replace("H", "J")) # " Jello World "
Exercise 6 Arithmetic Operators

Perform the following operations:

  1. Print the result of `10 + 5`.
  2. Print the result of `10 / 2`.
  3. Print the result of `2` raised to `3` (`**`).
  4. Print the integer division result of `15 // 2`.
Solution
print(10 + 5)   # 15
print(10 / 2)   # 5.0
print(2 ** 3)   # 8
print(15 // 2)  # 7
Exercise 7 User Input

Interact with the user:

  1. Ask the user for their name using `input()`.
  2. Print "Hello" followed by the entered name.
Solution
username = input("Enter username:")
print("Hello " + username)
Exercise 8 F-Strings

Combine variables with text:

  1. You have `age = 36`.
  2. Use an f-string to print "My name is John, and I am 36".
Solution
age = 36
txt = f"My name is John, and I am {age}"
print(txt)
Exercise 9 Booleans

Evaluate the following expressions:

  1. Print the result of `10 > 9`.
  2. Print the result of `10 == 9`.
  3. Print `bool("Hello")` (is a non-empty string True?).
Solution
print(10 > 9)        # True
print(10 == 9)       # False
print(bool("Hello")) # True
Exercise 10 Multiple Assignment

Assign multiple variables in one line:

  1. Assign "Orange", "Banana", "Cherry" to `x`, `y`, `z` respectively.
  2. Print each variable.
Solution
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Smart Editor

Write code and see the result instantly

Try it free