Fundamentos de Python
Fundamentos e sintaxe básica da linguagem Python com exemplos práticos de código.
Cartões · 60
- Print to console
- print('Hello, World!')
- Variable assignment
- x = 10 name = 'Alice'
- Multiple assignment
- a, b = 1, 2
- Formatted string (f-string)
- name = 'Bob' print(f'Hello, {name}!')
- User input
- user_name = input('Enter your name: ')
- Type casting to integer
- num = int('42')
- Type casting to string
- text = str(100)
- Check variable type
- print(type(42)) # <class 'int'>
- Single-line comment
- # This is a single line comment
- Multi-line string or comment
- text = '''This spans multiple lines'''
- Arithmetic division vs floor division
- print(7 / 2) # 3.5 print(7 // 2) # 3
- Modulus operator
- remainder = 10 % 3 # 1
- Exponentiation
- power = 2 ** 3 # 8
- Conditional if-elif-else
- if x > 0: print('pos') elif x < 0: print('neg') else: print('zero')
- Ternary operator
- status = 'adult' if age >= 18 else 'minor'
- Logical operators (and, or, not)
- if x > 0 and not is_closed: print('Open and positive')
- While loop
- i = 0 while i < 3: print(i) i += 1
- For loop with range
- for i in range(5): print(i) # 0 to 4
- Loop with break
- for n in range(10): if n == 5: break
- Loop with continue
- for n in range(5): if n == 2: continue print(n)
- Defining a function
- def greet(name): return f'Hi, {name}'
- Function with default arguments
- def power(base, exp=2): return base ** exp
- Arbitrary positional arguments (*args)
- def total(*nums): return sum(nums)
- Arbitrary keyword arguments (**kwargs)
- def show_info(**kwargs): print(kwargs)
- Lambda function
- square = lambda x: x ** 2 print(square(4)) # 16
- Create a list
- fruits = ['apple', 'banana', 'cherry']
- Append item to list
- items = [1, 2] items.append(3)
- Insert item at specific index
- items = ['a', 'c'] items.insert(1, 'b')
- Remove item from list by value
- items = ['a', 'b', 'c'] items.remove('b')
- Pop item from list
- items = [1, 2, 3] last = items.pop()
- List slicing
- nums = [0, 1, 2, 3, 4] print(nums[1:4]) # [1, 2, 3]
- List comprehension
- squares = [x**2 for x in range(5)]
- List comprehension with filter
- evens = [x for x in range(10) if x % 2 == 0]
- Create a tuple
- point = (10, 20)
- Tuple unpacking
- x, y = (10, 20)
- Create a dictionary
- user = {'name': 'Ana', 'age': 25}
- Access dictionary with get
- age = user.get('age', 0)
- Iterate dictionary keys and values
- for k, v in user.items(): print(k, v)
- Dictionary comprehension
- squares = {x: x**2 for x in range(3)}
- Create a set
- unique_ids = {1, 2, 2, 3} # {1, 2, 3}
- Set union and intersection
- a = {1, 2} b = {2, 3} print(a | b) # union print(a & b) # inter
- String length
- length = len('Python') # 6
- String split and join
- words = 'a,b,c'.split(',') joined = '-'.join(words)
- String strip whitespace
- clean = ' hello '.strip() # 'hello'
- Check substring presence
- if 'py' in 'python': print('Found!')
- Try-except error handling
- try: res = 10 / 0 except ZeroDivisionError: res = None
- Try-except-finally block
- try: f = open('file.txt') finally: print('Execution finished')
- Raise an exception
- if age < 0: raise ValueError('Age cannot be negative')
- Read file with context manager
- with open('data.txt', 'r') as f: content = f.read()
- Write text to a file
- with open('out.txt', 'w') as f: f.write('Hello file!')
- Import a module
- import math print(math.sqrt(16)) # 4.0
- Import specific function from module
- from random import randint val = randint(1, 6)
- Define a class with __init__
- class Dog: def __init__(self, name): self.name = name
- Class method and self
- class Cat: def speak(self): return 'Meow'
- Class inheritance
- class Animal: pass class Dog(Animal): pass
- Enumerate a sequence
- for index, value in enumerate(['a', 'b']): print(index, value)
- Zip multiple iterables
- names = ['a', 'b'] scores = [1, 2] combined = list(zip(names, scores))
- Any and all built-in checks
- has_true = any([False, True]) all_true = all([True, True])
- Sorted function with key
- words = ['banana', 'pie'] sorted_words = sorted(words, key=len)
- Main guard boilerplate
- if __name__ == '__main__': print('Executed directly')